Module 2
Module 2
MODULE 2
MANAGING INPUT AND OUTPUT OPERATIONS
INTRODUCTION
Reading, processing and writing of data are three essential functions of a computer
program.
There are two methods. The first method is to assign the values and the second method
is to use input function scanf to read data and output function printf to write data.
Ex: #include<stdio.h> Includes function calls such as printf( ) and scanf( ) into the
source code when compiled.
READING A CHARACTER
The simplest way of all input/output operations is reading a character from the ‘standard
input’ unit (usually keyboard) and writing it to the ‘standard output’ (usually the screen).
Reading a single character can be done by using the function getchar and it does not
have any parameter.
The getchar function can also be used to read the characters successively until the return
key is pressed.
The character function are contained in the file type ctype.h and therefore the
preprocessor directive #include<ctype.h> is included.
And the functions of ctype.h returns 1 if (TRUE) and 0 if (FALSE).
Function Test
isalnum(c) Is c alphanumeric
character?
isalpha(c) Is c alphabetic character?
isdigit(c) Is c a digit?
islower(c) Is c a lower case letter?
isupper(c) Is c a upper case letter?
www.vtuupdates.com Page 1
C Programming for problem solving 21CPS13/23
Example Program:
#include<stdio.h>
#include<ctype.h>
void main( )
{
char key;
printf(“Enter any key\n”);
key=getchar( );
if(isalpha(key))
printf(“The entered key is a letter\n”);
else if(isdigit(key))
printf(“The entered key is a digit\n”);
else
prinprintf(“The entered key is not alphanumeric\n”);
}
www.vtuupdates.com Page 2
C Programming for problem solving 21CPS13/23
OUTPUT:
WRITING A CHARACTER
Example: name=’y’;
putchar(name);
The characters entered can be converted into reverse i.e., from upper to lower case and
vice versa.
The functions used to convert are toupper, tolower.
Example Program:
#include<stdio.h>
#include<ctype.h>
void main( )
{
char alphabet;
printf(“Enter any alphabet\n”);
alphabet=getchar( ); Output
if(islower(alphabet)) 1. Enter any alphabet a
putchar(toupper(alphabet)); A
else 2. Enter any alphabet A
putchar(tolower(alphabet)); a
}
www.vtuupdates.com Page 3
C Programming for problem solving 21CPS13/23
FORMATTED INPUT
Formatted input refers to an input data that has been arranged in particular format.
Ex: 152 Rajesh
In the above example the first part contains integer and the second part contains
characters. This is possible with the help of scanf function.
The control string specifies the field form in which data should be entered and the
arguments arg1, arg2,…..,argn specifies the address of the location where the data is stored.
The width of the integer number can be specified using %wd.
Example-2:
– scanf(“%2d %2d”, &a, &b);
%2d two digit integer
%2d two digit integer
45 67 25
a=45 b=67
Note: 25 is not at all stored
The input field may be skipped using * in the place of field width.
Example-3:
– scanf(“%2d %*d %2d”, &a, &b);
%2d two digit integer
%*d skip this integer
45 25 63
a=45
25 is skipped
b=63
The scanf function can read single character or more than one character using %c or %s.
www.vtuupdates.com Page 4
C Programming for problem solving 21CPS13/23
The below table shows the scanf format codes commonly used.
The l can be used as a prefix for long integer. Ex: %ld
Code Meaning
%c Read a single character
%d Read a decimal integer
%e, %f, Read a floating point value
%g
%h Read a short integer
%i Read a decimal integer
%o Read a octal integer
%s Read a string
%u Read an unsigned decimal integer
%x Read a hexadecimal integer
%[ ] Read a string of word
FORMATTED OUTPUT
The printf function is used for printing the captions and results.
www.vtuupdates.com Page 5
C Programming for problem solving 21CPS13/23
%07d
0 0 0 7 7 7 7
Output:
10 77
6.3f means totally 6 locations are
allocated out of which 3 is for number
of decimal places.
%6.3f
1 0 . 7 7 6
www.vtuupdates.com Page 6
C Programming for problem solving 21CPS13/23
Output:
a=10 b=77 c=88
%4d
Width of 4 memory space is
1 0 allocated and printed from right
side
The below table shows the scanf format codes commonly used.
Code Meaning
%c Print a single character
%d Print a decimal integer
%e Print a floating point value in exponent form
%f Print a floating point value without exponent
%g Print a floating point value with or without exponent
%h Print a short integer
%i Print a decimal integer
%o Print a octal integer
%s Print a string
%u Print an unsigned decimal integer
%x Print a hexadecimal integer
%[] Print a string of word
www.vtuupdates.com Page 7
C Programming for problem solving 21CPS13/23
Examples: a=9876; 9 8 7 6
printf(“%d”, a);
9 8 7 6
printf(“%6d”,a);
printf(“%-6d”,a);
6d”,a); 9 8 7 6
printf(“%3d”,a);
9 8 7 6
gets and puts are line oriented input output functions available in the <stdio.h> header
file.
gets( ): Alternative method to read strings is gets( ) (read it as get string) function which
is an unformatted string input function. Advantage of gets( ) is it can read multi-word
word strings.
Example: char name[10];
gets(name);
puts( ): This function can be used to display entire string on monitor screen without the
help of %s specifier.
Example: char name[ ] = “Bengaluru” puts(name);
puts( ) will display the string value stored in parameter passed to it on monitor.
In this case it is—Bengaluru.
www.vtuupdates.com Page 8
C Programming for problem solving 21CPS13/23
INTRODUCTION
C language possesses such decision making capabilities by supporting the following
statements:
1. If statement
2. Switch statement
3. Conditional operator statement
4. goto statement
These statements are popularly known as decision making statements. Also known as
control statements.
The basic decision statement in the computer is the two way selection.
The decision is described to the computer as conditional statement that can be answered
TRUE or FALSE.
If the answer is TRUE, one or more action statements are executed.
If answer is FALSE, the different action or set of actions are executed.
Regardless of which set of actions is executed, the program continues with next
statement.
C language provides following two-way selection statements:
1. if statement
2. if – else statement
3. Nested if else statement
4. Cascaded if else (also called else-if ladder)
www.vtuupdates.com Page 9
C Programming for problem solving 21CPS13/23
The Expression is evaluated first, if the value of Expression is true (or non zero) then
Statement1 will be executed; otherwise if it is false (or zero), then Statement1 will be
skipped and the execution will jump to the Statement2.
Remember when condition is true, both the Statement1 and Statement2 are executed in
sequence. This is illustrated in Figure1.
Statement1
Statement2
www.vtuupdates.com Page 10
C Programming for problem solving 21CPS13/23
if (Expression)
{
(true-block;) Statement1;
}
else
{
(false-block;) Statement2;
}
Statement3;
If the Expression is true (or non-zero) then Statement1 will be executed; otherwise if it is
false (or zero), then Statement2 will be executed.
In this case either true block or false block will be executed, but not both.
This is illustrated in Figure 2. In both the cases, the control is transferred subsequently to
the Statement3.
Statement2 Statement1
Statement3
www.vtuupdates.com Page 11
C Programming for problem solving 21CPS13/23
Example:
void main( )
{
int a=10, b=11;
if (a >b)
{
printf(“a is bigger and value is= %d”, a);
}else
e printf(“b is bigger and value is= %d”, b);
l
}
s
e
{
Output: b is bigger and value is=11
}
}
www.vtuupdates.com Page 12
C Programming for problem solving 21CPS13/23
3. Nested if .. else statement: When a series of decisions are involved, we have to use
more than one if..else statement in nested form as shown below in the general syntax.
if (Expression1)
{
if(Expression2)
{
Statement1;
}
else
{
Statement2;
}
}
else if(Expression3)
{
Statement3;
}
else
{
Statement4;
}
www.vtuupdates.com Page 13
C Programming for problem solving 21CPS13/23
}
else
{
if(B>C)
{
printf(“largest=%d”, B);
}
else
{
printf(“largest=%d”, C);
www.vtuupdates.com Page 14
C Programming for problem solving 18CPS13
}
}
}
Output: largest=20
4. else-if ladder or cascaded if else: There is another way of putting ifs together when
multipath decisions are involved. A multi path decision is a chain of ifs in which the
statement associated with each else is an if. It takes the following form.
if (Expression1)
{
Statement1;
}
else if(Expression2)
{
Statement2;
}
else if(Expression3)
{
Statement3;
}
else
{
Statement4;
}
Next Statement;
C Programming for problem solving 18CPS13
if(choice==1)
printf(“sum=%d”, a+b);
printf(“difference=%d”, a-b);
else if(choice==3)
printf(“product=%d”, a*b);
else if (choice==4)
printf(“rem=%d”, a%b);
else
printf(“Invalid option”);
}
SWITCH STATEMENT
switch(choice)
{
case label1: block1;
break;
case label2: block2;
break;
case label3: block-3;
break;
default : default-block;
break;
}
Here switch, case, break and default are built-in C language words.
If the choice matches to label1 then block1 will be executed else if it evaluates to label2
then block2 will be executed and so on.
If choice does not matches with any case labels, then default block will be executed.
float div;
printf(“Enter two numbers:”); scanf(“%d%d”,&a,&b);
printf(“1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division\n 5.Remainder”);
printf(“Enter your choice:\n”);
scanf(“%d”,&ch); switch(ch)
{
case 1: res=a+b;
printf(“Result=%d\n”,res); break;
case 2: res=a-b;
printf(“Result=%d\n”,res); break;
case 3: res=a*b;
printf(“Result=%d\n”,res); break;
case 4: div=(float)a/b;
printf(“Result=%f\n”,div); break;
case 5: res=a%b;
printf(“Result=%d\n”,res); break;
default: printf(“Wrong choice!!\n”); exit0); (
}
}
In this program if ch=1 case ‘1’ gets executed and if ch=2, case ‘2’ gets executed and so on.
Ternary operator or conditional operator (?:)
C Language has an unusual operator, useful for making two way decisions.
This operator is combination of two tokens ? and : and takes three operands.
.
Syntax:
Expression1 ? Expression 2 : Expression 3
Where,
Expression1 is Condition
Expression2 is Statement Followed if Condition is True Expression3 is Statement
Followed if Condition is False
Meaning of Syntax:
1. Expression1 is nothing but Boolean Condition i.e. it results into either TRUE or
FALSE
#include<stdio.h>
void main( )
{
int num;
printf("Enter the Number : "); scanf("%d",&num);
flag = ((num%2==0)?1:0); if(flag==0)
printf("\nEven");
else
printf("\nOdd");
}
Goto statement
goto is an unconditional branching statement. The syntax of goto is as follows:
goto label;
statement1;
statement2;
label:
void main( )
{
int a=5, b=7;
goto end;
a=a+1;
b=b+1;
end: printf(“a=%d b=%d”, a,b);
}
MODULE 2
Decision Making and Looping
INTRODUCTION
Loops can be classified into two types based on the placement of test-condition.
If the test-condition is given in the beginning such loops are called pre-test loops (also
known as entry-controlled loops).
Otherwise if test condition is given at the end of the loop such loops are termedas post-
test loops (or exit controlled loops).
Note Figure 1:
1. Here condition is at the beginning of loop. That is why it is called pre-test loop
2. It is also called as entry controlled loop because condition is tested before entering
into the loop.
3. while is a keyword which can be used here.
Note Figure 2:
1. Here condition is at the end of the loop. That is why it is called post-test loop.
2. It is also called as exit controlled loop because condition is tested after body of the
loop is executed at least once.
3. do and while are keywords which can be used here.
LOOPS IN C:
C language provides 3 looping structures namely:
1. while loop
2. do….while loop
3. for loop
The loops may be classified into two general types. Namely:
1. Counter-controlled loop
2. Sentinel-controlled loop
When we know in advance exactly how many times the loop will be executed, we use a
counter-controlled loop. A counter controlled loop is sometimes called definite repetition
loop.
In a sentinel-controlled loop, a special value called a sentinel value is used to change the
loop control expression from true to false. A sentinel-controlled loop is often called
indefinite repetition loop.
i. while loop:
It is a pre-test loop (also known as entry controlled loop). This loop has following
syntax:
while (condition)
{
statement-block;
}
In the syntax given above ‘while’ is a key word and condition is at beginning of the
loop.
If the test condition is true the body of while loop will be executed.
After execution of the body, the test condition is once again evaluated and if it is true,
the body is executed once again.
This process is repeated until condition finally becomes false and control comes out of
the body of the loop.
Flowchart
Here is an example program using while loop for finding sum of 1 to 10.
Example: Before loop execution:
ii. do…. while loop: It is a post-test loop (also called exit controlled loop) it has two
keywords do and while. The General syntax:
Do
{
statement-block;
} while (condition);
In this loop the body of the loop is executed first and then test condition is evaluated.
If the condition is true, then the body of loop will be executed once again. This process
continues as long as condition is true.
When condition becomes false, the loop will be terminated and control comes out of the
loop.
Flowchart:
void main( )
{
Before loop execution:
N=10;
i=1; N=10, sum=0, i=1
sum=0; First Round:
do
{
N=10, sum=1, i=2
sum=sum+i; i=i+1;
} Second Round:
while (i<=N);
printf(“%d”, sum); N=10, sum=3, i=3
}
General syntax:
for( initialization; test-condition; updation)
{
Body-of loop;
}
1. In this loop first initialization of control variable is done first, using assignments such as
i=1, count=0. The variable i count are called loop control variable.
2. The value of control variable is tested using the test condition. The test condition is
evaluated. If the condition is true, the body of the loop is executed; otherwise loop will be
terminated.
3. When the body of the loop is executed, the control transferred back to the for statement
to update the loop variable. And then condition is checked once again. If condition is true
once again body will be executed once again. This process continues till the value of the
control variable fails to satisfy the test condition.
Flowchart:
Example: Same program to find some of 1 to 10 numbers can be written using for loop as
follows:
void main( )
{
int i, N=10, sum=0;
Note: In for loops whether both i++ or ++i operations will be treated as pre-increment only.
In some programming situations within one for loop we have to write another for loop.
Such embedded for loops are called nested for loops.
Following diagram depicts a nested for loop flowchart.
Example:
Here is an example program segment with sample outputs that illustrates the working of a
nested for loop:
for(cols=1;cols<=3; cols++)
{
printf(“%d %d”, rows, cols);
}
Working:
1. Initially value of rows=1 and 1 <=4 is true so control enters to
inner loop
2. In inner loop cols=1 and 1<=3 is also true so body of the loop (i.e. printf gets
executed)
Following are the outputs obtained in every repetition of inner/outer for loops:
If any of these three components are missing program behaves indifferently. For
instance if updating statement is missing loop goes into infinite mode as shown in
following example:
void main( )
{
int ctr=1, N=10;
while(ctr<=N)
{
printf(“Hello World\n”); printf(“Hi Galaxy\n”);
}
}
Output: it prints,
Hello World
Hello Galaxy
infinite number of times as ctr value remains 1 forever as
void main( )
{
int ctr, N=10; while(ctr<=N)
{
printf(“Hello World\n”); printf(“Hi Galaxy\n”); ctr=ctr+1;
}
Output: Loop will not at all get executed as initial value of ctr is unknown!
So program prints nothing.
3. JUMPS IN LOOPS
Break and continue: break and continue are unconditional control construct.
i. break
This statement is useful to terminate a loop and transfer control out of loop
under special situations.
break statement works with while, do….while, for and switch statements.
Following program syntax diagrammatically represents the working
mechanism of break statement.
Note: If break statement is used in the nested loops, the control will come out
from the inner loop; still the outer loop is active.
Note:
Working of break statement:
When condition2 is true the loop gets terminated and control is transferred to
statement5 (which is outside the loop). Here we can observe that even though
Note: If break statement is used in the nested loops, the control will come out from the
void main( )
{
int i; for(i=1;i<=5;i++)
{
if(i==3)
ii. Continue
Statement is helpful to skip particular set of statements in loop body and to continue
execution from the beginning of loop.
Following syntax clearly depicts how control shifts to beginning of a loop on finding
continue statement.
Note:
Working of continue statement:
When condition2 is true continue statement is executed which results in transfer
of control to beginning of while loop skipping statement4 and statement5.
A table of binomial coefficients is required to determine the binomial coefficient for any set
of m and x.
B(m,0) = 1
B(m, x) = B(m, x-1) [ − +1] , X = 1, 2, 3, …., m
Further,
B(0, 0) = 1
That is, the binomial coefficient is one when either x is zero or m is zero. The program
below points the table of binomial coefficients for m=10. The program employs one do
loop and one while loop.
Program:
printf(“ m x”);
for(m = 0; m <=10; ++m) printf(%4d”, m);
printf(“\n \n”);
m = 0;
do
{
printf(“%2d”, m); x = 0;
binom = 1; while(x<=m)
{
if(m == 0 || x ==0) printf(“%4d”, binom);
else
{
binom = binom * (m-x + 1) / x; printf(“%4d”, binom);
}
x = x + 1;
}
printf(“\n”); m=m+1;
}
while (m<= MAX);
printf(“ \n”);
}
OUTPUT:
mx 0 1 2 3 4 5 6 7 8
----------------------------------------------------- ----------------------------------------
- --
0 1
1 1 1
2 1 2 1
3 1 3 3 1
4 1 4 6 4 1
5 1 5 10 10 5 1
6 1 6 15 20 15 6 1
Pascal’s Triangle
One of the most interesting Number Patterns is Pascal's Triangle (named after
Blaise Pascal, a famous French Mathematician and Philosopher).
To build the triangle, start with "1" at the top, then continue placing numbers below it in
a triangular pattern.
Each number is the numbers directly above it added together.
#include <stdio.h>
long factorial(int);
int main()
{
int i, n, c;
printf("Enter the number of rows you wish to see in pascal triangle\n"); scanf("%d",&n);
{
for (c = 0; c <= (n - i - 2); c++) printf(" ");
printf("\n");
}
return 0;
}
long factorial(int n)
{
int c;
long result = 1;
return result;
}
QUADRATIC EQUATION
The Quadratic Formula uses the "a", "b", and "c" from "ax2 + bx + c", where "a", "b",
and "c" are just numbers; they are the "numerical coefficients" of the quadratic equation
they've given you to solve.
#include<stdio.h>
#include<math.h>
void main( )
{
float x1, x2, a, b, c, disc;
printf("Enter the coefficients a, b and c\n");
scanf("%f%f%f",&a,&b,&c);
disc=(b*b)-(4*a*c);
if(disc == 0)
{
x1= -b/(2*a);
x2= -b/(2*a);
printf("The roots are real and equal\n");
printf("1st root = %f\n",x1);
printf("2nd root = %f\n",x2);
}
else if(disc > 0)
{
x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
printf("The roots are real and distinct\n");
printf("1st root = %f\n",x1);
printf("2nd root = %f\n",x2);
}
else
{
x1=-b/(2*a);
x2=sqrt(fabs(disc))/(2*a);
printf("The roots are imaginary\n");
printf("1st root = %f + i%f\n",x1,x2);
printf("2nd root = %f - i%f\n",x1,x2);
}
}
Output
Enter the coefficients a, b and c 1 2 3
The roots are imaginary
1st root = -1.000000 + i1.414214
2nd root = -1.000000 - i1.414214
Output is:
Round-1: i=1, j=3
4. sum=0
for(n=1; n!=10; n+=2)
sum = sum+n;
Output is:
Round-1: n=1, 1!=10 is true
sum=1
Round-2 n=3, 3!=10 is true
sum=4
Round-3 n=5, 5!=10 is true
sum=9
Round-4 n=7, 7!=10 is true
sum=1