Friday, September 11, 2020

Assignment 2. Decision Making Control Structures

 Assignment 2. Decision Making Control Structures


Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

In decision control statements (if-else and nested if), group of statements are executed when condition is true.  If condition is false, then else part statements are executed.

There are 3 types of decision making control statements in C language. They are,

  if statements

  if else statements

  nested if statements

“IF”, “ELSE” AND “NESTED IF” DECISION CONTROL STATEMENTS IN C:

Syntax for each C decision control statements are given in below table with description.

 Decision control statements      

 Syntax/Description

1)   if            

Syntax:

if (condition)

{ Statements; }

Description:

In these type of statements, if condition is true, then respective block of code is executed.

Example:

int main()

{

  int m=40,n=40;

  if (m == n)

  {

  printf("m and n are equal");

  }

}

 

2)      if…else  

Syntax:

if (condition)

{ Statement1;

Statement2; }

else

{ Statement3;

 Statement4; }

Description:

In these type of statements, group of statements are executed when condition is true.  If condition is false, then else part statements are executed.

Example:

#include <stdio.h>

int main()

{

  int m=40,n=20;

  if (m == n)

  {

  printf("m and n are equal");

  }

  else

  {

  printf("m and n are not equal");

  }

}


3)      nested if             

Syntax:

if (condition1)

{ Statement1; }

else_if(condition2)

{ Statement2; }

else Statement 3;

Description:

If condition 1 is false, then condition 2 is checked and statements are executed if it is true. If condition 2 also gets failure, then else part is executed.

Example :

#include <stdio.h>

int main()

{

  int m=40,n=20;

  if (m>n) {

 printf("m is greater than n");

  }

  else if(m<n) {

  printf("m is less than n");

  }

  else {

  printf("m is equal to n");

  }

}


4Switch Statement : Instead of else –if ladder, ‘C’ has a built-in multi-way decision statement known as a switch. The general form of the switch statement is as follows.

 Syntax:-

 Switch (expression)

{

case value1   : block1;

                        break;

case value 2  : block 2;

                        break;

.

.

.

 default          :  default block;

                        break;

}

st – x;

 

The expression is an integer expression or character value1, value-2---- are constants or constant expressions and also known as case lables. Each  of the values should be a unit within a switch and may  contain zero or more statements.

When the switch is executed the value of the expression is successively compared against the values value-1,value-2------- If  a case is found whose value matches with the of the expression then the block of statements that follows the case are executed .

The break statement at the end of each block signals the end a particular case and causes an exist from the switch statement transfering the control  to the st-x following the switch. The default is an optional case . If will be executed if the value of the expression doesn’t match with any Of the case values then control goes to the St-x.

 

Ex :  

switch (number)

{

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;

          default : printf(“Saturday”);

            break;

}

 

5. The  Conditional ( ? : ) Operator :  These operator is a combinations of question and colon and takes three operands this is also known as conditional operator. The general form of the conditional operator is as follows

Conditional expression? Expression 1:expression2

The conditional expression is evaluated first If the result is non-zero expression is evaluated and is returns as the value of the conditional expression, Otherwise expression2 is evaluated and its value is returned.

 Ex :    flag = ( x<0) ? 0 : 1

            It’s equalent of the If-else structure is as follows

                        If ( x<0)

Flag = 0;

                        Else

                                    Flag = 1;

6. Goto Statement :  The goto statement is used to transfer the control of the program from one point to another. It is something reffered to as unconditionally branching. The goto is used in the form

Goto label;


7. Label statement : The label is a valid ‘C’ identifier followed by a colon. we can precode any statement by a label in the form

                                    Label : statement ;

This statement immediately transfers execution to the statement labeled with the label identifier.

          

Ex :                 i = 1;

                        bc : if(1>5)                                  Output :        1

                        goto ab;                                                            2

                        printf(“%d”,i);                                                   3

                        ++i;                                                                  4

                        goto bc;                                                            5

                        ab : {

                        printf(“%d”,i); }        


Assignments:- 

Excercise 1 :

 Set A:

 1. Write a program to accept an integer and check if it is even or odd.

 #include <stdio.h>

