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(a>c)
{
printf("Greatest is:%d " , a);
}
else if(c>a)
{
printf("Greatest is: %d", c);
}
}
else if(b>c) //outermost if-else block
{
printf("Greatest is:%d" , b);
}
else
{
printf("Greatest is: %d" , 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 executed. 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;
--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("Enter a 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 switch

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 Statement
The 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("Enter a 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 statement
goto 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.

Sample Programs( all university questions)
1.Print factors of a number
#include <stdio.h>
main()
{
int n,i;
printf("Enter the number...\n");
scanf("%d",&n);
printf("Factors of the number\n");
for(i=1;i<=n;i++)
if(n%i==0)
printf("%d\n",i);
}
Note: an efficient way is to go up to n/2
2.Sum of the digits of a number
#include <stdio.h>
main()
{
int n,i,s=0,d;
printf("Enter the number...\n");
scanf("%d",&n);
while(n!=0)
{d=n%10;
s=s+d;
n=n/10;
}
printf("Sum of the digits of the number=%d\n",s);
}
3.Check for perfect number ( Eg: 6,28,496 etc..)
#include <stdio.h>
#include <string.h>
int main()
{
int n,i,s=0;
printf("Enter the number\n");
scanf("%d",&n);
for(i=1;i<=n/2;i++)
{
if(n%i==0)
s=s+i;
}
if(s==n)
printf("%d is a pefect number \n",n);
else
printf("%d is a not a pefect number \n",n);
}
4.Check for prime ( Eg:2,3,5,7,11 etc...)
#include <stdio.h>
#include <string.h>
int main()
{
int n,i,prime=1;
printf("Enter the number\n");
scanf("%d",&n);
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{prime=0;break;}
}
if(prime)
printf("%d is a prime number \n",n);
else
printf("%d is a not a prime number \n",n);
}
5.Fibonacci series up to 100(0 1 1 2 3 5 8 13.....)
#include <stdio.h>
#include <string.h>
int main()
{
int a=0,b=1,c;
printf("Fibonacci series up to 100\n");
printf("%4d%4d",a,b);
while(1)
{
c=a+b;
if(c>100) break;
a=b;
b=c;
printf("%4d",c);
}
}

Comments

Popular posts from this blog

KTU Mandatory C programs for Laboratory and Solutions

LIST OF LAB EXPERIMENTS 1. Familiarization of Hardware Components of a Computer 2. Familiarization of Linux environment – Programming in C with Linux 3. Familiarization of console I/O and operators in C     i) Display “Hello World”     ii) Read two numbers, add them and display their sum     iii) Read the radius of a circle, calculate its area and display it 4. Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))   and display its solution. Read the values of the variables from the user through console 5. Read 3 integer values, find the largest among them. 6. Read a Natural Number and check whether the number is prime or not 7. Read a Natural Number and check whether the number is Armstrong or not 8. Read n integers, store them in an array and find their sum and average 9. Read n integers, store them in an array and search for an element in the    array using an algorithm for Linear Search 10.Read n integers, store them in an array and sort the elements in t

PROGRAMMING IN C KTU EST 102 THEORY AND LAB NOTES

PROGRAMMING IN C  KTU  EST 102  THEORY AND LAB   COMMON FOR ALL BRANCHES About Me Syllabus Theory Syllabus Lab Model Question Paper University Question Papers and evaluation scheme Introduction( Lab) Introduction to C programming Linux History and GNU How to create a bootable ubuntu USB stick Installing  Linux Install Linux within  Windows Virtual Box and WSL Linux Basic Features and Architecture Basic Linux Commands Beginning C Programming Compiling C programs using gcc in Linux Debugging C program using gdb Module 1: Basics of computer hardware and software          Module-1 Reading Material Basics of Computer Architecture Hardware and Software System Software and Application Software  Programming Languages ( High level, Low level and Machine Language) and Translators ( Compiler, Interpreter, Assembler) Algorithm, Flowcharts and Pseudo code Program Development Structured Programming Basics of hardware ( video) Know about Motherboard(video) Know Universal Serial Bus ( USB) - video Lea

Input Output-printf() and scanf()

printf() and scanf() function in C   printf() and scanf() functions are inbuilt library functions in C programming language which are available in C library by default.These functions are declared and related macros are defined in “stdio.h” which is a header file in C language. We have to include “ stdio.h ” file as shown in below to make use of these printf() and scanf() library functions in C program. #include <stdio.h>   printf() function in C   In C programming language, printf() function is used to print the “character, string, float, integer, octal and hexadecimal values” onto the output screen. Here’s a quick summary of the available printf format specifiers:   %c           character %d           decimal (integer) number (base 10) %ld         Long integer %e           exponential floating-point number %f           floating-point number %lf          double number %i            integer (base 10) %o         octal number (base 8) %s         a string of characters %u