C (Chap-5-Decision Making and Branching Statement)
C (Chap-5-Decision Making and Branching Statement)
C (Chap-5-Decision Making and Branching Statement)
Statement:
A statement (also called an instruction) is the smallest element of a programming language. A statement or
instruction is used to inform the computer to perform an action when a program is executed.
A statement can set a value of a variable, can alter the value of a variable, it can accept the input, it can
manipulate the data and display the data.
The expressions such as i++ or sum = 0 or scanf ("%d", &n) become statements when the are terminated
by a semicolon as shown below :
i++; /* statement 1 */
sum = 0; /* statement 2 */
scanf(“%d”,& n); /* statement 3 */
a=10; /* statement 4 */
Note: Each statement in C must be terminated by a semicolon (denoted by ;)
Compound Statement:
The set of statements enclosed within a pair of curly braces such as ‘{’ and ‘}’ is considered as a
compound statement.
For example, the following compound statement computes and displays the addition of 2 numbers.
{
a = 10; ‘ /* statement 1 */
b = 5 ; /* statement 2 */
c=a+b; /* statement 3 */
printf (“%d\n”, c); /* statement 4 */
}
Control Statements:
The order in which the statements are executed is called control flow. The statements that are used to
control the flow of execution of the program are called control statements.
Based on the order in which the statements are executed, the various Control statements are classified as
shown below:
simple if
goto
if else
break
Nested if
continue
else-if ladder
switch
Sequential Statements:
The programmer writes a sequence of statements to do a specific activity. All these statements in a
program are executed in the order in which they appear in the program.
These programming statements that are executed sequentially, that is one after the other, are called
sequential control statements. Here, no separate statements are required to make these statements executed
in sequence.
printf(“Hello”); //Statement 1
ch=’A’; //Statement 2
printf(“%c”,ch); //Statement 3
a=10; //Statement 4
Here, statement-1 is executed first ,followed by statement-2 followed by statement-3 and
so on. In short, we say that execution of a program is normally sequential (one after the
other).
getchar() putchar()
getch() putch()
getche() puts()
gets()
a. getchar():
getchar() is a Unformatted input function which is used to input a character from keyboard at run time and
only 1 character can be entered at a time.
In getchar() we can not use any format specifiers.
getchar() is only used for taking characters.
Syntax:
Variable=getchar();
Example:
char ch;
ch=getchar();
b. putchar():
putchar() is a Unformatted output function which is used to display a character on output screen.
Syntax:
putchar(variable/value);
Example 1:
char ch=’A’;
putchar(ch);
Example 2:
char ch;
ch=getchar();
putchar(ch);
Example 3:
putchar(‘a’);
Sahyog College of Management Studies, Thane W
Program for getchar() and putchar():
c. getch(),getche():
The functions getch() and getche() are used to read a character from the keyboard similar to getchar().
While using getchar() a return key pressed terminates the reading of a character. In case of getch() and
getche() it is not required. Just a character entered itself terminates reading.
When getch() is used the character entered is not displayed or echoed on the screen
whereas when getche() is used the character entered is echoed or displayed on the screen.
The syntax of both the functions is as follows :
These functions read a character from the keyboard and copy it into memory area which is identified by
the variable ch.
No arguments are required for these functions. These functions do not wait for the user to press “Enter or
Return” key.
Note: The typed character will not be displayed on the screen if we use getch() function. The typed character
will be echoed (displayed) on the screen if we use getche() function.
d. putch():
putch() is a Unformatted output function
This function displays a character stored in the memory using a variable on the monitor. The variable
should be passed as parameter to the function.
Syntax:
putch(character/variable);
Example 1:
char ch=’A’;
putch(ch);
Example 2:
Sahyog College of Management Studies, Thane W
char ch;
ch=getche();
putchar(ch);
Example 3:
putch(‘d’);
e. gets() :
gets() is used to read a set of characters(string) from the keyboard .
Example:
char str[10];
gets(str); /* reads a set of characters into memory area str */
f. puts():
puts() function is used to display string on output screen
Example 2:
char s1[10];
gets(s1);
puts(s1);
Example 3:
puts(“good morning”);
scanf () printf()
The following table shows the way the user has to enter the values from the keyboard:
Input statement What has to entered How to enter
scanf ("%d%d%d",& a,& b,& c); 3 integer values 1 2 3 123
Here, a = 1, b = 2 and c = 3
NOTE : Do not use any back slash characters such as \t,\n etc., in scanf().
2468 54321
Here a=246, b=8,c=543
And remaining degits 2 1 will be ignored.
(Space Matters)
scanf(“%4s”,&str); 1 string Sahyog
Here, str=sahy
og will be ignored.
printf():
The data stored in the memory area can be displayed on monitor or output device using the printf()
function.
The user can display integer values,floating-points,characters and strings using printf() function.
printf() returns the total no. of digits or characters displayed on output screen.
Explanation: printf() prints the good morning first and then returns the number of characters it has printed and
that no is stored in variable ‘a’ that is why its output is GOOD MORNING 12, 12 is returned by printf()
function.
The following table shows the given values, for the statement to be executed and output obtained on the
screen.
Input values Output statement to be executed Output obtained
a=1,b=2,c=3 printf(“a=%d,b=%d,c=%d”, a, b, c); a=1,b=2,c=3
a=1,b=2,c=3 printf(“a=%d\tb=%d\tc=%d”,a,b,c); a=1 b=2 c=3
a=1,b=2,c=3 printf(“a=%d\nb=%d\nc=%d”,a,b,c); a=1
b=2
c=3
printf("\"Hello\""); “Hello”
printf("Hello"); Hello
Printf(“New\tDelhi”); New Delhi
Field Width Specification for Integer:
The printf() function uses the field width to know the total number of spaces used on the screen while printing
the value.
The specification is provided by means of a format string like “%wk” where,
w indicates total number of spaces required to print the value(width specifier).
k is the format specifier i.e. %d,%c etc.
Sahyog College of Management Studies, Thane W
Input Output statement to be executed Output Obtained
Values
n=208 printf(“%5d”,n); 2 0 8
Note: Right Justification printing because of positive
value.
n=208 printf(“%-6d”,n); 2 0 8
Note: Left Justification printing because of negative
value.
n=208 printf(“%2d”,n); 2 0 8
Note: if the space specified is less than the actual
requirement then the width specifier is ignored.
Additional Programs:
1. WAP to add 2 numbers(take input from user)
#include<stdio.h>
int main()
{
int num1,num2,add;
printf("Enter 1st number:\n");
scanf("%d",&num1);//5
printf("Enter 2nd number:\n");
scanf("%d",&num2);//10
Sahyog College of Management Studies, Thane W
add=num1+num2;
printf("----------------------\n");
printf("%d + %d = %d",num1,num2,add);
printf("\n----------------------\n");
return 0;
}
Output:
Enter 1st number:
12
Enter 2nd number:
10
----------------------
12 + 10 = 22
----------------------
2. WAP to check smallest no between 2 nos. using conditional operator(take input from user)
#include<stdio.h>
#include<math.h>
int main()
{
int num1,num2,small;
printf("Enter 1st number:\n");
scanf("%d",&num1);//5
printf("Enter 2nd number:\n");
scanf("%d",&num2);//10
Task
WAP to convert inch to cm. (take input from user) (1 inch=2.54 cm)
WAP to find out sqrt of a number using sqrt() function(take input from user)
WAP to find out square and cube of a number.(take input from user)
Branching Statements:
In sequential control all the statements are executed in the order specified in the program one after the other
however computer can skip execution of some statements. This skipping facility is provided by the
instructions called skip instructions. These skip instructions are also called branching statements. Thus, the
statements that alter the sequence of execution of the program are called branching statements.
Branching Statements
1. Simple if / if statements
The simple if or if statement is a simple decision statement.When a set of statement have to be executed or
skipped when the condition is true or false,then if statement is used.
Syntax of if:
if(condition/expression)
{
Statement-1;
Statement-2;
: Execute if condition is true
:
Statement-n;
}
Working of if statement:
The if statement evaluates the expression/condition inside the parenthesis ().
Sahyog College of Management Studies, Thane W
If the expression/condition is evaluated to true, statements inside the body of if are executed.
If the expression/condition is evaluated to false, statements inside the body of if are not executed.
Note: If the body of an if...else statement has only one statement, you do not need to use brackets {} but if more
than 1 statement is associated with if then {} is required.
Example:
if (condition)
statement 1;
In this example, only statement 1 is associated with the if statement. so {} is not mandatory.
Program to display a message if user enters less than 10.
#include<stdio.h>
int main()
{
int n; Output 1: Output 2:
printf(“Enter a number:\n”); Enter a number: Enter a number:
scanf(“%d”,&n); 4 13
if(n<10) Value is less than 10
{
printf(“value is less than 10”);
}
return 0;
}
Flowchart for above program Algorithm for above program
Start
step 1: start
step 2: Declare variable:n
Declare a variable: n step 3: display:”Enter a number”
step 4: read: n
Display: “Enter a
Display: step 5: if(n<10)
number”
display:”value is less than 10”
step 6: stop
Read: n
Yes
if (n<10)
Display:”value is Stop
less than 10”
Sahyog College of Management Studies, Thane W
Program to check for positive number.
#include<stdio.h>
int main() Output 1: Output 2:
{ Enter a number: Enter a number:
int n; 20 -10
printf(“Enter a number\n”); 20 is a positive number
scanf(“%d”,&n);
if ( n>0)
{
printf(“%d is a positive number”);
}
return 0;
}
step 1: start
Start
step 2: Declare variable:n
step 3: Display:”Enter a number”
Declare a variable: n
step 4: Read: n
step 5: if(n>0)
Display: “Enter a
Display:
number” Display:”positive number”
step 6: stop
Read: n
Yes
if (n>0)
Display:”positive
number”
Stop
2.if-else statement
It is a two way decision statement which executes one statement (or block of statements) or another
statement (or block of statements).
one of these two is done when condition is true and the other one when the condition is false for this
purpose if-else statement is used.
For true part if takes care and for the false part else takes care.
Yes No
if(a<b))
Display: ”b is
Display: ”a is
smallest no”
smallest no”
numbers”
Stop
Task:
Prepare Flowchart and Algorithm for above program.
Write a C program to check whether a number is divisible by 5 and 11 or not using if else.
Write a C program to check whether a character is alphabet or not.
Write a C program to input any alphabet and check whether it is vowel or consonant.
Write a C program to input any character and check whether it is alphabet, digit or special character.
Write a C program to check whether a character is uppercase or lowercase alphabet.
Write a C program to input all sides of a triangle and check whether triangle is valid or not.
Note:
We can directly put any integer number or zero 0 at condition place.
Integer number indicates than condition is true and zero indicates that the condition is false.
Program 1:
#include<stdio.h>
int main()
{
if(1)
printf("hi");
else
printf("hello");
return 0;
}
Output:
hi
program 2:
#include<stdio.h>
int main()
{
if(0)
printf("hi");
else
printf("hello");
return 0;
}
Output:
hello
program 3:
#include<stdio.h>
int main()
{
if(4)
printf("hi");
else
printf("hello");
return 0;
}
Output:
hi
3.else-if ladder
The if...else statement executes two different codes depending upon whether the test expression is true or
false. Sometimes, a choice has to be made from more than 2 possibilities.
The if...else ladder allows you to check between multiple test expressions and execute different statements.
else-if ladder helps user decide from among multiple options. The statements are executed from the top
down.
else if(ch==2)
{
printf("Enter 2 numbers\n");
scanf("%d%d",&a,&b);
c=a-b;
printf("%d-%d=%d",a,b,c);
}
else if(ch==3)
{
printf("Enter 2 numbers\n");
scanf("%d%d",&a,&b);
Additional Programs:
Program to check whether entered number is positive, negative or zero using else if ladder.
#include<stdio.h>
Sahyog College of Management Studies, Thane W
#include<conio.h>
int main()
{
int a;
printf("Enter a Number: ");
scanf("%d",&a);
if(a > 0)
{
printf("%d is Positive number",a);
}
else if(a == 0)
{
printf("Entered Number is Zero");
}
else if(a < 0)
{
printf("%d is Negative number",a);
}
return 0;
}
Output 1:
Enter a Number: -9
-9 is Negative number
Output 2:
Enter a Number: 11
11 is Positive number
4.Nested-if:
Nested if statements means an if statement inside another if statement and It is possible to include
an if...else statement inside the body of another if...else statement.
When a series of decision is required, nested if-else is used. in nested if, conditions are checked in series
that in sequence and here condition checking is depend on each other i.e. if first condition is true then only
second condition will get checked otherwise not.
syntax:
if(condition1)
{
if(condition2)
{
statements;
}
else
{
statements;
}
}
else
{
Sahyog College of Management Studies, Thane W
statements;
}
Program to check whether candidate is eligible for the interview or not using nested-if
conditions: 1. if candidate has scored more than 60 in ssc then only he/she will be eligible for second round
2. if candidate has scored more than 80 in C then he/she will be selected for the interview else not.
Note: if ssc marks is not more than 60 then second condition should not be checked, directly candidate will be
out of the interview.
Program:
#include<stdio.h>
int main()
{
int ssc,c;
printf("Enter ssc score:\n");
scanf("%d",&ssc);
printf("Enter c score:\n");
scanf("%d",&c);
if(ssc>60)
{
if(c>80)
{
printf("Congratulations!!! you are selected");
}
else
{
printf("Sorry!!!Try to score more in C");
}
}
else
{
printf("sorry!! try to score more in ssc");
}
return 0;
}
Output 1 Output 2 Output 3
1.else and else..if are optional statements, a program having only “if” statement would run fine.
2. else and else..if cannot be used without the “if”.
3. There can be any number of else..if statement in an if else..if block.
4. If none of the conditions are met then the statements in else block gets executed.
5. Just like relational operators, we can also use logical operators such as AND (&&), OR(||) and NOT(!).
Sahyog College of Management Studies, Thane W
5. switch():
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.
Switch statement in C checks the value of a variable and compares it with multiple cases. Once the case
match is found, a block of statements associated with that particular case is executed.
Each case in a block of a switch has a different name/number which is referred to as an identifier. The
value provided by the user is compared with all the cases inside the switch block until the match is found.
If a case match is NOT found, then the default statement is executed, and the control goes out of the switch
block.
syntax:
switch( expression )
{
case value-1:
statements;
break;
case value-2:
statements;
break;
case value-n:
statements;
break;
default: statements;
break;
}
Note:
The expression can be integer or a character only, floating points and strings are not allowed in switch
expression.
Duplicate case values are not allowed.
The case value must be an integer or character constant
How does the switch statement work?
The expression is evaluated once and compared with the values of each case label.
If there is a match, the corresponding statements after the matching label are executed. For example, if the
value of the expression is equal to value-2, statements after case value-2 are executed until break is
encountered.
If there is no match, the default statements are executed.
If we do not use break, all statements after the matching label are executed until a break is reached.
By the way, the default clause inside the switch statement is optional.
switch(op)
{
case '+':
printf("Enter two operands:\n ");
scanf("%d %d",&n1, &n2);
printf("\n=============================\n");
printf("%d + %d = %d",n1, n2, n1+n2);
printf("\n=============================\n");
break;
case '-':
printf("Enter two operands:\n ");
scanf("%d %d",&n1, &n2);
printf("\n=============================\n");
printf("%d - %d = %d",n1, n2, n1-n2);
printf("\n=============================\n");
break;
case '*':
printf("Enter two operands:\n ");
scanf("%d %d",&n1, &n2);
printf("\n=============================\n");
printf("%d * %d = %d",n1, n2, n1*n2);
printf("\n=============================\n");
break;
case '/':
printf("Enter two operands:\n ");
scanf("%d %d",&n1, &n2);
printf("\n=============================\n");
printf("%d / %d = %d",n1, n2, n1/n2);
printf("\n=============================\n");
break;
default:
printf("Error! operator is not correct");
}
return 0;
}
Output:
Enter an operator (+, -, *, /):
-
Enter two operands:
12
3
=============================
12 - 3 = 9
Sahyog College of Management Studies, Thane W
Program to execute more than 1 case at a time.
We can also execute multiple cases based on a single value given by the user.
#include<stdio.h>
int main()
{
int n;
printf("Enter value\n");
scanf("%d",&n);
switch(n)
{
case 1:
case 2:
case 3:
printf("User entered 1,2 or 3");
break;
case 4:
case 5:
case 6:
printf("User entered 4,5 or 6");
break;
default:
printf("User entered more than 6 or some other value");
}
return 0;
}
Output 1:
Enter value
3
User entered 1, 2 or 3
Output 2:
Enter value
8
User entered more than 6 or some other value
Additional Programs:
C program to read weekday number and print weekday name using switch.
#include <stdio.h>
int main()
{
int wDay;
switch(wDay)
{
Sahyog College of Management Studies, Thane W
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 weekday number.");
}
return 0;
}
Output:
Enter weekday number (1-7):
3
Tuesday
C program to check whether a character is VOWEL or CONSONANT using switch.
#include<stdio.h>
int main()
{
char ch;
printf("Enter a character: ");
scanf("%c",&ch);
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z')) //condition to check character is alphabet or not
{
switch(ch)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
Sahyog College of Management Studies, Thane W
case 'o':
case 'u':
printf("%c is a VOWEL.\n",ch);
break;
default:
printf("%c is a CONSONANT.\n",ch);
}
}
else
{
printf("%c is not an alphabet.\n",ch);
}
return 0;
}
Output :
Enter a character: U
U is a VOWEL.
Output 1:
Enter a number:
3
3 is an ODD number.
Output 2:
Enter a number:
12
12 is an EVEN number.
TASK:
C program to find number of days in a month using switch case.
C program to read gender (M/F) and print corresponding gender using switch.
1. Type Conversion
2. Type Casting
The type conversion is the process of converting a data value from one data type to another data type
automatically by the compiler. Sometimes type conversion is also called implicit type conversion.
The implicit type conversion is automatically performed by the compiler.
For example, in c programming language, when we assign an integer value to a float variable the integer
value automatically gets converted to float value by adding decimal value 0. And when a float value is
assigned to an integer variable the float value automatically gets converted to an integer value by removing
the decimal value. To understand more about type conversion observe the following.
int i=10;
float x=15.5;
char ch=’A’;
i=x;
printf("i value is %d\n",i);
x=i;
printf("x value is %f\n",x);
i = ch ;
printf("i value is %d\n",i);
}
Output:
In the above program, we assign i = x, i.e., float variable value is assigned to the integer variable. Here, the
compiler automatically converts the float value (90.99) into integer value (90) by removing the decimal
part of the float value (90.99) and then it is assigned to variable i. Similarly, when we assign x = i, the
integer value (90) gets converted to float value (90.000000) by adding zero as the decimal part.
3. Typecasting is also called an explicit type conversion. Compiler converts data from one data type to
another data type implicitly. When compiler converts implicitly, there may be a data loss. In such a case,
we convert the data from one data type to another data type using explicit type conversion. To perform this
we use the unary cast operator. To convert data from one type to another type we specify the target data
type in parenthesis as a prefix to the data value that has to be converted. The general syntax of typecasting
is as follows.
(TargetDataType) DataValue;
Program:
#include<stdio.h>
int main()
{
int totalMarks = 450, maxMarks = 600 ;
float avg;
avg = totalMarks / maxMarks * 100 ;
printf("Average without cast=%f",avg);
Sahyog College of Management Studies, Thane W
avg = (float) totalMarks / maxMarks * 100 ;
printf("\nAverage with cast=%f",avg);
return 0;
}
Output:
Average without cast=0.000000
Average with cast=75.000000
***