void main()

{

    int num;

    printf("Enter an integer number: ");

    scanf("%d", &num);

    if(num % 2 == 0)

 printf("\n%d is even.", num);

 else

 printf("\n%d is odd.", num);

}

2. Write a program to accept three numbers and check whether the first is between the other two numbers. Ex: Input 20 10 30. Output: 20 is between 10 and 30

 #include<stdio.h>

void main()

{

 int a,b,c;

 printf("Enter the three numbers : ");

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

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

  printf("\n%d is between %d and %d",a,b,c);

  else

  printf("\n%d is not between %d and %d",a,b,c);

}

3. Accept a character as input and check whether the character is a digit. (Check if it is in the range ‘0’ to ‘9’ both inclusive)

 #include<stdio.h>  

void main()

{

    char ch;

    printf("Enter a Character: ");

    scanf("%c", &ch);

    if(ch >= '0' && ch <= '9')

        printf("\n%c is a Digit\n", ch);

    else

     printf("\n%c is a not Digit", ch);

}

4. Write a program to accept a number and check if it is divisible by 5 and 7.

 #include<stdio.h>

void main()

{

  int number;

  printf("Enter the number : ");

  scanf("%d",&number);

  if(number%5==0 && number%7==0)

    printf("\nThe number %d is divisible by 5 and 7",number); 

else

    printf("\nThe number %d is not divisible by 5 and  7",number);

}

5. Write a program, which accepts annual basic salary of an employee and calculates and displays the Income tax as per the following rules. *** Basic: < 1,50,000 Tax = 0 1,50,000 to 3,00,000 Tax = 20% > 3,00,000 Tax = 30%

 #include<stdio.h>

void main()

{

 float sal,tax;

 printf("Enter the Employee basic salary : ");

 scanf("%f",&sal);

 if(sal<=150000)

 {

  tax=0;

  printf("\nTax = %0.2f",tax);

 }

 else if(sal>150000 && sal<=300000)

 {

  tax=(sal*0.2);

  printf("\nTax = %0.2f",tax);

 }

 else if(sal>300000)

 {

  tax=(sal*0.3);

  printf("\nTax = %0.2f",tax);

 }

}

6. Accept a character from the user and check whether the character is a vowel or consonant. (Hint: a,e,i,o,u, A, E, I, O, U are vowels)

 #include <stdio.h>

void main()

{

    char ch;

        printf("Enter an Alphabet: ");

    scanf("%c",&ch); 

     if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')

        printf("\n%c is a vowel.", ch);

    else

        printf("\n%c is a consonant.", ch);

}

7. Accept any year as input through the keyboard. Write a program to check whether the year is a leap year or not. (Hint leap year is divisible by 4 and not by 100 or divisible by 400)  

#include <stdio.h>

void main()

{

   int y;

   printf("Enter year : ");

   scanf("%d",&y);

   if (((y%4==0) && (y%100!=0)) || (y%400==0))

        printf("\n%d is a leap year", y);

       else

        printf("\n%d is not a leap year", y);

   } 


Set B: 

1. Write a program to check whether given character is a digit or a character in lowercase or uppercase alphabet. (Hint ASCII value of digit is between 48 to 58 and Lowercase characters have ASCII values in the range of 97 to122, uppercase is between 65 and 90) 

#include<stdio.h>

void main()

{

char c;

int ch;

printf("\nEnetr the charcter:");

scanf("%c",&c);

ch=c;

if(ch>=48&&ch<=58)

printf("\n%c Character is digit:",c);

else if(ch>=97&&ch<=122)

printf("\n%c Charcter is lowercase Alphabet:",c);

else

printf("\n%c Charcter is uppercase Alphabet:",c);

}


2. Accept the x and y coordinate of a point and find the quadrant in which the point lies. 

#include<stdio.h>

void main()

