Introduction to Control Structure



A program is nothing but the execution of sequence of one or more instructions. Quite often, it is desirable to alter the sequence of the statements in the program depending upon certain circumstances. (i.e., we have a number of situations where we may have to change the order of execution of statements based on certain conditions) i.e. Repeat a group of statements until certain specified conditions are met. This involves a kind of decision-making to see whether a particular condition has occurred or not and direct the computer to execute certain statements accordingly. Based on application, it is necessary/essential. To alter the flow of a program .Test the logical conditions .Control the flow of execution as per the selection these conditions can be placed in the program using decision-making statements.

Type of Control Structure 

Ø  Branching(Decission Making): the program chooses to follow one branch or another.

Ø  If

Ø  if else

Ø  if elseif

Ø  nested elseif

Ø  switch case

Ø  Looping:

Ø  While

Ø  do while

Ø  for

Ø  Jumping(Unconditional):

Ø  Goto

Ø  break

Ø  Continue

Ø  return

 Branching(Decission Making)-if

Ø  This is the most simple form of the branching statements.

Ø  It takes an expression in parenthesis and an statement or block of statements.

Ø  if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.

Ø  Syntax:

if (expression)   

statement;                             



Ø  (Or)

if (expression)

  {

    Block of statements;

  }

Branching(Decission Making)-if else

Ø  The if statement may have an optional else block.

Ø  Use the else statement to specify a block of code to be executed if the condition is false.

Fig: Flowchart of if estatement


Ø  Syntax:

if (condition) {

    // run code if test expression is true

}

else {

    // run code if test expression is false 

}

Branching(Decission Making)-if elseif

Ø  Use the else if statement to specify a new condition if the first condition is false.

Ø  Syntax

if (condition1) {

  // block of code to be executed if condition1 is true

}

else if (condition2) {

  // block of code to be executed if the condition1 is false and condition2 is true

}

else {

  // block of code to be executed if the condition1 is false and condition2 is false

}


Fig: Flowchart of if elseif statement 


Branching(Decission Making)-nested if else

Ø  Including numerous if-else statements inside an if and else statement is called nesting.

Ø  The second if and else statements are said to be nested inside the first if and else statement.

Ø  nested if else statements provide clearer decision making when some extra conditions are needed to be checked inside the initial conditions.



 

Program to find the grade of a student

Ø  Take input a mark of the subject from the candidate and according to the following condition we will calculate the grade.

Ø  If marks <50 then the Grade is F

Ø  if marks >=50 <60 then Grade is D

Ø  if marks >=60 <70 then Grade is C

Ø  if marks >=70 <80 then Grade is B

Ø  if marks >=80 <90 then Grade is A

Ø  if marks >=90 then Grade is A+

Solution:

#include<stdio.h>

void main(){

    int marks;

    printf("Enter your marks ");

    scanf("%d",&marks);

    if(marks<0 || marks>100)    {

        printf("Wrong Entry");

    }

    else if(marks<50)    {

        printf("Grade F");

    }

    else if(marks>=50 && marks<60)    {

        printf("Grade D");

    }

else if(marks>=60 && marks<70)    {

        printf("Grade C");

    }

    else if(marks>=70 && marks<80)    {

        printf("Grade B");

    }

    else if(marks>=80 && marks<90)    {

        printf("Grade A");

    }

    else    {

        printf("Grade A+");

    }

}



       

 

 

 





Program to find all possible roots of quadratic equation 
ax2+bx+c.

            #include <math.h>

            #include <stdio.h>

            int main() {

                double a, b, c, discriminant, root1, root2, realPart, imagPart;

                printf("Enter coefficients a, b and c: ");

                scanf("%lf %lf %lf", &a, &b, &c);

                discriminant = b * b - 4 * a * c;

                // condition for real and different roots

                if (discriminant > 0) {

                    root1 = (-b + sqrt(discriminant)) / (2 * a);

                    root2 = (-b - sqrt(discriminant)) / (2 * a);

                    printf("root1 = %.2lf and root2 = %.2lf", root1, root2);

                }

            // condition for real and equal roots

                else if (discriminant == 0) {

                    root1 = root2 = -b / (2 * a);

                    printf("root1 = root2 = %.2lf;", root1);

                }

                // if roots are not real

                else {

                    realPart = -b / (2 * a);

                    imagPart = sqrt(-discriminant) / (2 * a);

                    printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart);

                }

                return 0;

            }

