Control Structures in c

Control Structures in C

Control Structures in C

The structures of a program which affects the order of execution of the statements are called control structures. The normal execution of statements is in sequential fashion but to change the sequential flow, various control structures are used. Broadly, control structures are of three types-

  • Selection /conditional – executes as per choice of action.
  • Iteration – Performs a repetitive action.
  • Jumping – used to skip the action, or particular statements.


Selection/Conditional control structures

Also called conditional control constructs and are used to choose from alternative course of actions based on certain conditions. It has various forms

  • if
  • if-else
  • nested if-else
  • if-else if
  • switch -case

If Statements

If statement tests a condition and if it results in non-zero(true) value then the statements following if are executed.

Syntax

if(condition)
{
                body of if
}

Note :

  • There is no semi colon after if statement
  • The conditional expression of c can have relational (<,<=, >,>=,==,)or logical(&&,||,!) operator but can’t have assignment operator.

Example to print the largest of three numbers

#include
void main()
{
int a,b,c,d;
printf("Enter any three numbers");
if(scanf("%d%d%d",&a,&b,&c))
          {
                d=a;
                if(b%d) d=b;
                if(c%d) d=c;
           }
printf("The largest number is %d",d);
}

Explanation – In the first if statement, it will scan for three variables a,b and c. This if statement will be TRUE only if all three variables are entered through standard input device.

d=a;

 Then value of a is assigned to d.

if(b%d) d=b;

In the second if statement modulus value of b against d is calculated , it will result in non zero if b is greater than d(which is actually value of a). hence value of b would be assigned to d. It actually means that b is greater than a. Now 

if(c%d) d=c;

value of c is compared with b and if it returns as non zero then c is greatest of all. Otherwise b is greatest.

In second and third if statements are false then a is the greatest of all.

if statement does not give any output if condition is false. To get the result for both true and false, if-else statement is used.

If-Else Statement

This control structure tests the if conditions and if it is true then the body of if is executed otherwise body of else is executed. If-else is more complete version as compare to simple if statement where you have statements for TRUE and FALSE conditions.

Syntax

if(condition)
  {
                body of if
}
else
{
                body of else
}

Example

 

#include
void main()
{
int a,b;
printf("Enter any two numbers");
scanf("%d%d",&a,&b);
if(a>b)
                printf("%d is greater than %d",a,b);
else
                printf("%d is greater than %d",b,a);
}

Note: Body of if -else statement should be enclosed in curly braces if it have more than one statements. The same is not mandatory for single statement.

Nested if-else statement

Sometimes, the body of if-else statement may be placed within  another if-else statement then it is called nested if-else statement. This control structure is particularly helpful to simultaneously test more than one conditions. For example a group of friends are planning a picnic on Sunday if it is a sunny day. So here two conditions are simultaneously tested, the day should be sunday and second it should be a sunny day.

Syntax

if(condition1)
{
                if(condition2)
                {
                                body of inner if
                }
                else
                {
                body of inner else
                }
}
else
{
if(condition3)
                {
                                body of inner else if
                }
                else
                {
                body of inner else
                }
}

Example to find out the largest of three numbers.

#include
void main()
{
int a,b,c;
printf("Enter any three numbers");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
                {
                if(a>c) printf("%d is greatest of %d%d%d",a,a,b,c);
                else printf("%d is greatest of %d%d%d",c,a,b,c);
                }
else
                {
                if(b>c) printf("%d is greatest of %d%d%d",b,a,b,c);
                else printf("%d is greatest of %d%d%d",c,a,b,c);
                }
}

If-else if Statement

When you have to evaluate more than two conditions then you need to use if-else if ladder. This control structure is particularly helpful when you have more conditions to evaluate.

Syntax

if(condition1)
body of if
else if(condition2)
body of else if
else if(condition3)
body  of else if
else
body of else

Example to demonstrate grade of a student

#include
void main()
{
int marks;
printf("Enter the marks");
scanf("%d",&marks);
if(marks>=80)
printf("Excellent");
else if(marks>=70)
printf("A grade");
else if(marks>=60)
printf("B grade");
else if(marks>=50)
printf("Pass");
else
printf("Work Hard! You have failed");
}