{

    int x, y;

     printf("Enter the values for X and Y : ");

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

    if (x > 0 && y > 0)

        printf("\npoint (%d, %d) lies in the First quadrant\n",x,y);

    else if (x < 0 && y > 0)

        printf("\npoint (%d, %d) lies in the Second quadrant\n",x,y);

    else if (x < 0 && y < 0)

        printf("\npoint (%d, %d) lies in the Third quadrant\n",x,y);

    else if (x > 0 && y < 0)

        printf("\npoint (%d, %d) lies in the Fourth quadrant\n",x,y);

    else if (x == 0 && y == 0)

        printf("\npoint (%d, %d) lies at the origin\n",x,y);

}


3. Write a program to calculate the roots of a quadratic equation. Consider all possible cases. Accept the cost price and selling price from the keyboard. Find out if the seller has made a profit or loss and display how much profit or loss has been made. 

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

 void main()

{

    float x, y, z, r1, r2;

    float real, imag, disc;

     printf("Enter the values of x, y and z: ");

    scanf("%f %f %f", &x, &y, &z);

    if (x == 0 || y == 0 || z == 0)

    {

        printf("\nError: Roots cannot be determined");

        exit(1);

    }

    else

    {

        disc = y * y - 4.0 * x * z;

        if (disc < 0)

        {

            printf("\nImaginary Roots");

            real = -y / (2.0 * x) ;

            imag = sqrt(abs(disc)) / (2.0 * x);

            printf("\nRoot1 = %f + %fi", real, imag);

            printf("\nRoot2 = %f - %fi", real, imag);

        }

        else if (disc == 0)

        {

            printf("\nRoots are real and equal");

            r1 = -y / (2.0 * x);

            r2 = r1;

            printf("\nRoot1 = %f", r1);

            printf("\nRoot2 = %f", r2);

        }

        else if (disc > 0 )

        {

            printf("\nRoots are real and distinct");

            r1 =(-y + sqrt(disc)) / (2.0 * x);

            r2 =(-y - sqrt(disc)) / (2.0 * x);

            printf("\nRoot1 = %f ", r1);

            printf("\nRoot2 = %f ", r2);

        }

    }

}


4. Write a program to accept marks for three subjects. Calculate the average and also display the class obtained. (Distinction – above _____Class I – above __%, class II – ___% to ___%, pass class – ___% to ___% and fail otherwise)  

#include<stdio.h>

void main()

{

         int m1,m2,m3,total;

         float percentage;

         printf("Enter three subject marks : ");

         scanf("%d %d %d",&m1,&m2,&m3);

         total=m1+m2+m3;

         percentage=total*100/300;

         printf("\nTotal marks= %d",total);

         printf("\nPercentage = %.3f",percentage);

         if(percentage>=60 && percentage<=100)

                 printf("\nYou are in Distinction");

        else if(percentage>=50 && percentage<=60)

                 printf("\nYou are in 1st class");

        else if(percentage>=40 && percentage<=50)

                 printf("\nYou are in 2nd class");

        else

                 printf("\nYou are Fail");

}


Excercise 2 :To demonstrate decision making statements (switch case) 
SET A:
1. Accept a single digit from the user and display it in words. For example, if digit entered is 9, display Nine. 
#include<stdio.h>
void main()
{
   int ch;
   printf("Enter Digit(0-9): ");
   scanf("%d",&ch);
   switch(ch)
   {
case 0:
      printf("Zero\n");
      break;
case 1:
      printf("one\n");
      break;
case 2:
      printf("Two\n");
      break;
case 3:
      printf("Three\n");
      break;
case 4:
      printf("Four\n");
      break;
case 5:
      printf("Five\n");
      break;
case 6:
      printf("Six\n");
      break;
case 7:
      printf("Seven\n");
      break;
case 8:
      printf("Eight\n");
      break;
case 9:
      printf("Nine\n");
      break;
default:
      printf("invalid digit\nPlease try again ....\n");
      break;
    }
}

2. Write a program, which accepts two integers and an operator as a character (+ - * /), performs the corresponding operation and displays the result. 

#include<stdio.h>
void main()
{
int n1,n2;
char op;
printf("\nEnter 2 numbers:");
scanf("%d%d",&n1,&n2);
printf("\n+.Addition\n-.Substration\n*.Multiplication\/.Division\5Exit");
printf("\nEnter your choise");
scanf(" %c",&op);
switch(op)
{
case '+':printf("\nAddition is %d",n1+n2);
break;
case '-':printf("\nSubstration is %d",n1-n2);
break;
case '*':printf("\nMultiplication is %d",n1*n2);
break;
case '/':printf("\nDivision is %d",n1/n2);
break;
}

}

