18bma55s U2
18bma55s U2
Reading, processing and wri ng of data are the three essen al func ons of a computer program.
Programs take some data as input and display the processed data as result.
● We have two methods of providing data to the program variables.
o One method is to assign values to variables through assignment statements like
y = 56; amt = 50000;
o Second method is to use the input func on scanf (meaning scan forma ed)
which can read data from a keyboard. Output func on prin (meaning print
forma ed) is used to show results in the terminal.
● These func ons are collec vely known as the standard I/O library. If we use these
func ons in a program then we must include the statement #include <stdio.h> at the
beginning of the program.
● The statement #include <math.h> should be wri en in the beginning, if we use
mathema cal func ons like cos(x), sin(x) in the program.
READING A CHARACTER
Reading a single character can be done by using the func on getchar. This can also be done
with the help of scanf func on. The getchar takes the form variable_name = getchar();
The variable_name is a valid C name that has been declared as char type. When this statement is
encountered, the computer waits un l a key is pressed and then assigns that character as the value to
the getchar func on. Since the getchar func on is used on the RHS of an assignment statement, the
character value of getchar is in turn assigned to the variable name on the LHS. For example
char name;
name = getchar();
The above statement will assign the character ‘N’ to the variable name when we press the key N on the
keyboard. The getchar func on may be called successively to read the characters contained in a line of
text. For example:
_______
_______
char cityname;
cityname = ‘ ‘;
while(cityname != ‘\n’)
{
cityname = getchar();
}
_______
_______
C supports many other func ons to test the character type, these func ons are contained in the file
ctype.h and therefore the statement #include <ctype.h> must be included in the beginning of the
program to use the character type test func ons.
Character test func ons
Func on Test
isalnum(c) Is c an alphanumeric character?
isalpha(c) Is c an alphabe c character?
isdigit(c) Is c a digit?
islower(c) Is c lower case le er?
isprint(c) Is c a printable character?
ispunct(c) Is c a punctua on mark?
isspace(c) Is c a white space character?
isupper(c) Is c an upper case le er?
WRITING A CHARACTER
Like getchar, there is an analogous func on putchar for wri ng characters one at a me to the
terminal. It takes the form putchar (variable_name); where variable_name is a type char
variable containing a character. For example
answer = ‘y’;
putchar (answer); displays the character y on the screen.
The statement putchar (‘\n’); would cause the cursor on the screen to move to the beginning of the
next line.
Program
#include <stdio.h>
#include <ctype.h>
main()
{
char sec on;
prin (“Enter sec on”);
putchar(‘/n’);
sec on = getchar();
if (islower(sec on ))
putchar(toupper(sec on));
else
putchar(tolower(sec on));
}
OUTPUT
1) Enter sec on 2) Enter sec on 3) Enter sec on
FORMATTED INPUT
Forma ed input refers to an input data that has been arranged in a par cular format. For
example 15.23 3456 Meena This line contains three pieces of data, arranged in a par cular
form. 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 func on. The general form of scanf statement to
read more than one data is scanf (“control string”, arg1, arg2, …, argn);
The control string specifies the field format in which the data is to be entered and the arguments arg1,
arg2, … argn specify the address of loca ons where the data is stored. The arguments are separated by
commas. The control string (also known as format string) contains field specifica ons for input data. It
may include
● Field ( or format) specifica ons, consis ng of the conversion character %, data type character
and an op onal number(specifying the field width)
● Blanks, tabs or newlines.
The data type character indicates the type of data that is to be assigned to the variable. Field width
specifier is op onal.
The field specifica on for reading an integer number is %w sd The percentage sign (%) indicates the
conversion specifica on, w specifies the field width of the integer number to be read and d indicates the
data type character that reads the integer number.
For example scanf(“%2d %5d”, &num1, &num2);
The correct input data to be given is of the form 50 32145. This input assigns 50 to variable num1 and
32145 to variable num2.
If we give data as 32145 50 This input assigns 32 to variable num1 and 145 to variable num2.
● Input data items must be separated by spaces, tabs or newlines.
● Punctua on marks do not count as separators.
● When the scanf func on searches the input data line for a value to be read, it will always bypass
any white space characters.
● If a floa ng point number is entered instead of an integer, then the frac onal part will be
neglected. Once the invalid character ‘.’ is encountered the scanf statement may skip further
input.
● Another example: scanf(“%d %*d %d”, &a, &b); In this example the middle input field may be
skipped by specifying * .
If we give input data as 123 454 789 then value 123 assigns to variable a, 454 is skipped
because of * and 789 assigns to variable b.
● It is legal to use non-white space character between field specifica ons however scanf expects a
matching character in receiving input in the given loca on. For example scanf(“%d-%d, &a,
&b); accepts input like 123-456 and assigns 123 to variable a and 456 to variable b.
● The field specifica on for reading long integers is %ld (ell d) and %hd to read short integers.
Unlike integer numbers, the field width of real numbers is not to be specified and therefore
simple specifica on is %f for both decimal point nota on and exponen al nota on. For example
scanf(“%f %f %f”,&x, &y, &z); accepts input data 475.67 23.678 87.56E-2 assigns value 475.67
to x, value 23.678 to y and value 87.56E-2 to z.
For double data type the specifica on should be %lf (ell f).
A number may be skipped using %*f specifica on.
To read a single character from the keyboard we know to use the getchar func on. The same
can be achieved using the scanf func on. The field specifica on %ws or %wc reads character
strings. %c may be used to read a single character.
Some version of C supports the specifica on %[characters] means that only the characters
specified within the brackets are permissible in the input string. The specifica on %[^chararacters]
does exactly the reverse ie., the characters specified a er circumflex (^) are not permi ed in the input.
In one scanf statement more than one data type values can be read by giving specifica ons in order and
type. When an a empt is made to read an item that does not match the type expected, the scanf
func on does not read any further and immediately returns the values read. The statement scanf(“%d
%c %f %s”, &count, &code, &ra o, name); will read the data 15 p 1.343 coffee correctly and
assigns the value to the variables in the same order as they appear.
When a scanf func on completes reading its list, it returns the value of number of items that are
successfully read. This value can be used to test whether any errors occurred while reading the input. For
example scanf(“%d %f %s”, &a, &b, name); will return the value 3 if the following data is typed in
20 150.65 motor.
It returns value 1 if the following line 20 motor 150.65 is encountered.
POINTS TO REMEMBER
● All func on arguments, except the control string, must be pointers to variables
● Format specifica ons contained in the control string should match the arguments in order.
● Input data items must be separated by spaces and must match the variables receiving the input
in the same order.
● The reading will be terminated, when scanf encounters a mismatch of data or a invalid character
for the value being read.
● When searching for a value, scanf ignores line boundaries and simply looks for the next
appropriate character.
● Any unread data items in a line will be considered as part of the data input line to the next scanf
call.
● When the field width specifier w is used, it should be large enough to contain the input data size.
FORMATTED OUTPUT
We have seen the use of prin func on for prin ng cap ons and numerical results. The prin statement
provides certain features that can be effec vely used to control the alignment and spacing of print-outs
on the terminals. The general form of prin statement is
prin (“control string”, arg1, arg2, …, argn);
Control string consists of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specifica ons that define the output format for display of each item.
3. Escape sequence characters such as \n, \t and \b.
The control string indicates how many arguments follow and what their types are. The arguments arg1,
arg2, …, argn are the variables whose values are forma ed and printed according to the specifica ons of
the control string. The arguments should match in number, order and type with the format
specifica ons.
OUTPUT OF INTEGERS
The format specifica on for prin ng an integer number is %wd where w specifies the minimum field
width for the output. However if a number is greater than the specified field width, it will be printed in
full, overriding the minimum specifica on. d specifies that the datatype of the variable to be printed is
an integer. The number is wri en right-jus fied in the given field width. Leading blank space will appear
as necessary. The following examples illustrate the output of the number 1256 under different formats.
Format Output
Prin (“%d”, 1256) 1 2 5 6
Prin (“%6d”, 1256) 1 2 5 6
Prin (“%2d”, 1256) 1 2 5 6
Prin (“%-6d”, 1256) 1 2 5 6
Prin (“%06d”, 1256) 0 0 1 2 5 6
The minus sign in the control string “%-6d” prints the number le -jus fied. The control string “%06d”
prints zero before the number (if the number of digits is less than the specified field width). The minus
(-) and zero (0) are known as flags.
Long integers may be printed by specifying ld in the place of d in the format specifica on. Short integers
may be printed by specifying hd in the place of d in the format specifica on.
main()
{
int m = 12345;
long n = 987654;
prin (“%d\n”,m);
prin (%10d\n”,m);
prin (“%010d\n”,m);
prin (“%-10d\n”, m);
prin (“%10ld\n”, n);
prin (“%10ld\n”, n);
}
output
12345
12345
0000012345
12345
987654
-987654
The output of a real number may be displayed in decimal nota on using the following specifica on:
%w.pf
The integer w indicates the minimum number of posi ons that are to be used for the display the value
and the integer p indicates the number of digits to be displayed a er the decimal point (precision). The
value when displayed is rounded to p decimal places and printed right-jus fied in the field of w columns.
Leading blank spaces and zeros will appear as necessary. The default precision is 6 decimal places. The
nega ve numbers will be printed with the minus sign. The number will be displayed in the form -98.456
We can also display a real number in exponen al nota on by the specifica on: %w.pe
The field width w should sa sfy the condi on w ≥ p+7.
The value will be rounded off and printed right-jus fied in the field if w columns. Using flag 0 before the
field width specifier w we have zeros before digits and by using the flag – we have the numbers
le -jus fied. The following table gives output for different format strings if variable y = 98.7654
Format Output
prin (“%7.4f”,y); 9 8 . 7 6 5 4
prin (“%7.2f”,y); 9 8 . 7 7
prin (“%-7.2f”,y); 9 8 . 7 7
prin (“%f”,y); 9 8 . 7 6 5 4
prin (“%10.2e”,y); 9 . 8 8 e + 0 1
prin (“%11.4e”,-y); - 9 . 8 7 6 5 e + 0 1
prin (“%-10.2e”,y); 9 . 8 8 e + 0 1
prin (“%e”,y); 9 . 8 7 6 5 4 0 e + 0 1
Some systems also support a special field specifica on character that lets the user define the field size at
run me. This takes the following form: prin (“%*.*f”, width, precision, number);
SPECIFICATION OUTPUT
“%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
“%.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
The if statement is a powerful decision-making statement and is used to control the flow of execu on of
statements. It is basically a two-way decision statement and is used in conjunc on with an expression.
The general form is if (test expression)
The test expression is either rela onal expression or condi onal expression whose value is one (true) or
zero (false). IF statement is a two way branching like this figure.
The statement-block may be a single statement or a group of statements. If the test expression is true,
the statement-block will be executed and a er that control transferred to statement-x; if the test
expression is false the statement-block will be skipped and the execu on will jump to the statement-x. In
both the cases statement-x will be executed in sequence.
The flow chart for simple if statement:
………
……..
If (category == sports)
{
Marks = marks + bonus_marks;
}
Prin (“%f”, marks);
…….
…….
The program tests the type of category of the student. If the student belongs to sports category, then he
gets a addi onal bonus_marks to his marks before they are printed. For others bonus_marks are not
added.
Another example for simple if statement
Program
main()
{
int a, b, c, d;
float ra o;
prin (“enter four integer values\n”);
scanf(“%d %d %d %d”, &a, &b, &c, &d);
if (c – d != 0)
{
ra o = (float) (a+b) / (float) (c-d);
prin (“ra o = %f\n”, ra o);
}
}
output
1st run
2nd run
Enter four integer values
12 23 34 34
In first run of the above program c-d is not equal to zero therefore it gives the result ra o. But during the
second run of the program c-d is equal to zero therefore the statement bock of if statement is skipped
and the program stops without producing any output.
Note that here we used float conversion to evaluate ra o. This is necessary to avoid trunca on due to
integer division.
IF … ELSE STATEMENT:
The if … else statement is an extension of the simple if statement. The general form is
if (test expression)
{
true-block statements
}
else
{
false-block statements
}
statement-x;
If the test expression is true then the true-block statements are executed otherwise the false-block
statements are executed. In either case either true-block or false-block will be executed not both. Then
the control is transferred subsequently to the statement-x. The flow-chart is given below
Consider the example of coun ng the number of boys and girls in a class. We use code 1 for boy and
code 2 for girl. The program to count number of boys and girls using if… else statement is given below.
……..
……..
if (code == 1)
boy = boy + 1;
else
girl = girl + 1;
statement-x;
…..
…..
Here if the code is equal to 1, the statement boy = boy + 1; is executed and the control is transferred to
the statement-x, a er skipping else part. If the code is not equal to 1 the statement girl = girl + 1 is
executed and control reaches the statement-x.
Another program to find the ra o between (a+b) and (c – d) where a, b, c, d are integers. The ra o is
calculated only if (c – d) is not equal to zero.
……..
……..
if (c – d != 0)
{
ra o = (float) (a+b) / (float) (c – d);
prin (“ra o = %f\n”, ra o);
}
else
prin (“c – d is zero\n”);
statement-x;
…..
…..
When a series of decisions are involved, we may have to use more than one if … else statement in nested
form and its general format is
If (test condi on – 1)
{
If (test condi on – 2)
{
Statement block – 1;
}
else
{
Statement block – 2;
}
}
Else
{
Statement block – 3;
}
Statement x;
First test condi on – 1 is evaluated, if it is true test condi on – 2 is evaluated and if it is also true then
statement block – 1 is evaluated. If test condi on – 1 is true but test condi on – 2 is false then statement
block – 2 is evaluated. If test condi on – 1 is false statement block – 3 is evaluated. In either case the
control is transferred to the statement-x. The flow chart is given below
In a commercial bank, an incen ve policy of giving bonus to all its deposit holders. For female deposit
holders with balance greater than 5000, 5% of balance is added to the original balance as bonus a nd
other deposit holders will get 2% of balance is added to the original balance as bonus.
……..
……..
if (gender is female)
{
if (balance > 5000)
bonus = 0.05 * balance;
else
bonus = 0.02 * balance;
}
else
{
bonus = 0.02 * balance;
}
balance = balance + bonus;
…….
…….
If (condi on 1)
Statement – 1;
Else if (condi on 2)
Statement-2;
Else if (condi on 3)
Statement-3;
Else if (condi on n)
Statement-n;
Else
Default-statement;
Statement-x;
This construct is known as the else if ladder. The condi ons are evaluated from the first if of the ladder,
downwards. As soon as true condi on is found the statement associated with it is executed and the
control is transferred to statement-x (skipping the rest of the ladder). When all the n condi ons become
false then the final else containing the default-statement will be executed.
Consider the example of grading the students in an academic institution. The grading is done
according to the range of marks.
Average Grade
marks
80 to 100 Distinction
60 to 79 First class
50 to 59 Second
Less than 49 class
Third class
……
……
if (marks > 79)
grade = “distinction”;
else if (marks > 59)
grade = “first class”;
else if (marks > 49)
grade = “second
class”;
else
grade = “third class”;
printf(“%s\n”, grade);
……
…..
When using control structures, a statement often controls many other statements that follow it.
In such situations it is good practice to use proper indentation (alignment) to understand the
program clearly.
1. Indent statements that are dependent on the previous statements; provide at least three
spaces of indentation.
2. Align vertically else clause with their matching if clause.
3. Use braces on separate lines to identify a block of statements.
4. Indent the statements in the block by at least three spaces to the right of the braces.
5. Align the opening and closing braces.
6. Use appropriate comments to signify the beginning and end of blocks.
7. Indent the nested statements as per the above rules.
8. Code only one clause or statement on each time.
When one of many alterna ves is to be selected, we can use an if statement to control the selec on.
However the complexity of such a program increases drama cally when the number of alterna ves
increases. The program becomes difficult to read and follow. Some mes it may confuse the person who
designed it. Fortunately C has a built-in mul way decision statement known as a switch. The switch
statement tests the value of the expression or variable, when match is found a block of statements
associated with that case is executed. The general format is
switch (expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
case value-3:
block-3
break;
…….
…….
default:
default-block
break;
}
statement-x;
The expression is an integer expression or characters. Value-1, value-2, … are constant expressions or
constants (integral constant) and are known as case labels. Each of these values should be unique within
a switch statement. Block-1, block-2, … are statement lists and may contain zero or more statements.
There is no need to put braces around these blocks. The case labels must end with a colon (:).
When switch statement is executed, the value of the expression is successfully compared against the
values value-1, value-2, … if a match is found then the block of statements that follows the case are
executed. The break statement at the end of each block signals the end of a par cular case and causes
an exit from the switch statement and transfers the control to the statement-x following the switch.
The default is an op onal case, when present it will be executed if the value of the expression does not
match with any of the case values. If not present, no ac on takes place when no match found between
expression and case values. And the control goes to the statement-x. ANSI C permits the use of as many
as 257 case labels. The flow chart of switch statement is as follows:
The switch statement can be used to grade the students as given below
80 to 100 Distinction
60 to 79 First class
50 to 59 Second class
Less than 49 Third class
…….
…….
avg = marks / 10;
switch (avg)
{
case 10:
case 9:
case 8:
grade = “ dis nc on”;
break;
case 7:
case 6:
grade = “ first class”;
break;
case 5:
grade = “second class”;
break;
case 4:
case 3:
case 2:
case 1:
case 0:
grade = “third class”;
break;
}
prin (“grade = %s\n”, grade);
…..
…...
Note that we have used conversion statement avg = marks / 10; where avg is defined as an integer. The
variable avg takes the following integer values 1,2, … 10. Here the first two cases uses empty block which
means it will execute the statement grade = “ dis nc on”; which is corresponding to case 8. Same way
cases 6 and 7. Also cases 0,1,2,3,4 executes the statement grade = “third class”;
The C language has an usual operator useful for making two-way decisions. This operator is a
combina on of ? and : and takes three operands. This operator is popularly known as the condi onal
operator. The general form of condi onal operator is as follows:
The condi onal expression is evaluated first. If the result is nonzero (true), expression1 is evaluated
and this value is the value of the condi onal expression. Otherwise expression2 is evaluated and its
value is the value of the condi onal expression.
Another example of condi onal operator for the equa on y = [1.5x + 3 f or x≤2 2x + 5 f or x > 2 ]
Another example is to calculate the weekly salary of the employee by the formula
salary = {4x + 100 f or x < 40 300 f or x = 40 4.5x + 150 f or x > 40 } where x is
the number of products sold by the employee.
Like many other languages C supports the goto statement to branch uncondi onally from one point
to another in the program. The goto requires a label in order to iden fy 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 format of goto
and label statements are as given below.
…….. label:
goto label; statement-x;
……… ………
……… ………
……… ………
label: goto label;
statement-x;
The label can be anywhere in the program either before or a er the goto label; statement. During
the execu on of the program when a statement like goto begin; is met the flow of control will jump
to the statement immediately following the label begin: . This happens uncondi onally. The goto
statement breaks the normal sequen al execu on of the program. 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. If the label: is placed a er the goto label; it skips some of the
statements and jumps to the statement next to label: This jump is known as forward jump. Goto is
o en used at the end of the program to direct the control to the input statement to read further
data.
This program evaluates the square root of a series of numbers read from the terminal. The program
uses goto statement a er prin ng the square root and the control again goes to read label and gets
a new number using scanf statement. If the number given is less than zero it prints “ The squareroot
of this number is imaginery”. Thus goto statement transfers control to any part of the program.
-------------------------------------------------UNIT II OVER-----------------------------------------------------