Program to find the second largest number among given three number.

#include<stdio.h>

int main() {

    double a, b, c;

    printf("Enter 3 numbers:\n");

    scanf("%lf%lf%lf", &a, &b, &c); 

    // a is the largest

    if(a >= b && a >= c) {

        if(b >= c) {

            printf("\n\n%.2lf is the 2nd largest number\n", b);

        }

        else {

            printf("\n\n%.2lf is the 2nd largest number\n", c);

        }

    }

else if(b >= a && b >= c) {

        if(a >= c) {

            printf("\n\n%.2lf is the 2nd largest number\n",a);

        }

        else {

            printf("\n\n%.2lf is the 2nd largest number\n",c);

        }

    }

// c is the largest number of the three

    else if(a >= b) {

        printf("\n\n%.2lf is the 2nd largest number\n", a);

    }

    else {

        printf("\n\n%.2lf is the 2nd largest number\n", b);

    }

    return 0;

}

Branching(Decission Making)-switch case

Ø  The switch statement allows us to execute one code block among many alternatives.

Ø  You can do the same thing with the if...else..if ladder.

Ø  However, the syntax of the switch statement is much easier to read and write.

Ø  Syntax

switch (expression) ​{

    case constant1:

      // statements

      break;

    case constant2:

      // statements

      break;    .

    .

    .

    default:      // default statements

Flow chart of switch case

Program calculate the basic arithmetic operations (+,-,*,/) using switch case statement.

            #include<stdio.h>

            #include<conio.h>

            int main()

            {

                int a,b;

                int op;

                printf(" 1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division\n");

                printf("Enter the values of a & b: ");

                scanf("%d %d",&a,&b);

                printf("Enter your Choice : ");

                scanf("%d",&op);

            switch(op)

                {

                case 1                :

                    printf("Sum of %d and %d is : %d",a,b,a+b);

                    break;

                case 2                :

                    printf("Difference of %d and %d is : %d",a,b,a-b);

                    break;

                case 3                :

                    printf("Multiplication of %d and %d is : %d",a,b,a*b);

                    break;

            case 4    :

                    printf("Division of Two Numbers is %d : ",a/b);

                    break;

             default                :

                    printf(" Enter Your Correct Choice.");

                    break;

                }

                return 0;

            }

Looping-while

Ø  while loop in C programming repeatedly executes a target statement as long as a given condition is true.

Ø  Syntax:

while(condition) {

   statement(s);

}

Ø  Here, statement(s) may be a single statement or a block of statements.

Ø  The condition may be any expression, and true is any nonzero value.

Ø  The loop iterates while the condition is true.

Ø  When the condition becomes false, the program control passes to the line immediately following the loop.

Example of looping-while

         


            #include<stdio.h>  

            int main() {                

int i=1;      

while(i<=10) {      

printf("%d \n",i);      

i++;      

}  

return 0;  

            }    

Print table for the given number using while loop in C

            #include<stdio.h> 

            int main() {   

int i=1,number;   

printf("Enter a number: ");   

scanf("%d",&number);   

while(i<=10) {   

printf("%d \n",(number*i));   

i++;   

}   

return 0;

 }

Looping-do while



Ø  Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop.

Ø  do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.

Ø  Syntax:

do {

   statement(s);

} while( condition );

Program to find a sum of user input number until user gives input zero.

            #include <stdio.h>

            int main() {

              int number, sum = 0;

              do {

                printf("Enter a number: ");

                scanf("%d", &number);

                sum += number;

              }while(number != 0);

              printf("Sum = %d",sum);

              return 0;

            }

Looping-for



Ø  When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

Ø  Syntax:

for (initialization_stmt; test_Expression; update_stmt)

{

    // statements inside the body of loop

}

Find  the input number is prime or composite

            #include<stdio.h>

            int main()

            {

                int num, i, count=0;

                printf("Enter a number: ");

                scanf("%d", &num);

                for(i=2; i<num; i++)  {

                    if(num%i == 0)  {

                        count++;

                        break;

                    }

                }

            if(count==0)

                    printf("\nIt's a prime number");

            else

                    printf("\nIt's not a prime number");

                return 0;

            }

Program to find a Fibonacci series upto nth term

            #include <stdio.h>

            int main() {

              int i, n;

              // initialize first and second terms

              int t1 = 0, t2 = 1;

              // initialize the next term (3rd term)

              int nextTerm = t1 + t2;

              // get no. of terms from user

              printf("Enter the number of terms: ");

              scanf("%d", &n);

              // print the first two terms t1 and t2

              printf("Fibonacci Series: %d, %d, ", t1, t2);

            // print 3rd to nth terms

              for (i = 3; i <= n; ++i) {

                printf("%d, ", nextTerm);

                t1 = t2;

                t2 = nextTerm;

                nextTerm = t1 + t2;

              }

              return 0;

            }

Program to find a factorial of a given number

            #include <stdio.h>

            int main() {

                int n, i;

                unsigned long long fact = 1;

                printf("Enter an integer: ");

                scanf("%d", &n);

                // shows error if the user enters a negative integer

                if (n < 0)

                    printf("Error! Factorial of a negative number doesn't exist.");

            else {

                    for (i = 1; i <= n; ++i) {

                        fact *= i;

                    }

                    printf("Factorial of %d = %llu", n, fact);

                }

                return 0;

            }

Program to find the reverse of a given number

            #include <stdio.h>

            int main() {

              int n, reverse = 0, remainder;

              printf("Enter an integer: ");

              scanf("%d", &n);

              while (n != 0) {

                remainder = n % 10;

                reverse = reverse * 10 + remainder;

                n /= 10;

              }

              printf("Reversed number = %d", reverse);

              return 0;

            }

Program to count the number of digits in a user given number

            #include <stdio.h>

            int main() {

              long int n;

              int count = 0;

              printf("Enter an integer: ");

              scanf("%ld", &n);

              do {

                n /= 10;

                ++count;

              } while (n != 0);

              printf("Number of digits: %d", count);

              return 0;

            }

Jumping-goto



Ø  The C goto statement is a jump statement which is sometimes also referred to as an unconditional jump statement.

Ø  The goto statement can be used to jump from anywhere to anywhere within a function.

Ø  Syntax:

Ø  goto label;

Ø  ... .. ...

Ø  ... .. ...

Ø  label:

Ø  statement;

Program to check whether given number is odd or even using goto statement

            #include <stdio.h>

            int main() {

                int num;

                printf("Enter any integer number");

                scanf("%d",&num);

                if (num % 2 == 0)

                    goto even;

                else

                    goto odd;

            even:

                printf("%d is even", num);

                return;

            odd:

                printf("%d is odd", num);

                return 0;

            }

Jumping-break

Ø  The break statement ends the loop immediately when it is encountered. 

Ø  used to jump out of a loop.

Ø  Syntax:

Ø  break;

Ø  The break statement is almost always used with if...else statement inside the loop.

Jumping-continue

Ø  The continue statement skips the current iteration of the loop and continues with the next iteration.

Ø  Syntax:

Ø  continue;

Ø  The continue statement is almost always used with the if...else statement.

Jumping-return

Ø  ends the execution of a function and returns the control to the function from where it was called.

Ø  The return statement may or may not return a value depending upon the return type of the function. For example, int returns an integer value, void returns nothing, etc.

Ø  In C, we can only return a single value from the function using the return statement and we have to declare the data_type of the return value in the function definition/declaration.

Ø  Syntax:

Ø  return return_value;

Nested Control Structure

Ø  Nested control structures refer to the practice of using one control structure within another control structure.

Ø  In programming, control structures are used to determine the flow of execution of statements in a program.

Ø  They allow a program to make decisions based on conditions or repeat a set of statements a certain number of times

Ø  nesting control structures means that we can have one control structure within another control structure.

Ø  This allows us to create more complex and flexible programs, by enabling us to execute a series of statements only under certain conditions, or to repeat a series of statements multiple times within a larger loop

program to generate the following output using loop

 1.           #include <stdio.h>

            int main() {

               int i, j, rows;

               printf("Enter the number of rows: ");

               scanf("%d", &rows);

               for (i = 1; i <= rows; ++i) {

                  for (j = 1; j <= i; ++j) {

                     printf("%d ", j);

                  }

                  printf("\n");

               }

               return 0;

            }

            Output:

            1

            1 2

            1 2 3

            1 2 3 4

            1 2 3 4 5

        2.     #include<stdio.h>

            int main() {

                int i, j, n;

                printf("Enter number of lines of pattern: ");

                scanf("%d", &n);

                for(i=1;i<=n;i++) {

                    for(j=1;j<=i;j++) {

                        printf("%d  ", (j+1)%2);

                    }

                    printf("\n");

                }

                return 0;

            }

            Output:

            0

            0 1

            0 1 0

            0 1 0 1

            0 1 0 1 0

           3.  #include <stdio.h>

            int main() {

               int i, j, rows;

               printf("Enter the number of rows: ");

               scanf("%d", &rows);

               for (i = 1; i <= rows; ++i) {

                  for (j = 1; j <= i; ++j) {

                     printf("%d ", i);

                  }

                  printf("\n");

               }

               return 0;

            }

            Output:

            1

            2 2

            3 3 3

            4 4 4 4

            5 5 5 5 5

    4.         #include <stdio.h>

            int main() {

                int rows = 5;

                for (int i = 0; i < rows; i++) {

                    for (int j = 0; j < 2 * i; j++) {

                        printf(" ");

                    }

                    for (int k = 0; k < rows - i; k++) {

                        printf("%d ", (k + 1)%2);

                    }

                    printf("\n");

                }

                return 0;

            }

            Output:

            1 0 1 0 1

               1 0 1 0

                  1 0 1

                     1 0

                        1

         5.    #include <stdio.h>

            int main()  {

                int rows = 5;

                int i,j,k;

                for (i = 0; i < rows; i++) {

                    for (j = 0; j < 2 * (rows - i) - 1; j++) {

                        printf(" ");

                    }

                    for (k = 0; k < 2 * i + 1; k++) {

                        printf("* ");

                    }

                    printf("\n");

                }

                return 0;

            }

            Output:

                      *

                   * * *

                 * * * * *

               * * * * * * *

             * * * * * * * * *

            program to calculate the sequence 1/1!+2/2!+3/3!+……+n/n!

#include<stdio.h>

            int main(){

                int i = 1, j, n;

                float sum = 0.0, fact;

                 printf("Enter n");

        scanf("%d",&n);

                while(i <= n) {

                    fact = 1;

                    for(j = 1; j <= i; j++) {

                        fact = fact * j;

                    }

                    

            sum = sum + (i / fact);

                    i++;

                }

                printf("Sum of series is %f\n", sum);

                return 0;

            }

Program to display sum of the following series upto n terms: sum = x – x2+x3+x4+…….+xn

            #include<stdio.h>

            #include<math.h>

            int main(){

                int x,n,sum=0,i;

      printf("Enter values of x and n");

      scanf("%d %d",&x,&n);

                for(i = 1; i <= n; i++) {

                    if(i%2 == 0)

                 sum = sum - pow(x,i);

                     else

                 sum = sum + pow(x,i);

                }

            printf("Sum of series is %d\n", sum);

                return 0;

            }

program to calculate the sequence 1+x/1!+x2/2!+x3/3!+……+xn/n!

            #include <stdio.h>

            #include<math.h>

            void main() {

                            float x,sum,fact;

                            int i,j,n;

                            printf("Input the value of x :");

                            scanf("%f",&x);

                            printf("Input number of terms : ");

                            scanf("%d",&n);

                            sum =1;

            for (i=1;i<n;i++)  {

                     fact = 1;

                    for(j = 1; j <= i; j++) {

                        fact = fact * j;

                    }

                              sum =sum + (pow(x,i)/fact);

                            }

                            printf("\nThe sum  is : %f\n",sum);

            }

 

 

 

 

 




 

 

 

 

 

 

 

 

 

 

 


No comments:

Post a Comment

Research in Social Science

   C  Concept of Research in Social Science -         Understanding the concept of Research Methods, Techniques and Tools: Interview, Fo...