3. Accept two numbers in variables x and y from the user and perform the following operations

 Options                                                 Actions 
1. Equality                                       Check if x is equal to y 
2. Less Than                                    Check if x is less than y 
3. Quotient and Remainder             Divide x by y and display the quotient and remainder 
4. Range                                         Accept a number and check if it lies between x and y (both inclusive) 5. Swap                                             Interchange x and y

#include<stdio.h>
void main()
{
int n1,n2,ch,q,r,t;

printf("\nEnter 2 numbers:");
scanf("%d%d",&n1,&n2);
printf("\n1.Equality\n2.Less than\n3..Quotient and remainder\n4.Range
\n5.Swap");
printf("\nEnter your choise");
scanf(" %d",&ch);
switch(ch)
{
case 1:if(n1==n2)
printf("\n %d equals to %d",n1,n2);
else
printf("\n %d not equal to %d",n1,n2);
break;
case 2:if(n1<n2)
printf("\n %d less than%d",n1,n2);
else
printf("\n %d not less than %d",n1,n2);
break;
case 3:q=n1/n2;
printf("\nQuotient is %d",q);
r=n1%n2;
printf("\nRemainder is %d",r);
break;
case 4:printf("\nEnter number :");
scanf("%d",&t);
if(t>n1 && t<n2)
printf("\n %d is between %d and %d",r,n1,n2);
else
printf("\n %d is not between %d and %d",r,n1,n2);
break;
case 5:printf("\nBefore swap no is");
printf("First no is:%d",n1);
printf("Second no is %d",n2);
t=n1;
n1=n2;
n2=t;
printf("\After swap no is");
printf("First no is:%d",n1);
printf("Second no is %d",n2);
break;
default:printf("\nInvalid choise:");
}

}

SET B :

1. Accept radius from the user and write a program having menu with the following options and corresponding actions 
Options                                                                 Actions 
1. Area of Circle                                   Compute area of circle and print 
2. Circumference of Circle                  Compute Circumference of circle and print 
3. Volume of Sphere                             Compute Volume of Sphere and print 

#include<stdio.h>
void main()
{
int op;
float r,ans;

printf("\nEnter redius:");
scanf("%f",&r);
printf("\n1.Area of circle\n2.Circumference of circle\n3.Volume of Shere");
printf("\nEnter your choice:");
scanf("%d",&op);
switch(op)
{
case 1:ans=3.14*r*r;
printf("\nArea of circle is %f",ans);
break;
case 2:ans=2*3.14*r;
printf("\nCircumference of circcle is %f",ans);
break;
case 3:ans=4/3*3.14*r*r*r;
printf("\nVolume of Shere is %f",ans);
break;
default:printf("\nInvalid input:");
}

}


2. Write a program having a menu with the following options and corresponding actions 

Options                                                                Actions
 1. Area of square                  Accept length, Compute area of square and print 
2. Area of Rectangle             Accept length and breadth, Compute area of rectangle and print 
3. Area of triangle                 Accept base and height, Compute area of triangle and print  

#include<stdio.h>
void main()
{
int op;
float l,b,h,ans;
printf("\n1.Area of square\n2.Area of Rectangle\n3.Area of triangle");
printf("\nEnter your choise:");
scanf("%d",&op) ;
switch(op)
{
case 1:printf("\nEnter length :");
scanf("%f",&l);
ans=l*l;
printf("\nArea of square is %f",ans);
break;
case 2:printf("\nEnter length :");
scanf("%f",&l);
printf("\nEnter breadth:");
scanf("%f",&b);
ans=l*b;
printf("\nArea of Rectangle is %f",ans);
break;
case 3:printf("\nEnter base:");
scanf("%f",&b);
printf("\nEnter height:");
scanf("%f",&h);
ans=1.0/2.0*b*h;
printf("\nArea of square is %f",ans);
break;
}

}

No comments:

Post a Comment