Statements in C Language

In C programming language, there are several types of statements that are used to express different actions and control flow in a program. Here are the most common types of statements in C:

  1. Expression Statements: These statements evaluate an expression and typically end with a semicolon (;). The expression can be a function call, assignment, arithmetic operation, or any other valid C expression.

example:

x = 5; // Assignment statement
printf(“Hello”); // Function call statement
x = y + z; // Arithmetic operation statement

 

  1. Compound Statements (Blocks): Compound statements, also known as blocks, are enclosed within curly braces ({}) and can contain multiple statements. They are often used to group statements together and define the scope of variables.

For example:

{
int a = 5;
int b = 10;
int sum = a + b;
printf(“Sum: %d”, sum);
}

 

Control Flow Statements:

  • Conditional Statements: These statements are used to perform different actions based on certain conditions. The common conditional statements in C are:
    • if Statement: Executes a block of code if a given condition is true.
    • if-else Statement: Executes one block of code if a condition is true and another block if it is false.
    • nested if-else Statement: Allows nesting if-else statements within each other to handle multiple conditions.

Example:

int x = 5;
if (x > 0) {
printf(“Positive”);
} else if (x < 0) {
printf(“Negative”);
} else {
printf(“Zero”);
}

3.switch Statement: Evaluates an expression and executes different code blocks based on its value.

Example:

int day = 3;
switch (day) {
case 1:
printf(“Monday”);
break;
case 2:
printf(“Tuesday”);
break;
case 3:
printf(“Wednesday”);
break;
default:
printf(“Invalid day”);
break;
}

4.Loop Statements: These statements allow repetition of a block of code based on a condition.

  • while Loop: Repeats a block of code while a given condition is true.
  • do-while Loop: Repeats a block of code at least once and continues as long as a given condition is true.
  • for Loop: Repeats a block of code for a specified number of times. Examples:

// while loop
int i = 0;
while (i < 5) {
printf(“%d “, i);
i++;
}

// do-while loop
int j = 0;
do {
printf(“%d “, j);
j++;
} while (j < 5);

// for loop
for (int k = 0; k < 5; k++) {
printf(“%d “, k);
}

 

5. Jump Statements: These statements alter the normal flow of control in a program.

  • break Statement: Terminates the nearest loop or switch statement and transfers control to the statement immediately following it.
  • continue Statement: Skips the remaining code in the current iteration of a loop and moves to the next iteration.
  • return Statement: Terminates the execution of a function and returns a value to the calling function. Examples:

// break statement
for (int i = 0; i < 10; i++) {
if (i == 5) {

Related Posts