Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

EST 102 : PROGRAMMING IN C

Viji R
Assistant Prof in ECE
Feb 2024
Contents
 Decision making structures in C: if-else, switch statements
 Control flow statements-for, while, do-while
 Simple programs for familiarisation of if-else, switch and
control flow statements
Decision making using ‘if’
 If the boolean expression
evaluates to true, then the
block of code inside the if
statement will be executed.

 If boolean expression evaluates


to false, then the first set of
code after the end of the if
statement (after the closing
curly brace) will be executed.
Example 1
int main ()
{
int a = 10;

if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
if…else
 If the boolean expression
evaluates to true, then the
if block of code will be
executed, otherwise else
block of code will be
executed.
Example 2
#include <stdio.h>
int main ()
{

int a = 100;

if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
else
{
/* if condition is false then print the following */
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
if...else if...else Statement
Example 3
int main ()
{ else if( a == 30 )
{
printf("Value of a is 30\n" );
int a = 100;
}
if( a == 10 )
{ else
{
printf("Value of a is 10\n" );
printf("No value matches\n" );
} }
else if( a == 20 )
printf("value of a is: %d\n", a );
{ return 0;
printf("Value of a is 20\n" ); }
}
1.Find largest among two number
#include<stdio.h>
int main()
{
int num1,num2;
printf(“Enter the first number : \n”);
scanf(“%d”,&num1);
printf(“Enter the first number : \n”);
scanf(“%d”,&num2);

if (num1 ==num2)
printf(“The numbers are equal”);

else if (num1 > num2)


printf(“The number largest number is : %d” , num1);

else
printf(“The number largest number is : %d” , num2);
}
2.Check whether the character is upper case or lower case
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character: ");
scanf("%c", &ch);
if(ch >= 'A' && ch <= 'Z’)
{
printf("'%c' is uppercase alphabet.", ch);
}
else if(ch >= 'a' && ch <= 'z’)
{
printf("'%c' is lowercase alphabet.", ch);
}
else
{ printf("'%c' is not an alphabet.", ch);
}
return 0;
}
2. Check whether the character is upper case or lower case
Another way
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character: ");
scanf("%c", &ch);
if(ch >= 65 && ch <= 90)
{
printf("'%c' is uppercase alphabet.", ch);
}
else if(ch >=97 && ch <=122)
{
printf("'%c' is lowercase alphabet.", ch);
}
else
{ printf("'%c' is not an alphabet.", ch);
}
return 0; ASCII values of A-Z are 65-90 and
} a-z are 97-122
3. Read a character from user and convert its case (Upper case to lower
case/ lower case to upper case number)

#include <stdio.h>
int main()
{
char in,out;
int x;
printf("Enter an uppercase Character: ");
scanf("%c", &in);
/* x=in;
printf("\nAscii value = %d", x);
*/
out = in+32;
printf("\nIts Lowercase = %c", out);
return 0; ASCII values of A-Z are 65-90 and
} a-z are 97-122
SWITCH STATEMENT
Switch statement is one of decision-making control-flow statements. Just
like else if ladder, it is also used to make a decision among multiple choices.
switch statement has the following form:
switch(expression)
{
case exp-val-1:
statements block-1
break;
case exp-val-2:
statements block-2
break;
case exp-val-3:
statements block-3
break;
:
case exp-val-N:
statements block-N
break;
default:
default statements block
}
SWITCH STATEMENT
The keyword case is followed by an integer or a character constant. Each
constant in each case must be different from all the others.

Execution of Switch statement:


 First, the integer expression following the keyword switch is
evaluated.
 The value it gives is then matched, one by one, against the constant
values that follow the case statements.
 When a match is found, the program executes the statements
following that case until a break or execute all subsequent case and
default statements as well.
 If no match is found with any of the case statements, only the
statements following the default are executed.
 Default statement is optional.
SWITCH STATEMENT
/* Switch with integer constants */
main( )
{
int i = 3 ;
switch ( i )
{
case 2 :
printf ( "I am in case 2 \n" ) ; break ;
case 1 :
printf ( "I am in case 1 \n" ) ; break ;
case 3:
printf ( "I am in case 3 \n" ) ; break ;
default :
printf ( "I am in default \n" ) ;
} The output of this program would be:
} I am in case 3
main( )
{ /* Switch with Character constants */
char ch ;
printf ( "Enter any of the alphabet a, b, or c " )
;
scanf ( "%c", &ch ) ;
switch ( ch )
{
case 'a' :
case 'A' :
printf ( “The letter is a" ) ; break ;
case 'b' :
case 'B' :
printf ( " The letter is b " ) ; break ;
case 'c' :
case 'C' :
printf ( " The letter is c " ) ; break ;
default :
printf ( “Letter is not a,b,c" ) ;
}
}
SWITCH STATEMENT

 Even if there are multiple statements to be executed in each case there is


no need to enclose them within a pair of braces (unlike if, and else).

 If there is no default case, then the program simply falls through the
entire switch and continues with the next instruction (if any,) that
follows the closing brace of switch.

 Switch can check any expression. Thus the following switch statements
are legal.
switch ( i + j * k )
switch ( 23 + 45 % 4 * k )
switch ( a < 4 && b > 7 )

 Expressions can also be used in cases provided they are constant


expressions.
Thus case 3 + 7 is correct, however, case a + b is incorrect.
Basis of
Comparison
If – else Switch
Expression if-else statement uses multiple statement switch statement uses single expression for
for multiple choices. multiple choices.
Testing if-else statement test for equality as well switch statement test only for equality.
as for logical expression.
Evaluation if statement evaluates integer, character, switch statement evaluates only character
pointer or floating-point type or boolean or integer value.
type.
Sequence Either if statement will be executed or switch statement execute one case after
of
Execution else statement is executed. another till a break statement is appeared or
the end of switch statement is reached.
Default If the condition inside if statements is If the condition inside switch statements
Execution
false, then by default the else statement is does not match with any of cases, for that
executed if created. instance the default statements is executed
if created.
Editing It is difficult to edit the if-else statement, It is easy to edit switch cases as, they are
if the nested if-else statement is used. recognized easily.
// 4. Program to Check the given character is vowel or not

#include <stdio.h>
int main()
{
char ch;
printf("Enter the character");
scanf("%c", &ch);
switch(ch)
{
case ‘A’:
case ‘a’:
case ‘E’:
case ‘e’:
case ‘I’:
case ‘i’:
case ‘O’:
case ‘o’:
case ‘U’:
case ‘u’:
printf(“The given Character is a vowel");
default:
printf(“The given character is not vowel");
}
return 0;
}
// 5. Program to create a simple calculator
switch(operator)
{
case '+’:
#include <stdio.h> printf("%d+ %d= %d",n1, n2, n1+n2);
int main() break;
{ case '-’:
char operator; printf("%d - %d= %d",n1, n2, n1-n2);
int n1, n2; break;
printf("Enter an operator (+, -, *, /): "); case '*’:
scanf("%c", &operator); printf("%d* %d= %d",n1, n2, n1*n2);
printf("Enter two operands: "); break;
scanf("%d %d",&n1, &n2); case '/’:
printf("%d/ %d = %d",n1, n2, n1/n2);
break;
default:
printf("Error! operator is not correct");
}
return 0;
}
? : Operator
Conditional operator ? : can be used to replace if...else statements.
It is a ternary operator (it takes three operands)
It has the following general form:
Exp1 ? Exp2 : Exp3;

Exp1 is evaluated. If it is true, then Exp2 is evaluated and


becomes the value of the entire ? expression. If Exp1 is false,
then Exp3 is evaluated and its value becomes the value of the
expression.

int a=5,b;
b=(a==5)?5:4;
printf("b=%d",b);
Control Flow Statements:

 For Loop
 While Loop, Do While Loop
 Break and Continue statements.
 (Simple programs covering control flow)
LOOPS

Based on condition check loops are classified into.


Entry-controlled loops
In entry control loops the given conditions check before execute the body of
loop.
For this loop to work, the test condition should necessarily be true. For
example, for and while loops are entry-controlled.

Exit-controlled loops
In this type loops body of loop executed first and then condition is checked.
Body of loop will execute at least once.
For example, do….while loop.
While LOOP
While statement is used to carry out looping operations, in which a group of
statements is executed repeatedly, until some condition has been satisfied.

Basic Syntax

while(condition)
{
statement(s)
}
void main( ) void main( )
{ {
int i = 1 ; int i = 1 ;
while ( i <= 10 ) do
{ {
printf ( "%d\n", i ) printf ( "%d\n", i );
i++ ; i++ ;
} } while (i <= 10 ) ;
} }

while loop do while loop

When i=11, what will be the output?


Do…While LOOP

The do-while loop is pretty similar to while loop with an additional feature. It is
an exit-controlled loop that gives the user the provision to execute the loop at
least one.
In do…While First, the body of the loop is executed, then the condition is
checked which is in contrast to the while loop.

do
{
statement(s)
_________
_________
} while(condition);
main( )
main( ) {
{ do
while ( 4 < 1 ) {
printf ( "Hello there \n") ; printf ( "Hello there \n") ;
} } while ( 4 < 1 ) ;
}
for LOOP

The for allows us to specify three things about a loop in a single line:
 Setting a loop counter to an initial value.
 Testing the loop counter to determine whether its value has reached the
number of repetitions desired.
 Increasing the value of loop counter each time the program segment within
the loop has been executed.

Syntax:
for( initialization ; condition ; increment / decrement )
{
statement(s)
}

The body of the loop can be single statement or multiple statements.


It is an entry controlled loop
for LOOP

Syntax:

for( initialization ; condition ; increment / decrement )


{
statement(s)
}

for ( count = 1 ; count <= 10 ; count = count + 1 )


{
Statements;
}
Example how the for statement gets executed:
 When the for statement is executed for the first time, the value of count is set
to an initial value 1.
 Now the condition count <= 10 is tested. Since count is 1 the condition is
satisfied and the body of the loop is executed for the first time.
 Upon reaching the closing brace of for, control is sent back to the for
statement, where the value of count gets incremented by 1.
 Again the test is performed to check whether the new value of count exceeds 3.
 If the value of count is still within the range 1 to 10, the statements within the
braces of for are executed again.
 The body of the for loop continues to get executed till count doesn’t exceed the
final value 10.
 When count reaches the value 11 the control exits from the loop and is
transferred to the statement (if any) immediately after the body of for.
for LOOP

It is important to note that the initialization, testing and incrementation part of


a for loop can be replaced by any valid expression. Thus the following for
loop is perfectly ok.

for ( i = 1; i <=10 ;)
printf ( "%d",i++ );
for LOOP
Print numbers from 1 to 10 in different ways
main( )
{
main( ) int i ;
{ for ( i = 1 ; i <= 10 ;)
int i ; {
for ( i = 1 ; i <= 10 ; i = i + 1 ) printf ( "%d\n", i ) ;
printf ( "%d\n", i ) ; i = i + 1;
} }
}

main( )
main( ) {
{ int i = 1;
int i = 1 ; for (; i <= 10 ;)
for (; i <= 10 ; i = i + 1 ) {
printf ( "%d\n", i ) ; printf ( "%d\n", i ) ;
} i = i + 1;
}
}
for LOOP

Multiple Initialisations in the for Loop


The initialisation expression of the for loop can contain more than one statement
separated by a comma.
For example,

for ( i = 1, j = 2 ; j <= 10 ; j++ )

Multiple statements can also be used in the incrementation expression of for loop;
i.e., for loop support increment (or decrement) two or more variables at the same
time.

Only one expression is allowed in the test expression. This expression may contain
several conditions linked together using logical operators.
BREAK Statement

 Sometimes it becomes necessary to come out of the loop even before loop
condition becomes false then break statement is used.
 Break statement is used inside loop and switch statements.
 It cause immediate exit from that loop in which it appears and it is generally
written with condition.
 It is written with the keyword as break. When break statement is encountered loop
is terminated and control is transferred to the statement, immediately after loop
without waiting to get back to conditional state.
BREAK Statement
void main( )
{
int i;
for ( i = 0; i < 10; i++)
{
if ( i == 3)
break;
printf ( “The number is%d\n", i);

}
printf ( “Out of loop”);
}

OUTPUT :
The number is 0
The number is 1
The number is 2
Out of loop
CONTINUE Statement
 Continue statement is used for continuing next iteration of loop after
skipping some statement of loop.

 When it encountered control automatically passes through the beginning


of the loop.

 It is usually associated with the if statement.

 It is useful when we want to continue the program without executing any


part of the program( with in the loop).
Break &Continue Statement

 The difference between break and continue is, when the break encountered
loop is terminated and it transfer to the next statement and when continue is
encounter control come back to the beginning position.

 In while and do while loop after continue statement control transfer to the test
condition and then loop continue

 In for loop after continue control transferred to the updating expression and
condition is tested.
CONTINUE Statement
void main( )
{
OUTPUT :
int i;
The number is 0
for ( i = 0; i < 10; i++) The number is 1
{ The number is 2
if ( i == 3) The number is 4
continue; The number is 5
printf ( “The numer is %d\n", i); The number is 6
} The number is 7
printf ( “Out of loop”); The number is 8
} The number is 9
Out of loop
Fibonacci Series: It is a series of numbers in which each number ( Fibonacci
number ) is the sum of the two preceding numbers.

The simplest is the series 0,1, 1, 2, 3, 5, 8, etc.


6. Program to print Fibonacci Series: 0,1, 1, 2, 3, 5, 8, etc.
#include <stdio.h>
int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm; /* t1: term 1 and t2: term2*/
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; ++i)
{
printf("%d\t", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
Prime number
A prime number is a natural number greater than 1 that has no positive divisors other than
1 and itself.
7. Prime number check program
#include<stdio.h>
int main(){
int n,i,m=0,flag=0;
printf("Enter the number to check prime:");
scanf("%d",&n);
m=n/2;
for(i=2;i<=m;i++)
{
if(n%i==0)
{
printf("Number is not prime");
flag=1;
break;
}
}
if(flag==0)
printf("Number is prime");
return 0;
}
/* 8. Program to print half pyramid using *(asterisk symbol) */

#include<stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (i=1; i<=rows; ++i)
{
for (j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0
/* 9. Modify the above Program to print number triangle */

1
1 2
1 2 3
1 2 3 4
………
……….
Sum of digits algorithm

To get sum of each digits by c program, use the following


algorithm:
• Step 1: Get number by user
• Step 2: Get the modulus/remainder of the number
• Step 3: sum the remainder of the number
• Step 4: Divide the number by 10
• Step 5: Repeat the steps from step 2 while number is greater
than 0.
10.Sum of digits C program
#include<stdio.h>
int main()
{
int n,sum=0,m;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
m=n%10;
sum=sum+m;
n=n/10;
}
printf("Sum is=%d",sum);
return 0;
}
11.Program to Reverse a number
#include<stdio.h>
int main()
{
int n, reverse=0, rem;
printf("Enter a number: ");
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
printf("Reversed Number: %d",reverse);
return 0;
}
Palindrome check
• Get the number from user
• Hold the number in temporary variable
• Reverse the number
• Compare the temporary number with reversed
number
• If both numbers are same, print palindrome number
• Else print not palindrome number
12.Program for Palindrome check
#include<stdio.h>
int main() if(temp==sum)
{ printf("palindrome number ");
int n,r,sum=0,temp; else
printf("not palindrome");
printf("enter the number=");
return 0;
scanf("%d",&n); }
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
Armstrong number

An Armstrong number is a number such that the sum of the nth power of its digits is equal
to the number itself, where n is the number of digits in the number (taken here to mean
positive integer)

Eg1: 371 – No of digits = 3


33+73+13 = 27+343+1 = 371
Eg2: 1634 – No ff digits = 4
14+64+34+44 = 1+1296+81+256 = 1634
13. Program to check Armstrong number

#include <stdio.h>
#include <math.h>

int main() while (temp != 0)


{ {
int num, temp, rem, n = 0, result=0; rem = temp % 10;
printf("Enter an integer: "); result += pow(rem, n);
scanf("%d", &num); temp /= 10;
}
temp = num; if (result == num)
while (temp != 0) printf("%d is an Armstrong number.", num);
{ else
temp /= 10; printf("%d is not an Armstrong number.",
++n; num);
} return 0;
}
temp = num;
Fibonacci series upto N numbers
Start
1. N=?
2. a=0,b=1 N=5
3. Print a ,b
4. i=2 a=0,b=1

5. F=a+b Print a,b


6. Print F
i=2
7. a=b,b=F
8. i=i+1 F=a+b
9. If i<N go to step 5 Print F
10. Stop
a=b, b=F
i=i+1

Y No
i<N Stop
14. Program for Fibonacci Series: 0,1, 1, 2, 3, 5, 8, etc.
#include <stdio.h> 1. N=?
int main()
{ 2. a=0,b=1
int i, N, a = 0, b = 1, F; 3. Print a ,b
printf("Enter the number of terms: ");
scanf("%d", &N); 4. i=2
printf("Fibonacci Series: ");
5. F=a+b
for (i = 1; i <= N; ++i)
{ 6. Print F
printf("%d\t", a);
F = a+b; 7. a=b,b=F
a=b; 8. i=i+1
b=F;
} 9. If i<N go to step 5
return 0;
} 10. Stop

Enter the number of terms: 10


Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
Algorithm and flow chart for
COMPUTING FACTORIAL of N

N! = 1 * 2 * 3 * …… N

Algorithm
1. Start
2. Read N
3. Initialize i = 1,F = 1
4. F=F*i
5. i=i+1
6. Repeat steps 4 and 5 until i > N
7. Print F
8. Stop
15: Program for factorial print

You might also like