0% found this document useful (0 votes)
12 views23 pages

18bma55s U2

This document covers managing input and output operations in C programming, detailing how to read, process, and write data using standard I/O functions like scanf and printf. It explains character input/output, formatted input/output, and the use of format specifiers for various data types, along with error detection in input. Additionally, it provides examples and guidelines for using these functions effectively in C programs.

Uploaded by

roynancy2k6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views23 pages

18bma55s U2

This document covers managing input and output operations in C programming, detailing how to read, process, and write data using standard I/O functions like scanf and printf. It explains character input/output, formatted input/output, and the use of format specifiers for various data types, along with error detection in input. Additionally, it provides examples and guidelines for using these functions effectively in C programs.

Uploaded by

roynancy2k6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT II

MANAGING INPUT AND OUTPUT OPERATIONS

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

a (input) Q (input) h (input)


A (output) q (output) H (output)

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.

INPUTTING INTEGER NUMBERS:

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.

INPUTTING REAL NUMBERS

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.

INPUTTING CHARACTER STRINGS

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.

READING MIXED DATA TYPES

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.

DETECTION OF ERRORS IN INPUT

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.

Commonly used scanf format codes


Code Meaning
%c Read a single character
%d Read a decimal integer
%e Read a floa ng point value
%f Read a floa ng point value
%g Read a floa ng point value
%h Read a short integer
%i Read a decimal, hexadecimal or octal integer
%o Read an octal integer
%s Read a string
%u Read an unsigned decimal integer
%x Read a hexadecimal integer
%[..] Read a string of words.
%hd Read a short integer
%ld Read a long integer
%lf Read a long double

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.

RULES FOR SCANF


● Each variable to be read must have a field specifica on.
● For each field specifica on, there must be a variable address of proper type.
● Any non-whitespace character used in the format string must have a matching character in the
user input.
● Never end the format string with whitespace. It is a error.
● The scanf reads un l:
1. A white space character is found in a numeric specifica on, or
2. The maximum number of characters have been read or
3. An error is detected or
4. The end of file is reached.

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.

A simple format specifica on has the following form: %w.p type-specifier


Where w is an integer number that specifies the total number of columns 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 characters to be printed from a string. Both w and p are op onal. Some
examples of prin statements are
prin (“programming in c”);
prin (“ “);
prin (”\n”);
prin (“%d”, x);
prin (“a = %f\n b = %f”, a b);
prin (“sum = %d”, 1234);
prin (“\n\n”);
prin never supplies a newline automa cally and therefore mul ple prin statements may be used to
build one line of output. A newline can be introduced by the help of a newline character ‘\n’ .

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.

Program to illustrate the output of integer numbers under various formats.


PROGRAM

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

OUTPUT OF REAL NUMBERS:

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);

For example prin (“%*.*f”, 7, 2, number); is equivalent to prin (“%7.2f”, number);


The advantage of this format is that the values for width and precision may be given during running the
program, thus making the format a dynamic one.

PRINTING A SINGLE CHARACTER


A single character can be displayed in a desired posi on using the format: %wc
The character will be displayed right-jus fied in the field of w columns. We can make the display
le -jus fied by placing a minus sign before the integer w. The default value for w is 1.
PRINTING OF STRINGS
The format specifica on for outpu ng strings is similar to that of real numbers. It is of 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-jus fied.
The following table gives the variety of specifica ons in prin ng a string ‘NEW DELHI 110001’ containing
16 characters (including blanks).

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

MIXED DATA OUTPUT


It is permi ed to mix data types in one prin statement. For example, the statement of the type
prin (“%d %f %s %c”, a, b, c, d); is valid. Prin uses its control string to decide how many variables to
be printed and what their data types are. The format specifica ons should match the variables in
number, order and type. If there are not enough variables or if they are of the wrong type, the output
results will be incorrect.

Commonly used prin format codes


Code Meaning
%c Print a single character
%d Print a decimal integer
%e Print a floa ng point value in exponen al form
%f Print a floa ng point value without exponent
%g Print a floa ng point value either e-type or f-type
%i Print a signed decimal integer
%o Print an octal integer without leading zero
%s Print a string
%u Print an unsigned decimal number
%x Print a hexadecimal integer, without leading Ox
%hd Print a short integer
%ld Print a long integer
%lf Print a double float
%Lf Print a long double

