c programming exercises
C Programming Exercise with Explanations
Step 1: Declare and Initialize Variables
#include <stdio.h>
int main() {
int num1 = 5;
int num2 = 10;
int sum = num1 + num2;
printf("The sum of %d and %d is %d\n", num1, num2, sum);
return 0;
}
- In this step, we declare and initialize three integer variables:
num1
,num2
, andsum
. We assign the values 5 and 10 tonum1
andnum2
respectively. Then, we calculate the sum ofnum1
andnum2
and store it in the variablesum
. Finally, we print the sum using theprintf
function. Step 2: User Input and Conditional Statement
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num % 2 == 0) {
printf("%d is even\n", num);
} else {
printf("%d is odd\n", num);
}
return 0;
}
- In this step, we declare an integer variable
num
to store user input. We prompt the user to enter a number usingprintf
and then usescanf
to read the input and store it innum
. Next, we use a conditional statement (if-else
) to check if the number is even or odd and print the result accordingly. Step 3: Looping Structure
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
- In this step, we use a
for
loop to print the numbers from 1 to 5. The loop initializes the variablei
to 1, then executes the loop body as long asi
is less than or equal to 5, and incrementsi
by 1 in each iteration. Inside the loop, we useprintf
to print the value ofi
. Step 4: Function Definition and Call
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int num1 = 5, num2 = 3;
int result = add(num1, num2);
printf("The sum of %d and %d is %d\n", num1, num2, result);
return 0;
}
- In this step, we define a function
add
that takes two integer parametersa
andb
and returns their sum. Inside themain
function, we declare two integer variablesnum1
andnum2
and initialize them with values 5 and 3. We then call theadd
function withnum1
andnum2
as arguments and store the result in the variableresult
. Finally, we print the result usingprintf
. Step 5: Array Declaration and Access
#include <stdio.h>
int main() {
int arr[5] = {2, 4, 6, 8, 10};
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
- In this step, we declare an integer array
arr
with 5 elements and initialize it with the values 2, 4, 6, 8, and 10. Then, we use afor
loop to iterate through the array and print each element usingprintf
. Step 6: Structure Definition and Usage
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p1 = {3, 5};
printf("Coordinates of p1: (%d, %d)\n", p1.x, p1.y);
return 0;
}
- In this step, we define a structure
Point
with two integer membersx
andy
. Inside themain
function, we declare a variablep1
of typePoint
and initialize it with the coordinates (3, 5). Then, we print the coordinates ofp1
usingprintf
.