Skip to main content

Control Statements in C


Control statements enable us to specify the flow of program control; ie, the order in which the instructions in a program must be executed. They make it possible to make decisions, to perform tasks repeatedly or to jump from one section of code to another.
There are four types of control statements in C:
  1. Decision making statements
  2. Selection statements
  3. Iteration statements
  4. Jump statements
1.Decision Making Statement: the if-else Statement
The if-else statement is used to carry out a logical test and then take one of two possible actions depending on the outcome of the test (ie, whether the outcome is true or false).
Syntax:
if (condition)
{
statements
}
else
{
statements
}
If the condition specified in the if statement evaluates to true, the statements inside the if-block are executed and then the control gets transferred to the statement immediately after the if-block. Even if the condition is false and no else-block is present, control gets transferred to the statement immediately after the if-block.
The else part is required only if a certain sequence of instructions needs to be executed if the condition evaluates to false. It is important to note that the condition is always specified in parentheses and that it is a good practice to enclose the statements in the if block or in the else-block in braces, whether it is a single statement or a compound statement.
The following program checks whether the entered number is positive or negative.
#include<stdio.h>
int main( )
{
int a;
printf("n Enter a number:");
scanf("%d",&a);
if(a>0)
{
printf("n The number %d is positive.",a);
}
else
{
printf("The number %d is negative.",a);
}
return 0;
}
Nested if and if-else Statements
It is also possible to embed or to nest if-else statements one within the other. Nesting is useful in situations where one of several different courses of action need to be selected.

The general format of a nested if-else statement is:if(condition1)
{
// statement(s);
}
else if(condition2)
{
//statement(s);
}
.
else if (conditionN)
{
//statement(s);
}
else
{
//statement(s);
}

The above is also called the if-else ladder. During the execution of a nested if-else statement, as soon as a condition is encountered which evaluates to true, the statements associated with that particular if-block will be executed and the remainder of the nested if-else statements will be bypassed. If neither of the conditions are true, either the last else-block is executed or if the else-block is absent, the control gets transferred to the next instruction present immediately after the else-if ladder.

The following program makes use of the nested if-else statement to find the greatest of three numbers.#include<stdio.h>
int main( )
{
int a, b,c;
a=6,b=5, c=10;
if(a>b)
{
if(b>c)
{
printf("nGreatest is: " , a);
}
else if(c>a)
{
printf("nGreatest is: ", c);
}
}
else if(b>c) //outermost if-else block
{
printf("nGreatest is: " , b);
}
else
{
printf("nGreatest is: " , c);
}
return 0;
}
2.Selection Statement: the switch-case Statement
A switch statement is used for multiple way selections that will branch into different code segments based on the value of a variable or expression. This expression or variable must be of integer data type.
Syntax:switch (expression)
{
case value1:
      code segment1;
       break;
case value2:
      code segment2;
      break;

case valueN:
      code segmentN;
       break;
default:
         default code segment;
}

The value of this expression is either generated during program execution or read in as user input.
The case whose value is the same as that of the expression is selected and executed. The optional
default label is used to specify the code segment to be executed when the value of the expression
does not match with any of the case values.
The break statement is present at the end of every case. If it were not so, the execution would continue on into the code segment of the next case without even checking the case value

Example: a program to print the day of the week.
#include<stdio.h>
int main( )
{
int day;
printf("nEnter the number of the day:");
scanf("%d",&day);
switch(day)
{
case 1: printf("Sunday");
           break;
case 2:
             printf("Monday");
             break;
case 3:
             printf("Tuesday");
             break;
case 4:
           printf("Wednesday");
           break;
case 5:
            printf("Thursday");
            break;
case 6:
          printf("Friday");
          break;
case 7:
          printf("Saturday");
          break;
default:
         printf("Invalid choice");
}
return 0;
}
All programs written using the switch-case statement can also be written using the if-else statement.However, If you need to select among a large group of values, a switch statement will run much faster than a set of nested ifs. The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression.The switch statement must be used when one needs to make a choice from a given set of choices. The switch case statement is generally used in menu-based applications.
3.Iteration Statement(loops)Loops are used in programming to repeat a specific block until some end condition is met. There are three loops in C programming:

for loop
while loop
do...while loop

for LoopThe syntax of for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// statements
}

The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated. But if the test expression is true (nonzero), statements inside the body of for loop is executed and the update expression is updated.
This process repeats until the test expression is false.
The for loop is commonly used when the number of iterations is known.

Example: for loop// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d",&num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum+= count;
}
printf("Sum= %d", sum);
return 0;
}
while loop
The syntax of a while loop is:

while (testExpression)
{
//codes
}
where, testExpression checks the condition is true or false before each loop.The while loop evaluates the test expression.If the test expression is true (nonzero), codes inside the body of while loop are exectued. The test expression is evaluated again. The process goes on until the test expression is false.When the test expression is false, the while loop is terminated.// Program to find factorial of a number
// For a positive integer n, factorial = 1*2*3...n
#include <stdio.h>
int main()
{
int number;
long factorial;
printf("Enter an integer: ");
scanf("%d",&number);
factorial= 1;
//loop terminates when number is less than or equal to 0
while(number > 0)
{
factorial*= number; // factorial = factorial*number;
--number;
}
printf("Factorial=%lld", factorial);
return 0;
}
do...while loop
The do..while loop is similar to the while loop with one important difference. The body of do...while loop is executed once, before checking the test expression. Hence, the do...while loop is executed at least once.
Syntax: 
do...while loop

do
{
// codes
}
while (testExpression);
The code block (loop body) inside the braces is executed once.Then, the test expression is evaluated. If the test expression is true, the loop body is executed again. This process goes on until the test expression is evaluated to 0 (false).
When the test expression is false (nonzero), the do...while loop is terminated.// Program to add numbers until user enters zero
#include <stdio.h>
int main()
{
double number, sum = 0;
//loop body is executed at least once
do
{
printf("Entera number: ");
scanf("%lf",&number);
sum+= number;
}
while(number!= 0.0);
printf("Sum= %.2lf",sum);
return 0;
}

4.Jump statements
These statements cause the normal program control to jump to a different point. Normal jump statements are.
break
continue
goto


It is sometimes desirable to skip some statements inside the loop or terminate the loop immediately without checking the test expression.
In such cases, break and continue statements are used.
break Statement
The break statement terminates the loop (for, while and do...while loop) immediately when it is encountered. The break statement is used with decision making statement such as if...else.
Example : break statement// Program to calculate the sum of maximum of 10 numbers
// Calculates sum until user enters positive number
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1;i <= 10; ++i)
{
printf("Entera n%d: ",i); scanf("%lf",&number);
//If user enters negative number, loop is terminated
if(number< 0.0)
{
break;
}
sum+= number; // sum = sum + number;
}
printf("Sum= %.2lf",sum);
return 0;
}

This program calculates the sum of maximum of 10 numbers. It's because, when the user enters negative number, the break statement is executed and loop is terminated.

In C programming, break statement is also used with switch...case statement.

continue StatementThe continue statement skips some statements inside the loop. The continue statement is used with decision making statement such as if...else.
Example : continue statement// Program to calculate sum of maximum of 10 numbers
// Negative numbers are skipped from calculation
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1;i <= 10; ++i)
{
printf("Entera n%d: ",i);
scanf("%lf",&number);
//If user enters negative number, loop is terminated
if(number< 0.0)
{
continue;
}
sum+= number; // sum = sum + number;
}
printf("Sum= %.2lf",sum);
return 0;
}

goto

The goto statement is used to alter the normal sequence of a C program.
Syntax of goto statementgoto label;
... .. ...
... .. ...
... .. ...
label:
statement;

The label is an identifier. When goto statement is encountered, control of the program jumps to label: and starts executing the code.
Example: goto Statement// Program to calculate the sum and average of maximum of 5 numbers
// If user enters negative number, the sum and average of previously entered positive number is displayed
# include <stdio.h>
int main()
{
const int maxInput = 5;
int i;
doublenumber, average, sum=0.0;
for(i=1;i<=maxInput; ++i)
{
printf("%d.Enter a number: ", i);
scanf("%lf",&number);
//If user enters negative number, flow of program moves to label jump
if(number< 0.0)
goto label;
sum+= number; // sum = sum+number;
}
label: average=sum/(i-1);
printf("Sum= %.2f\n", sum);
printf("Average= %.2f", average);
return 0;
}

The use of goto statement may lead to code that is buggy and hard to follow.Also, goto statement allows you to do bad stuff such as jump out of scope.If you think the use of goto statement simplifies your program. By all means use it, otherwise avoid its use.

Comments

Popular posts from this blog

Files in C

A file is a repository of data that is stored in a permanent storage media, mainly in secondary memory. In order to use the files we should learn how to read information from a file and how to write information into a file. A very important concept in C is the stream.The stream is a common logical interface to the various devices( files).A stream is linked to a file while using an open operation. A stream is disassociated from a file while using a close operation. The current location, also referred to as the current position, is the location in a file where the next fie access will occur.There are two types of streams text and binary. The following are some difference between text and binary files ·Text file is human readable because everything is stored in terms of text. In binary file everything is written in terms of 0 and 1, therefore binary file is not human readable. ·A newline(\n) character is converted into the carriage return-linefeed combination before being written to the d…

KTU C programming question paper and evaluation scheme

APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY SECOND SEMESTER B.TECH DEGREE EXAMINATION, MAY 2017 CS 100 COMPUTER PROGRAMMING (CS, IT) SCHEME OF EVALUATION
PART A 1 An identifier is a sequence of characters invented by the programmer or to identify or name a specific object. The sequence of characters may be letters, digits, and special character ‘_’known as an underscore Rules: i)Identifiers should start with alphabets. ii)Identifiers are case sensitive iii)A numeric digit should not be the first character iv)Identifier name should not be a keyword v)Identifier may be of any reasonable length 1mark






2mark 2 Associativity defines the direction, left to right or right to left in which operator act upon its operands Unary operators have associativity is from right to left. For examplein the expression &--x, pre decrement works first and then address of operator works Direction + example<

Linear and Binary Search in C

Searching is one of the most common problems that arise in computing. Searching is the algorithmic process of finding a particular item in a collection of items. A search typically answers either True or False as to whether the item is present. On occasion it may be modified to return where the item is found. Search operations are usually carried out on a key field. Consider searching for a given value k in an array A of size n. There are 2 basic approaches: sequential search and binary search.
Linear (Sequential) Search When data items are stored in a collection such as a list or array , we say that they have a linear or sequential relationship. Each data item is stored in a position relative to the others. In C array, these relative positions are the index values of the individual items. Since these index values are ordered, it is possible for us to visit them in sequence. This process gives rise to our first searching technique, the sequential search. Starting at the first item in …