Commonly used output format flags


Flag Meaning
- Output is le -jus fied within the field. Remaining field will be blank
+ + or – will precede the signed numeric item
0 Causes leading zeros to appear
# (with o or x) Causes octal and hex items to be preceded by O and Ox, respec vely
# (with e, f or g) Causes a decimal point to be present in all floa ng point numbers, even if
it is whole number. Also prevents the trunca on of trailing zeros in g-type
conversion.

ENHANCING THE READABILITY OF OUTPUT


Computer outputs are useful for various calcula ons and for making decisions. Therefore clarity of
outputs are of utmost importance, to improve the clarity, readability and understandability of outputs
we can write the prin statements in following form.
1. Provide enough blank space between two numbers.
2. Introduce appropriate headings and variable names in the output.
3. Print special messages whenever a peculiar condi on occurs in the output.
4. Introduce blank lines between the important sec ons of the output.
The system usually provides two blank spaces between the numbers. But if we use ‘\t’ tab character we
get 4 blank space between two numbers and if we use ‘\n’ next line character we get the second number
in next line.
For example: prin (“a = %d\t b = %d”, a, b);
prin (“a = %d\n b = %d”, a, b);
DECISION MAKING AND BRANCHING
In C program the set of statements will be executed from first to last line in order which they appear. In
some situa ons we need to change the order by checking certain condi ons or in some cases we need
to repeat the group of statements un l certain condi ons are met. This involves a kind of decision
making to see whether a par cular condi on has occurred or not and then direct the computer to
execute certain statements accordingly.
C language supports following statements:
1. if statement
2. switch statement
3. condi onal operator statement
4. goto statement
These statements are popularly known as decision making statements. Since the statements controls
the flow of execu on, they are also known as control statements.

DECISION MAKING WITH IF STATEMENT:

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.

Some examples are if (code==1)


Person = male

If (age > 55)


Person = re red

The if statements may be implemented in different forms such as:


1. simple if statement
2. if … else statement
3. Nested if … else statement
4. Else if ladder
SIMPLE IF STATEMENT:
The general form of a simple if statement is
if (test expression)
{
Statement-block;
}
Statement-x;

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:

Example program 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

enter four integer values


12 23 34 45
ra o = -3.181818

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;
…..
…..

NESTING OF IF … ELSE STATEMENTS

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;
…….
…….

THE ELSE IF LADDER


There is another way of pu ng if together when mul path decisions are involved. The else if ladder
consists of a chain of ifs in which the statement associated with each else is an if. Its general form is

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

Program to grade the students using else if ladder is given below

……
……
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);
……
…..

The flow chart for else if ladder is given below


RULES FOR INDENTATION

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.

THE SWITCH STATEMENT

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

Average marks Grade

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”;

RULES FOR SWITCH STATEMENT


● THE SWITCH expression must be an integral type.
● Case labels must be constants or constant expressions.
● Case labels must be unique. No two labels can have the same value.
● Case labels must end with semicolon.
● The break statement transfers the control out of the switch statement.
● The break statement is op onal. That is two or more case labels may belong to the same
statements.
● The default label is op onal. If present it will be executed when the expression does not find a
matching case label.
● There can be at most one default label. The default may be placed anywhere but usually placed
at the end.
● It is permi ed to nest switch statements.

THE CONDITIONAL OPERATOR ( ? : )

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:

Condi onal expression ? expression1 : expression2;

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.

For example flag = (x < 0) ? 0 : 1;

In this example if x = 5 then flag = 1


If x = -8 then flag = 0.

Another example of condi onal operator for the equa on y = [1.5x + 3 f or x≤2 2x + 5 f or x > 2 ]

y = ( x > 2 ) ? ( 2 * x + 5) : ( 1.5 * x + 3);

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.

Salary = (x != 40) ? ((x < 40) ? (4 * x + 100) : (4.5 * x + 150)) : 300;

THE GOTO STATEMENT

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.

Consider the example


main()
{
double x,y;
read:
scanf(“%f”, &x);
if (x >0)
y = sqrt(x);
prin (“number = %f its squareroot is %f\n”, &x,&y);
goto read;
else
prin (“The squareroot of this number is imaginery”);
}

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-----------------------------------------------------

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy