
C Program
C programming is a versatile language that allows us to solve a wide range of problems, from simple arithmetic operations to complex algorithms. In this tutorial, we will explore two interesting examples:
-
Sum of Odd Numbers – A simple program to calculate the sum of all odd numbers up to a given number using loops and basic input/output in C.
-
Magic Square Generation – A program to generate a magic square of a given size. A magic square is a square matrix in which the sum of every row, column, and diagonal is the same. This demonstrates the use of arrays, loops, and logic implementation in C.
These examples will help you strengthen your understanding of loops, arrays, and algorithmic thinking in C programming.
#include <stdio.h>
int oddsum(int n){
int i, sum=0;
printf("Enter Number: ");
scanf("%d", &n);
for(i=1; i<=n; i+=2)
{
sum += i;
}
printf("Sum of odd numbers = %d", sum);
return 0;
}
int main()
{
oddsum(12);
}
#include<stdio.h>
#include<string.h>
void generateSquare(int n)
{
int magicSquare[n][n];
memset(magicSquare, 0, sizeof(magicSquare));
int i = n/2;
int j = n-1;
for (int num=1; num <= n*n; )
{
if (i==-1 && j==n) //3rd condition
{
j = n-2;
i = 0;
}
else
{
if (j == n)
j = 0;
if (i < 0)
i=n-1;
}
if (magicSquare[i][j]) //2nd condition
{
j -= 2;
i++;
continue;
}
else
magicSquare[i][j] = num++; //set number
j++; i--; //1st condition
}
printf("The Magic Square for n=%d:\nSum of "
"each row or column %d:\n\n", n, n*(n*n+1)/2);
for (i=0; i<n; i++)
{
for (j=0; j<n; j++)
printf("%3d ", magicSquare[i][j]);
printf("\n");
}
}
int main()
{
int n = 3;
generateSquare (n);
return 0;
}
- END -