Switch Statement

Switch control structure can cut short the long series of if-else if statements . The switch statement can select a case from several available cases. The case can be integral expression(int or char) only. If the case value matches with any of the available cases then statements below it are executed until break statement is encountered. If no matching case is found then default label is executed. If no default label has been defined then switch terminates.

Syntax

switch(expression)
{
case item1: action; break;  
case item2: action; break;  
case item3: action; break;  
case item4: action; break;  
default: default action;
}

Example

#include
void main()
{
int day;
printf("Enter the day between 1-7");
scanf("%d",&day);
switch(day)
                {
                   case 1:
                   printf("Monday"); break;  
                   case 2:
                    printf("Tuesday"); break;  
                    case 3:
                    printf("Wednesday");  break;  
                    case 4:
                    printf("Thursday");  break;  
                    case 5:
                    printf("Friday");  break;
                    case 6:
                    printf("Saturday");  break;
                    case 7:
                    printf("Sunday");  break;
                    default:
                    printf("Invalid choice enter value between 1-7");
                }
}

What are the differences between if and switch statement?

  1. If statement can test any type of expression (integral, floating point, logical, relational etc.) but switch can test only integral expression only.
  2. If statement encloses multiple statements inside curly braces but you can never put multiple statements of switch inside curly braces.
  3. Break can be used inside switch body but can’t be used inside if body.

Iterations

Iterations means repetitions. When you wish to repeat a task more than once then it is called iterative task. The iterative tasks can be performed in c language through loops.  Looping means to execute a task  repeatedly and simultaneously checking the condition when to stop.  

Loops control structures can be used to –

  • take same action on each character of a file until end of file is reached.
  • take the same action until the number becomes zero.
  • take the same action on each elements of an array until all array elements are processed.
  • take the same action until newline character is reached
  • take the same action on each item in the data set.
  • take the same action until the file gets printed.

C Language has three types of loops

  1. for loop
  2. while loop
  3. do-while loop

For Loop

For loop steps through a series of specified action once for each value monitoring the specified condition to terminate each time.

Syntax

for(initial_exp;cond_exp;modifier_exp)

loop body

here initial_exp – initialization expression. It initializes a variable with initial value

cond_exp – conditional expression. This condition decides whether to continue the loop or exit it.

modifier_exp – modifier expression. It changes the value of the variable after each iteration.

Example to write a counting from 0 to the value of i

#include
void main()
{
int x,i;
printf("Enter the value up to which you wish to write counting");
scanf("%d",&x);
for(i=0;i<=x;i++)
printf("%d\n",i);
}

Infinite Loop 

Infinite loop is a control structure which keep on executing it’s body indefinitely. Either it will keep on giving output continuously or no output at all. This kind of loops are also called indefinite or endless loop. 

Note – A loop control structure should always be finite means  it should terminate after some iterations, else it becomes infinite loop. Infinite loops are highly undesirable and due care should be taken to keep the loops finite.

for loop usage

  1           for loop control structure is best suited for the situations where we know in advance how many times the loop will execute.

2              for loop control structure is natural choice for processing the array elements of all dimensions

example

  #include
void main()
{
int i,j;
int a[2][2]={{1,2},{3,4}};
printf("Processing array elements \n");
for(i=0;i<2;i++)
        {
                for(j=0;j<2;j++)
                                printf("%d \t",a[i][j]);
                printf("\n");
        }
}

Conditions for infinite for loop

  • A for loop without conditional test is infinite for loop
  • A for loop whose conditional test is true for loop variables initial value but it’s not modified then loop becomes infinite loop.

While Loop

While loop is also called pre-test loop. It first tests the specified conditional expression and as long as the conditional expression evaluates to non-zero, action is taken.

Syntax

while(conditional expression)

body of while

here conditional expression can be condition or expression. so

while(1)

while(x=x+1)

while(n–) are all legal conditional expression in while loop.

Important points about while loop

  • While loop is mostly suited in the situations where it is not known for how many times the loop will continue executing. e.g. while(number!=0)
  • If conditional expression in a while loop is always evaluated as non zero then it infinite while loop. e.g. while(1) or while(!0).
  • Never us assignment operator in place of equality operator in the test condition
  • If the conditional expression evaluates to zero in the very starting then loop body will not execute even once.

