What do you understand by a decision-control statement? Give an example of each. 8
In a C program, a decision causes a one-time jump to a different part of the program, depending on the value of an expression. Decisions in C can be made in several ways. The most important is with the if…else statement, which chooses between two alternatives. This statement can be used without the else, as a simple if statement.
Another decision control statement, switch, creates branches for multiple alternative sections of code, depending on the value of a single variable.
The if Statement
It is used to execute an instruction or sequence/block of instructions only if a condition is fulfilled. In if statements, expression is evaluated first and then, depending on whether the value of the expression (relation or condition) is “true” or “false”, it transfers the control to a particular statement or a group of statements.
Write a program to award grades to students depending upon the criteria mentioned
- • Marks less than or equal to 50 are given “D” grade
- • Marks above 50 but below 60 are given “C” grade
- • Marks between 60 to 75 are given “B” grade
- • Marks greater than 75 are given “A” grade.
/* Program to award grades */
printf(“Enter the total marks of a student:\n”);
if (result <= 50)
else if (result <= 60)
else if (result <= 75)
Enter the total marks of a student:
Different forms of implementation if-statement are:
- • Simple if statement
- • If-else statement
- • Nested if-else statement
- • Else if statement
The Switch Statement
Its objective is to check several possible constant values for an expression, something similar to what we had studied in the earlier sections, with the linking of several if and else if statements. When the actions to be taken depending on the value of control variable, are large in number, then the use of control structure Nested if…else makes the program complex.
Write a program that performs the following, depending upon the choice selected by the user.
- calculate the square of number if choice is 1
- calculate the cube of number if choice is 2 and 4
- calculate the cube of the given number if choice is 3
- otherwise print the number as it is
printf(“\n Enter any number:\n “);
printf(“Choice is as follows:\n\n”);
printf(“1. To find square of the number\n”);
printf(“2. To find square-root of the number\n”);
printf(“3. To find cube of a number\n”);
printf(“4. To find the square-root of the number\n\n”);
printf(“Enter your choice:\n”);
case 1 : printf(“The square of the number is %d\n”,n*n);
case 2 :
case 4 : printf(“The square-root of the given number is %f”,sqrt(n));
case 3: printf(“ The cube of the given number is %d”,n*n*n);
default : printf(“The number you had given is %d”,n);
Enter any number:
Choice is as follows:
1. To find square of the number
2. To find square-root of the number\n”);
3. To find cube of a number
4. To find the square-root of the number
Enter your choice:
The square-root of the given number is 2