Statements
In C, statements are the building blocks of a program. They perform actions and can control the flow of execution. Here’s an overview of different types of statements in C:
1. Expression Statements
These are the most basic statements and typically involve variable assignments, function calls, or any expressions that perform an action.
x = 5; // Assignment statement
printf(“Hello, World!\n”); // Function call
2. Compound Statements
Also known as blocks, these group multiple statements together. They are enclosed in curly braces {}
.
{
int a = 10;
int b = 20;
printf(“Sum: %d\n”, a + b);
}
Selection Statements
These allow for decision-making in your code. The most common are if
, else
, and switch
.
- If Statement:
if (x > 0)
{
printf("x is positive.\n");
}
else
{
printf("x is non-positive.\n");
}
- Switch Statement:
switch (day)
{
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
default:
printf("Other day\n");
}
4. Iteration Statements
These enable looping. The most common loops are for
, while
, and do while
.
- For Loop:
for (int i = 0; i < 5; i++)
{
printf("%d\n", i);
}
- While Loop:
int i = 0;
while (i < 5)
{
printf("%d\n", i);
i++;
}
- Do While Loop:
int i = 0;
do
{
printf("%d\n", i);
i++;
}
while (i < 5);
5. Jump Statements
These alter the flow of control in the program. Common jump statements include break
, continue
, and return
.
- Break Statement: Exits a loop or switch statement.
for (int i = 0; i < 10; i++)
{
if (i == 5) break; // Exit the loop when i is 5
}
- Continue Statement: Skips the current iteration of a loop and continues with the next iteration.
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0) continue; // Skip even numbers
printf("%d\n", i); // Print odd numbers
}
- Return Statement: Exits a function and can return a value.
int sum(int a, int b)
{
return a + b; // Return the sum
}