Modul 2 Last Part
Modul 2 Last Part
Modul 2 Last Part
FORMATTED INPUT
Formatted input refers to an input data that has been arranged particular format.
For example: 15.75 123 John
This line contains three pieces of data, arranged in a particular form. For example, the first part
of the data should be read into a variable float, the second into int, and the third part into char.
This is possible in C using the scanf function.
The general form of scanf is
The control string (format string) specifies the field format in which the data is to be entered and
the arguments arg1,arg2….argn specifies the address of the location where the data is stored.
The format string contains format specifications, consisting of the conversion character %, a data
type character and an optional number specifying the field width.
%wd
The percentage sign (%) indicates that a conversion follows. w is an integer number that
specifies the field width of the number to be read and d, known as data type character, indicates
that the number to be read is in integer mode. Consider the following example:
scanf(“%2d %5d”, &num1,&num2);
50 31426
The value 50 is assigned to num1 and 31426 to num2. Suppose if the input data line is 31426 50,
then 31 is assigned to num1 and num2 will be assigned 426. The value 50 that is unread will be
assigned to the first variable in the next scanf().
scanf(“%d %d”, &num1,&num2); will read the data 31426 50
correctly and assign 31426 to num1 and 50 to num2.
An input field may be skipped by specifying *in the place of field width. For example, the
statement
scanf(“%d %*d %d”, &a,&b)
will assign the data
123 456 789
as follows: 123 to a
%ws or %wc
The corresponding argument should be a pointer to a character array. %c may be used to read a
single character.
Reading of a string using%wc and %ws is illustrated in
15 p 1.575 coffee
correctly and assign the values to the variables in the order in which they appear.
20 150.25 motor
and return the value 1 if the following line is entered
20 motor 150.25
Commonly used scanf format codes are given in the table
FORMATTED OUTPUT
We have seen the use of print function for printing captions and numerical results.
The general form of printf statement is
printf(“control string”,arg1,arg2,…..argn);
Where w is an integer number that specifies the total number ofcolums for the output value and p
is another integer number that specifies the number of digits to the right of the decimal point (of
a real number) or the number of character to be printed from a string. Both w and p are optional.
Examples of formatted printf
printf(“programming in C”);
printf(‘’ “);
printf(‘’\n “);
printf(‘’%d,x “);
printf(‘’a = %f\n b=%f “,a ,b);
printf(‘’sum=%d “,1234);
printf(‘’\n\n “);
%wd
Where w specifies the minimum field width for the output.
The following examples illustrate the output of the number 9876under different formats:
Format output
printf (“%d”, 9876)
9 8 7 6
printf(“%6d”, 9876 ) 9 8 7 6
printf(“%2d”, 9876) 9 8 7 6
printf(“%-6d” 9876)
9 8 7 6
printf(“%06d” 9876)
0 0 9 8 7 6
It is possible to force the printing to be left –justified by placing a minus sign directly after the %
character. It is also possible to pad with zero the leading blanks by placing a 0(Zero) before the
field width specifier Zero (0) are known as flags.
Long integers specifying ld in the place of d in hd short integers.
%w.p f
The integer w indicates the minimum number of positions that are to be used for the display of
the value and the integer p indicates the number of digits to be displayed after the decimal
point(precision). The value, when displayed, is rounded to p decimal places and printed right-
justified in the field of w columns.
We can also display a real number in exponential notation by using the specification:
%w.p e
The following examples illustrate the output of the number y=98.7654 under different format
specifications:
Format output
printf(“%7.4f”,y) 9 8 . 7 6 5 4
printf(“%7.2f”,y) 9 8 . 7 7
printf(“%-7.2f”,y) 9 8 . 7 7
printf(“%f”,y) 9 8 . 7 6 5 4
printf(“%10.2e”,y) 9 . 8 8 e + 0 1
Printf(“%11.4e”,-y) - 9 . 8 7 6 5 e + 0 1
printf(“%-10.2e”,y) 9 . 8 8 E + 0 1
printf(“%e”,y)
9 . 8 7 6 5 4 0 e + 0 1
Printing of a single character
A single character can be displayed in a desired position using the format
%wc
The character will be displayed right-justified in the field of w columns. We can make the
display left – justified by placing a minus sign before the integer w. The default value for w is 1
Printing of Strings
The format specification for outputting string is similar to that of real number. It is the form
%w.ps
Where w specifies the field width for display and p instructs that only the first p characters of the
string are to be displayed. The display is right –justified.
The following examples show the effect of variety of specifications in printing a string “NEW
DELHI 110001”, containing 16 characters (including banks)
Specification output
CSE, CITECH 2018-19 Page 57
C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping
%s
N E W D E L H I 1 1 0 0 0 1
%20s N E W D E L H I 1 1 0 0 0 1
%20.10s N E W D E L H I
%0.5s N E W D
%-20.10s N E W D E L H I
%5s N E W D E L H I 1 1 0 0 0 1
Mixed data output
It is permitted to mix data types in one printfstatement.For example, the statement of the type
printf(“%d%f%s%c”,a,b,c,d);
Commonly used printf format codes
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 either e-type or f-type depending on
%i Print assigned decimal integer
%o Print a octal integer, without leading zero
%s Print a string
%u Print a unsigned decimal integer
%x Print a hexadecimal integer,without leading Ox
The following letters may be used as prefix for certain conversion characters
h for short integers
l for long integers or double
L for long double
So far we have discussed ways of controlling the flow of execution based on certain
specified conditions. C supports the goto statement to branch unconditionally from one point to
another in the program.
The goto requires a label in order to identify the place where the branch is to be made. A label is
any valid variable name, and must be followed by a colon. The label is placed immediately
before the statement where the control is to be transferred. The general forms of goto and label
statements are shown below:
Syntax:
goto begin;
is met, the flow of control will jump to the statement immediately following the label begin: This
happens unconditionally.
If the label: is before the statement goto label; a loop will be formed and some statements will be
executed repeatedly. Such a jump is known as a backward jump. On the other hand, if the label:
is placed after the goto label; some statements will be skipped and the jump is known as forward
jump.
A goto is often used at the end of the program to direct the control to go to the input statement, to
read further data. Consider the following example
Output
50.70
50.750000 7.123903
40
40.000000 6.324555
-36
Value 3 is negative
75
75.000000 8.660254
11.25
11.250000 3.354102
End of computation
Program (use goto to write a program to perform the sum of first n natural numbers)
void main()
int i=0,n,sum=0;
printf(“enter n”);
scanf(“%d”,&n);
loop:
sum=sum+i;
i=i+1;
if(i<=n)
goto loop;
printf(“sum=%d”,sum);
Program (use goto to write a program to check if the input marks is pass or fail)
void main()
int marks;
printf(“enter marks”);
scanf(“%d”,&marks);
if(marks<50)
goto fail;
else
goto pass;
fail:
printf(“failed”);
exit(0);
pass:
printf(“passed”);
Program (use goto to write a program to check if the input number is odd or even)
void main()
int n;
printf(“enter a number”);
scanf(“%d”,&n);
if(n%2==0)
goto even;
else
goto odd;
even:
printf(“even”);
exit(0);
odd:
printf(“odd”);
Return statement : return statement terminates the execution and returns control to the calling
function.
For example, more than one variable can be initialized at a time in the for statement. The
statements
p = 1;
for (n=0; n<17; ++n)
Can be rewritten as
for (p=1,n=0; n<17; ++n)
Like the initialization section, the increment section may also have more than one part. For
example the loop
for(n=1, m=50; n<=m; n=n+1, m=m-1)
{
p=m/n;
printf(“%d %d %d\n”, n, m, p);
}
is perfectly valid. The multiple arguments in the Increment section are separated by commas.
The third feature is that the test-condition may have any compound relation and the testing need
not be limited only to the loop control variable. Consider the example below:
sum 0;
for (i =1; i < 20 && sum < 100; ++i)
{
sun = sum+i;
printf("%d %d\n”, i, sum);
}
Another unique aspect of for loop is that one or more sections can be omitted, if necessary.
Consider the following statements
m=5;
for (; m !=100;)
{
printf(“%d\n”,m);
m=m+5;
}
we can set up time delay using the null statement(;) as follows:
for(i=1;i<=1000;i++);
The loop is executed 1000 times without producing any output; it simply causes a time delay.
Nesting of for loop
Nesting of for loops that is one for statement within another for statement, is allowed in C. For
example two loops can be nested as follows:
Syntax:
Write a C program using nested for loop to print the following pattern.
i) * ii) 1 2 3 4
* * 1 2 3
* * * 1 2
* * * * 1
main()
{
int i,j;
for (i=1;i<=4; i++)
{
for (j=1;j<=i; j++)
{
printf(“*\t”);
}
printf(“\n”);
}
}
main()
{
int i,j;
for (i=4;i>=1; i--)
{
for (j=1;j<=i; j++)
{
printf(“%d\t”,j);
}
printf(“\n”);
}
}
Just like for, even while and do while can be nested.
void main()
{
int x,y,sum;
for(x=1;x<=2;x++)
{
for(y=1;y<=2;y++)
{
sum=x+y;
printf(“\nx=%d”,x);
printf(“\ny=%d”,y);
printf(“\nsum=%d”,sum);
void main()
{
int x,y,sum;
x=1;
while(x<=2)
{
y=1;
while(y<=2)
{
sum=x+y;
printf(“\nx=%d”,x);
printf(“\ny=%d”,y);
printf(“\nsum=%d”,sum);
y++;
x++;
Output:
x=1
y=1
sum=2
x=1
y=2
sum=3
x=2
y=1
sum=3
x=2
y=2
sum=4
JUMPS IN LOOPS
C permits a jump from one statement to another within a loop as well as a jump out of a loop.
An early exit from a loop can be accomplished by using the break statement or the goto
statement.
These statements can also be used within while, do, or for loops. When a break statement-is
encountered inside a loop, the loop is immediately exited and the program continues with the
statement immediately following the loop.
Another important use of goto is to exit from deeply nested loops when an error occurs. A simple
break statement would not work here.
Jumping within and exiting from the loop with goto statement
Program (to print first 10 even numbers not greater than 10)
void main()
int i;
for(i=2;i<=20;i=i+2)
if(i>10)
break;
printf(“%d\t”,i);
Program (Input 100 numbers, stop on encountering a negative value. Find the sum and
average of inputted values)
void main()
int i;
float n,sum=0,average;
for(i=0;i<100;i++)
scanf(“%d”,&n);
if(n<0)
break;
sum=sum+x;
average=sum/i;
printf(“sum=%f,average=%f”,sum,average);
During the loop operations, it may be necessary to skip a part of the body of the loop under
certain conditions. Like the break statement, C supports another similar statement called the
continue statement.
However, unlike the break which causes the loop to be terminated, the continue, causes the loop
to be continued with the next iteration after skipping any statements in between. The continue
statement tells the compiler, "SKIP THE FOLLOWING STATEMENTS AND CONTINUE
WITHTHE NEXT ITERATION". The format of the continue statement is simply
Syntax:
continue;
Avoiding goto
As mentioned earlier, it is a good practice to avoid using goto. When goto is used, many
compilers generate a less efficient code. In addition, using many of them makes a program logic
complicated and renders the program unreadable. The goto jumps shown in below fig would
cause problems and therefore must be avoided
int i;
for(i=2;i<=20;i=i+2)
if(i==6||i==8)
continue;
printf(“%d\t”,i);
Program (Input 1000 numbers, stop on encountering 9999. Find the square root of each
number only if it is non negative)
#include<stdio.h>
#include<math.h>
void main()
int i=0,negative=0;
float n,sq;
for(i=0;i<1000;i++)
scanf(“%d”,&n);
if(n==9999)
break;
if(n<0)
negative++;
printf(“number is negative”);
continue;
sq=sqrt(n);
We have just seen that we can jump out of a loop using either the break statement or goto
statement. In a similar way, we can jump out of a program by using the library function exit( ).
In case, due to some reason, we wish to break out of a program and return to the operating
system, we can use the exit() function, as shown below
…………
………...
If (test-condition) exit(0);
………..
………..
The exit() function takes an integer value as its argument Normally zero is used to Indicate
normal termination and a nonzero value to indicate termination due to some error or abnormal
condition. The use of exit() function requires the inclusion of the header file <stdlib.h>
Return statement : return statement terminates the execution and returns control to the calling
function.
Structured programming
The use of structured programming techniques helps ensure well-designed programs that are
easier to write, read, debug and maintain compared to those that are unstructured.
We often use test expressions in the if, for, while and do statements that are evaluated and
compared with zero for making branching decisions.
We can write concise test expressions without using any relational operators.
if (expression ==0)
is equivalent to
if(!expression)
similarly,
if (expression! = 0)
is equivalent to
if(expression)
for example, if (m%5==0&&n%5==0) is same as if(!(m%5)&&!(n%5)
Programs
1. Program to compute the roots of a quadratic equation by accepting the coefficients.
Print appropriate messages.
Algorithm:
Step1: [Initialize]
start
Step2: [Input the coefficients of quadratic equation]
Read a,b,c.
Step3: [Check for valid coefficients]
If (a==0)
Then invalid coefficients. Go to step 6
Step4:[Compute discriminate value as d]
d=b*b-4*a*c
Program:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
floata,b,c, d,root1,root2,real,imag;
printf("Enter the three coefficients:\n");
scanf("%f%f%f",&a,&b,&c);
if(a==0)
{
printf("Invalid coefficients");
exit(0);
}
d=b*b-4*a*c;
if(d>0)
{
root1=(-b+(sqrt(d)))/(2.0*a);
root2=(-b-(sqrt(d)))/(2.0*a);
printf("The roots are real and distinct....\n");
printf("root1=%f \n root2=%f\n",root1,root2);
}
else if(d==0)
{
root1=root2=-b/(2.0*a);
printf("The roots are real and equal....\n");
printf("root1=%f \n root2=%f\n",root1,root2);
}
else
{
real=-b/(2.0*a);
imag= sqrt(fabs(d))/(2.0*a);
printf("The roots are complex and imaginary....\n");
B(m,x) = , m >= x
A table of binomial coefficients is required to determine the binomial coefficient for any set
of m and x
B(m,o) = 1
Further,
B(o,o) = 1
That is, the binomial coefficient is one when either x is zero or m is zero. The program prints
the table of binomial coefficients for m = 10. The program employs one do loop and one
while loop.
Program (method-1)
#include<stdio.h>
#define MAX 10
int main()
int m, x, binom;
printf(" m x");
printf("%4d", m);
m = 0;
do
printf("\n");
printf("%4d", m);
x = 0;
binom = 1;
while (x <= m)
if(m == 0 || x == 0)
printf("%4d", binom);
else
printf("%4d", binom);
x = x + 1;
m = m + 1;
return 0;
Output
Program (method-1)
#include<stdio.h>
#define MAX 10
int main()
int m, x, binom;
printf(" m x");
printf("%4d", m);
m = 0;
do
printf("\n");
printf("%4d", m);
x = 0;
binom = 1;
while (x <= m)
if(m == 0 || x == 0)
printf("%4d", binom);
else
binom = factorial(m)/(factorial(m-x)*factorial(x));
printf("%4d", binom);
x = x + 1;
m = m + 1;
return 0;
int factorial(int n)
int f=1,i;
f=f*i;
return f;
}
Output
Pascal’s triangle is named after a French mathematician called Blasie Pascal. It is a triangular array of the
CSE, CITECH 2018-19 Page 79
C Programming for Problem solving (18CPS13/23) Module 2: Branching and Looping
binomial coefficients. 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>
int main()
int n, i, j;
printf("enter n:");
scanf("%d",&n);
printf("\n");
printf(" ");
printf("%4d", ncr(i,j));
return 0;
int factorial(int n)
int f=1,i;
f=f*i;
return f;
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
#include <stdio.h>
int main()
int n,r;
scanf("%d%d",&n,&r);
return 0;
int factorial(int n)
int f=1,i;
f=f*i;
return f;
Program (to find gcd of two numbers using ternary operator and for loop)
void main()
int a,b,min,i;
scanf(“%d%d”,&a,&b);
min=a<b?a:b;
for(i=min;i>0;i--)
if((a%i==0)&&(b%i==0)
printf(“gcd is %d”,a);
break;
}
Program (to find gcd of two numbers using Euclid’s Algorithm)
void main()
int a,b,r;
scanf(“%d%d”,&a,&b);
while(b!=0)
r=a%b;
a=b;
b=r;
printf(“gcd is %d”,a);
}
Program (to read a sentence and count the frequency of vowels and consonants)
#include<stdio.h>
#include<string.h>
void main()
int vc=0,cc=0;
char s[100],ch;
printf(“Enter a sentence”);
gets(s);
for(i=0;i<strlen(s);i++)
if(isalpha(s[i]))
ch=tolower(s[i]);
vc++;
else
cc++;
}
Program (to print Fibonacci series upto n)
#include<stdio.h>
void main()
int num1=0,num2=1,n,i,fib;
printf(“Enter n”);
scanf(“%d”,&n);
printf(“%d\t%d\t”,num1,num2);
for(i=3;i<=n;i++)
fib=num1+num2;
printf(“%d\t”,fib);
num1=num2;
num2=fib;
void main()
int num1=0,num2=1,n,i,fib;
printf(“Enter n”);
scanf(“%d”,&n);
for(i=3;i<=n;i++)
fib=num1+num2;
num1=num2;
num2=fib;
#define maxsize 20
void main()
double q;
p=1;
for(n=0;n<=maxsize;n++)
if(n==0);
p=1;
else
p=p*2;
q=1/(double)p;
printf(“%ld\t%ld\t%lf”,n,p,q);
void main()
int n,x,i,y=1;
printf(“enter n,x”);
scanf(“%d%d”,&n,&x);
for(i=1;i<=n;i++)
y=y*x;
printf(“result is %f”,y);