Example – to reverse a positive number

 #include
void main()
{
int num, rem, num1=0;
printf("Enter a number");
scanf("%d",&num);
while(num)
          {
                rem=num%10;
                num1=num1*10+rem;
                num/=10;
          }
printf("The reversed number is %d",num1);
}

Do-while loop

Also called post test loop because it executes it’s body at least once without testing specified conditional expression and then makes the test. Do-while terminates when the conditional expression evaluates to zero.

Syntax

do
{
     body
} while(condition);

Notice the semicolon after condition

Important points about do-while loop

  • A do-while loop tests the condition after executing the body at least once.
  • A do-while will make minimum iteration as 1 even if the condition is false.
  • A do-while loop is good choice for processing menus because of it’s first task then test nature.

Difference between while and do-while loops

SNo While Do-while
1 While is a pre-test loop. It tests the condition first, if condition is true loop body will execute Do-while is a post test loop. It executes its body at least once without testing the condition
2 The minimum number of iterations is 0 The minimum number of iterations is 1
3 While and for loops are inter changeable in almost every situation Do-while and for loops are not inter changeable in most of the situations

3              Jumping

There are three jumping statements

  1. break
  2. continue
  3. goto

Break Statement

Break is a jumping statement that when encountered in a –

  • Switch block – skips the rest of the switch block at once and jump to the next statement just after the switch block
  • Loop- skips the rest of the loop statements and jumps to the next statement just after loop body

Example – To find the given number as prime

#include
#include
void main()
{
int n,i,s;
printf("Enter a number ");
scanf("%d",&n);
s=sqrt(n);
for(i=2;i<=s;i++)
                {
                   if(n%i==0) break;
                }
if(i>s)
                printf("%d is a prime number",n);
else
                printf("%d is a not a prime number",n);
}

Continue Statement

Continue is also a jump statement which skips rest of the statements in the loop body and jumps to the next iteration. It differs from break in a way that break simply comes out of a block in which it is defined but continue just skips the rest of statements after it and continue to execute the loop body with next iteration.

Goto statement

Although goto statement is avoided in c language still it is available in two forms unconditional goto and conditional goto. it is a jump statement which causes the control to jump from the place where goto is encountered to the place indicated by label.

  • Unconditional goto – Used to make jump to the specified label without testing a condition.

Syntax

goto labelname;
...
labelname:
statements;
  • Conditional goto – Used to make jump to the specified label after testing condition.

Syntax

if(condition)
goto labelname;
...
labelname:
statements;

 

Similar Posts :      Input/Output functions in C           Operators and Expressions in C           Variables in C

You may also like :

Let us Learn JavaScript from Step By Step       Reverse Charge Mechanism in Tally.ERP9    What is New in HTML5

To Download Official TurboC Compiler from here

Difference between break and continue

1) Break causes exit from the loop leaving rest of the iterations while continue causes control to continue with the next iteration
2) break can be used in all control structures (for, while, do-while loops and switch statements ) except constructs of if family. Continue can be used only in the looping constructs but not in switch and if family.
3) Break can be used inside an infinite loop to stop them. Continue can be used inside infinite loops to skip one iterations but it can not stop it.

Similarities between break and continue

1) Both are used to jump from one place to another by skipping rest of the statements after them.
2) Both can be used inside the loops.
3) Inside a loop both can be used with if or switch statements.

Infinite Loops

An infinite loop is a loop that keeps on executing its body as there is not control . Reason for loop to be infinite are –
1 When conditional expression always evaluates to TRUE
2 No condition is imposed to come out of the loop
3 No modifier expression to modify the loop variable

How to stop an infinite loop

By pressing Ctrl+break keys
5 1 vote
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
1 year ago

[…] in C                                &n…Input/Output functions in […]

trackback
1 year ago

[…]         Control Structures in C                    Arrays in […]

Please Subscribe to Stay Connected

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

DigitalSanjiv will use the information you provide on this form to be in touch with you and to provide updates and marketing.
Share via
Copy link
Powered by Social Snap
%d bloggers like this: