Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

ProblemSolvingThroughCProgramming-Chapter3

Chapter 3 of 'Problem Solving Through C Programming' focuses on managing input and output operations in C, detailing the use of standard library functions like printf() and scanf() for data handling. It categorizes input/output functions into unformatted and formatted types, explaining their usage with examples. The chapter also introduces character functions from ctype.h and highlights the limitations of certain functions, such as scanf() not handling strings with spaces.

Uploaded by

Roopa Sk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

ProblemSolvingThroughCProgramming-Chapter3

Chapter 3 of 'Problem Solving Through C Programming' focuses on managing input and output operations in C, detailing the use of standard library functions like printf() and scanf() for data handling. It categorizes input/output functions into unformatted and formatted types, explaining their usage with examples. The chapter also introduces character functions from ctype.h and highlights the limitations of certain functions, such as scanf() not handling strings with spaces.

Uploaded by

Roopa Sk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/277143759

Problem Solving Through C Programming - Chapter 3

Book · January 2013

CITATIONS READS
0 37,809

1 author:

Rama M A
Maharani Lakshmi Ammanni College for Women
18 PUBLICATIONS 152 CITATIONS

SEE PROFILE

All content following this page was uploaded by Rama M A on 26 May 2015.

The user has requested enhancement of the downloaded file.


Managing Input & Output
Operations 3
3.1 INTRODUCTION
To solve a problem using a computer program, the three most important functions
required are input, output and processing of data. However, C does not contain any built-
in input or output statements. Further C carries out all its input and output operations
through library functions like printf() and scanf(). Thus the standard input/output library
functions are included in the header file called stdio.h. Therefore every C program using
input/output functions must begin with the statement.

#include<stdio.h>

stdio means standard input-output.


#include <stdio.h> is a command to search and include the contents of the header
file stdio.h in the program.
Basically there are 6 functions for input/output of data. They are :
1. scanf()
2. printf()
3. getchar()
4. putchar()
5. gets()
6. puts()
The above functions permit transfer of data between the computer and the standard
input/output devices like keyboard and monitor.
 getchar() and putchar() functions allow single character to be transferred into
and from the computers.
 scanf() and printf() allow transfer of single characters, numerical values and
strings.
 gets() and puts() facilitate the input and output of a string.
The input/output functions can be broadly divided into two categories :
 unformatted I/O functions
 Formatted I/O functions
The unformatted I/O functions do not allow the user to format her input data or
output data. However the formatted I/O functions allow the user to specify the type and
format of the input as well as output.
98 PROBLEM SOLVING TECHNIQUES USING C

3.2 UNFORMATTED I/O FUNCTIONS


The unformatted I/O functions available in C are :
(i) getchar( )
(ii) putchar( )
(iii) gets( )
(iv) puts( )
3.2.1 Reading a Character (getchar())
One of the ways of reading a single character into the computer is by using the
library function getchar( ). The syntax is
variable_name=getchar( );

where the variable_name can be of char type or integer type. For example,
char ch;
ch=getchar( );
In the above statement, the execution of the program is halted until a key is pressed.
This key is stored in ch. The key pressed could be anything including return and tab
keys.
Sometimes, when the user requires to store the ASCII code of the key pressed, the
variable can be declared as int type.

Example 3.1
/* Program to show usage of getchar() */
#include <stdio.h>
void main()
{
char ch;
/* to clear the screen */
clrscr();
printf("\n\n Enter a Single character Please : ");
ch = getchar();
printf("\n You pressed %c ",ch);
printf("\n and its ASCII code is %d ",ch);
}

Output
Enter a Single character Please : b
You pressed b
and its ASCII code is 98

The getchar( ) function can also be used to read strings containing more than one
character, by reading one character at a time within a loop. getch( ) is similar to
getchar( ). However it does not wait for the user to press the enter key. It is unbuffered
version of getchar( ).
MANAGING INPUT AND OUTPUT OPERATIONS 99

3.2.2 Writing a Character (putchar())


Single characters can be displayed using the library function putchar( ). Its general
form is :

putchar (variable_name) ;

Where the variable_name must be a character variable or a character constant.

Example 3.2
/* Program to show usage of putchar() */
#include <stdio.h>
void main()
{
char key;
/* to clear the screen */
clrscr();
printf("\n\n Type a Single character Please : ");
key = getchar();
printf("\n You pressed : ");
putchar(key);
putchar('\n');
}
Output
Type a Single character Please : M
You pressed : M

 Note that even though \n contains 2 characters, it is considered a character


constant. All escape sequences are character constants.
 The character constant for example 'A' and the single-character string constant
"A" are not the same. The character constant has an equivalent integer value (65
in this case), whereas the string constant consists of 2 characters the specified
character followed by a null character (\0). Further it does not have an
equivalent integer value.

Character Functions (ctype.h)


The C library supports character functions which are of boolean type and determine
the type of character of the argument (say ch). These functions are included in the header
file ctype.h. Each of the functions, except toascii( ), tolower( ) and toupper( ) return a
non-zero value if true and zero otherwise. Fig. 3.1 lists the most often used character
functions.
100 PROBLEM SOLVING TECHNIQUES USING C

Functions Purpose

isalnum (ch) ch is an alphabetic or numeric character


isalpha (ch) ch is an alphabetic character
isctrl (ch) ch is a control character
isdigit (ch) ch is a digit
isgraph(ch) ch is a graphics character
islower (ch) ch is a lowercase character
isprint (ch) ch is a printable character
ispunct (ch) ch is a punctuation character
isspace (ch) ch is a space, horizontal or vertical tab
isupper (ch) ch is an uppercase character
isxdigit (ch) ch is a hexadecimal digit
toascii (ch) converts value of argument to ASCII
tolower (ch) converts a letter to lowercase
toupper (ch) converts a letter to uppercase

Fig. 3.1 : Character functions

Any program which uses any one of the above functions must include the statement.
# include<ctype.h> in the program

Example 3.3
/* Program to convert upper case to lower case letters */
#include <stdio.h>
#include <ctype.h>
void main()
{
char ch;
/* Clears the screen*/
clrscr();
printf("\n Type an alphabet in upper case : ");
ch = getchar();
(isalpha(ch)>0) ? putchar(tolower(ch)):
printf("\n You did not type an alphabet");
/* Waits for a key press- used to see the output*/
getch();
}
MANAGING INPUT AND OUTPUT OPERATIONS 101

Output
Type an alphabet in upper case : S
s
Type an alphabet in upper case : u
u
Type an alphabet in upper case : 5
You did not type an alphabet

3.2.3 Reading a line of text (gets())


gets() is a function to read the input data which is of string type. It gets the
characters typed at the keyboard until the 'return' key is pressed. This set of characters is
stored as a string array. It's general form is :

gets (string);

where string is a string variable name.

Example 3.4

/* Program to show usage of gets() function */


#include <stdio.h>
void main( )
{
char addr[30];
clrscr(); // clears the screen
printf("\n Enter your Address :");
gets(addr);
printf("\n Your Address is : %s ! Right ",addr);
getch();
}

Output
Enter your Address :18TH CROSS, MALLESWARAM
Your Address is : 18TH CROSS, MALLESWARAM ! Right

3.2.4 Printing a String (puts())


puts() function is used to print string type of data. It takes single arguments. It's
general form is :

puts(expression);

where expression can be a string constant or a string variable. The string may
include blank space characters.
102 PROBLEM SOLVING TECHNIQUES USING C

Example 3.5
/* Program to show usage of puts() function */
#include <stdio.h>
void main()
{
char text[40];
clrscr(); // clears the screen
printf("\n Enter a line of text :");
gets(text);
puts("\n You typed the text :");
puts(text);
getch();
}

Output
Enter a line of text : MAHARANI LAKSHMI AMMANNI COLLEGE
You typed the text :
MAHARANI LAKSHMI AMMANNI COLLEGE

Every call to puts ( ) function is executed on a new line i.e., puts( ) function
automatically executes a line feed before printing the string.

3.3 FORMATTED INPUT (scanf( ))


Data can be input to the computer from a standard input device by using the library
function scanf( ). Any type of data like numerical values, character values, string values or
their combination can be input through scanf( ). Its general form is :

scanf("control string", list of address of variables);

where the control string specifies the format of the variables.


 The list of variables are separeated by commas.
 The format or conversion specifiers begin with a % sign followed by a character,
which indicates the type of data of the corresponding variables.
 The general format of format specifier is

%wd

where w is the field width and d is the data specifier. For example,

scanf("%3d",&a);

informs the compiler that the input would be an integer value which is a 3 digit number.
MANAGING INPUT AND OUTPUT OPERATIONS 103

The field width is optional. Further d is the format character for an integer. Fig. 3.2 lists
the data types and their corresponding format specifiers.

Data Type Format


Integer Integer %d
Short %d
Short unsigned %u
Long %ld
Long assigned %lu
Hexadecimal %x
Long hexadecimal %lx
Octal %O (letter 0)
long octal %lo
Real float,double %f, %lf, %g
Character %c
String %s

Fig. 3.2 : Format Specifiers for scanf( )

 Every variable in the variable list must match the format specifiers in the
control string.
 Every variable must be preceded by an ampersand symbol (&).
 scanf( ) ignores all leading spaces, blanks, tabs, newlines or form feed characters
in input.
 Comma, space or colon can be used as delimiters in the input stream. For
example, using the statement :

scanf("%d,%d,%f",&a,&b,&x);

the data 100, 200, 250.48 can be read into a, b and x respectively. In this case comma is
used as delimiter. Similarly, using the statement :
scanf("%d,%d",&x,&y);

the data 50 100 can be read into x and y using space as delimiter.
 Reading of data input is terminated when the specifier and the data mismatch.
 Unread data in an input stream is taken to be part of next scanf( ) statement.
This leads to errors.
 The field width of real numbers is generally not specified in the scanf()
statement.
 However the field width can be specified for integers. Care must be taken to see
that the field width can store the input data.
104 PROBLEM SOLVING TECHNIQUES USING C

Example 3.6
/* Program to show formatted input using scanf() function */
#include <stdio.h>
void main()
{
int a,b,c;
float x,y;
double p,q;
clrscr();
/* Conversion Specifiers for Integers */
printf("\n Enter 2 numbers :");
scanf("%d %d",&a,&b);
printf("\n a = %d b = %d\n",a,b);
printf("\n Enter a 9 digit number :");
scanf("%3d %3d %3d",&a,&b,&c);
printf("\n After splitting a 9 digit number: a = %d b= %d c = %d\n",a,b,c);
printf("\n Enter 3 integer numbers :");
scanf("%d %*d %d",&a,&b,&c);
printf("\n Skipping the 2nd number : a = %d b = %d c = %d\n",a,b,c);
/* Conversion Specifiers for Real numbers */
printf("\n\n Enter 2 real numbers x and y:");
scanf("%f %f",&x,&y);
printf("\n x = %f y= %f\n",x,y);
/* Conversion Specifiers for Double Precision numbers */
printf("\n\n Enter 2 double precision numbers p and q:");
scanf("%lf %lf",&p,&q);
printf("\n p = %lf q= %e\n",p,q);
}

Output
Enter 2 numbers :15 558
a = 15 b = 558
Enter a 9 digit number :123456789
After splitting a 9 digit number: a = 123 b= 456 c = 789
Enter 3 integer numbers :33 44 55
Skipping the 2nd number : a = 33 b = 55 c = 789
Enter 2 real numbers x and y:1234.555 8970.12345
x = 1234.555054 y= 8970.123047
Enter 2 double precision numbers p and q:1111122222.444 6666.8888888889
p = 1111122222.444000 q= 6.666889e+03
MANAGING INPUT AND OUTPUT OPERATIONS 105

3.3.1 Reading Strings


scanf( ) can also be used to read a string of characters. The format specifier for a
string data is given by :

%ws

where w is the width of the string. For example


char addr[25];
scanf("%s",addr);

is used to read the input data into the string variable addr. In this example, address
operator & is not attached to the variable addr since strings are directly accessed through
pointers (to be discussed in the chapter 8)

Example 3.7
/* Program to Input and Output a string*/
#include <stdio.h>
void main()
{
char name[20];
clrscr(); // Clears the screen
printf("\n Enter your name :");
scanf("%s",name);
printf("\n Your name is %s ! Right ",name);
getch();
}
Output
Enter your name : Rama
Your name is Rama ! Right

One main drawback of scanf( ) statement is that it cannot be used to read a line of
text containing blank spaces. In the example 3.7 suppose the input data is:
Arun Narayan
then the output would be
Arun
since blank spaces (also known as white space characters) are considered as
delimeters.

3.4 FORMATTED OUTPUT (printf())


Output data can be written from the computer on the screen using the library
function printf( ). This function is used to output any combination of numerical values,
106 PROBLEM SOLVING TECHNIQUES USING C

single characters and strings. The printf( ) function moves data from the computer's
memory to the standard output device.
When printf( ) is used to output values of variables or expressions, the formats are
supplied in its first argument called the control string. The variables to be printed are
listed after the control string. Commas are required to separate the control string and the
list of variables. The format is :

printf("control string", var1,var2,.......,var n);

 Format specification is provided in the control string.


 var1, var2, ........ are variables or expressions.
 If there are no variables then the control string must not contain any format
specifier. For example,
printft("The string does not refer to a variable");
The control string includes :
 Text messages
 Format specification defining the output format of each variable.
 Escape sequence characters like \n, \t etc.
The variables must match in number order and type with the format specifiers.
The most commonly used format characters for data output are as shown in
Figure 3.3.

Data type Format

Integer Integer %d
Short %d
Short unsigned %u
Long %ld
Long assigned %lu
Hexadecimal %x
Long hexadecimal %lx
Octal %O (letter 0)
long octal %lo
Real float %f,%g
Double(with exponent) %If, %e, %E
Character %c
String %s

Fig. 3.3 : Format Specifiers for printf()


MANAGING INPUT AND OUTPUT OPERATIONS 107

Example 3.8
/*Program to print floating-point output in 2 ways*/
void main( )
{
double x = 5000.0,y=0.0025;
printf("\n %f %f %f %f \n\n",x,y,x*y,x/y);
printf("\n %e %e %E %E",x,y,x*y,x/y);
}

Output
5000.000000 0.002500 12.50000 2000000.000000
5.000000e + 3 2.500000e - 03 1.250000E + 01 2.000000 E + 06

In example 3.8, the first line of output shows the values in standard floating point
format, without exponents. The second line shows the values in scientific notation, with
exponents. Notice that 6 decimal places are shown for each value. This can be altered by
specifying the field width, which is of the form

% - w.d type-specifier

where
 (minus sign) is for left justification
w field width
d specifies the number of digits to the right of the decimal point.
. dot denotes the decimal point for real numbers
printf( ) function never starts automatically in a new line. Thus printf( ) requires a new
line character i.e., \n as part of the control string to start printing in a new line.

3.4.1 Printing Integers


(i) Printing of numbers is by default, right justified i.e., when the field width specified
is greater than the number, leading blanks are included.
(ii) When the field width is not specified or when the width is less than the number to
be printed, the printf( ) function will override the specified width and print the full
number. Figure 3.4 illustrates some formats of printing integer values.
(iii) %wd right justifies the output and
%-wd left justifies the output
%owd fills leading blanks with zeros.
108 PROBLEM SOLVING TECHNIQUES USING C

Format Output

1 2 3 4
printf("%d",x); 2 5 4 5

1 2 3 4 5 6 7
printf("%07d:",x); 0 0 0 2 5 4 5

1 2 3 4
printf("%3d",x); 2 5 4 5

1 2 3 4 5
printf("%-5d",x); 2 5 4 5

1 2 3 4 5 6
printf("%06d",-x);  0 2 5 4 5

Fig. 3.4 : Formatted printing of integers (x = 2545)

3.4.2 Printing Real Numbers


(i) The field width in this case is specified by the format w.d where w specifies the
entire width of the real number and d indicates the number of decimal places after
the decimal point.
(ii) %w.df right justifies the output and
%-w.df left justifies the output.
%0w.df replaces leading blanks with zeros.
(iii) Real numbers can be printed in exponential format using the form
%w.de
(iv) When the field width is not specified, 6 decimal places are printed by default.
(v) When d is less than the number of decimal places in the real number, the value is
rounded off to 'd' number of places. Fig. 3.5 illustrates some formats of printing real
numbers.
(vi) In the format %w.d e,
w>=d+7

where 1 column is for the + or –sign


MANAGING INPUT AND OUTPUT OPERATIONS 109

1 column is for the most significant digit


1 column is for the decimal point
1 column is for the symbol e
1 column is for the + or –sign after e
2 columns are for the power
(vii) %g is used to print a real number either using e-type specifier or f-type specifier
depending on the value.

Format Output

printf("%f",y); 2 5 . 4 5 4 5 0 0

printf ("%7.4f",y); 2 5 . 4 5 4 5

printf("%7.3f",y); 2 5 . 4 5 5

printf("%-7.3f",y); 2 5 . 4 5 5

printf("%10.3e",y); 2 . 5 4 5 e  0 1

printf("%10.3e",-y);  2 . 5 4 5 e  0 1

printf("%e",y); 2 . 5 4 5 4 5 0 e  0 1

Fig. 3.5 : Formatted output of real number assume y = 25.4545)

3.4.3 Printing a Single Character


(i) Single characters can be printed in the required position by using the format

%c or %wc

where w gives the width of the field.


(ii) %wc gives right justified output and
%-wc gives left justified output
For example,
char ch = 'A'
printf("%5c%c",ch,ch);
gives the output
A A
110 PROBLEM SOLVING TECHNIQUES USING C

similarly
printf("% - 5c",ch);
gives the output
A

3.4.4 Printing String


(i) Strings are generally printed using the format

%s or %ws

where w is the width of the string.


(ii) %ws leads to left justified output and
%-ws leads to right justified output
Some examples are as shown in table 6.6 with name [20] = 'MAHARANI
LAKSHMI"

Format Output

printf("%s",name); M A H A R A N I L A K S H M I

printf("%10s",name); M A H A R A N I L A K S H M I

printf("%20s",name); M A H A R A N I L A K S H M I

printf("%-20s",name); M A H A R A N I L A K S H M I

Fig. 3.6 : Formatted output of strings

(iii) Readability of the output can be enhanced by printing appropriate headings and
messages.
(iv) Escape sequence \t (tab space) can be used to insert space between outputs.
The following example shows the formatted output of string.

Example 3.9
/* Program to show formatted printing of characters and strings */
#include <stdio.h>
void main()
{
char ch = 'a';
static char name[20] = "Maharani Lakshmi";
clrscr(); //clears the screen
/* Single character outputs */
MANAGING INPUT AND OUTPUT OPERATIONS 111

printf("\n Single Character Output \n");


printf("\n 12345678901234567890 <- Column Numbers");
printf("\n %5c %c", ch , ch);
printf("\n %-5c", ch);

/* String Output */
printf("\n String Outputs \n");
printf("\n 12345678901234567890 <- Column Numbers");
printf("\n %s ",name); //Requires 16 columns
printf("\n %20s ",name); //Adds 4 leading spaces (16+4)
printf("\n %8.4s ",name); //prints 4 characters & adds 4 leading spaces
printf("\n %-8.4s ",name); //Right-justified & prints 4 characters

printf("\n\n Name: %s \n Class: %s \n Marks: %d ","Suhasini","MCA",98);

getch();
}

Output
Single Character Output
12345678901234567890 <- Column Numbers
a a
a
String Outputs
12345678901234567890 <- Column Numbers
Maharani Lakshmi
Maharani Lakshmi
Maha
Maha

Name: Suhasini
Class: MCA
Marks: 98

Consider the following statements :


static char line[12] = “lower-case".
printf("\n %15s %15.5s %0.5s\n", line, line, line);
The output generated is :
lower-case lower lower
Here %15s overrides the minimum field width specification and the string is padded
with 5 leading blanks. The second string contains only 5 characters because of the 5
character precision specification. However, 10 leading blanks are added to fill the
112 PROBLEM SOLVING TECHNIQUES USING C

minimum field width specification, which is 15 characters. The last string contains only 5
characters and leading blanks are not added since width is 0.
Consider two integer variable x and y with values 27 and 117. Then in the statement
printf("%d %d\n",x,y);

the first %d called the format conversion specifier instructs that x will be printed as
a decimal integer (d stands for decimal) in a field as wide as may be necessary. Since x is
two-digit number, it will be printed in 2 columns. The second %d refers to y, which being a
3-digit number will be printed in a field 3 digit wide. The \n takes the cursor to the
beginning of next line. Since we have given a single space between the %d's in the control
string, there will be a single space separating the values of x and y as follows:
27 117
Suppose we introduce the format specification t for a tab between the %d's then
printf ("%d\t%d\n",x,y); will output the values separated by a tab (skips 7 columns)as
27 117
The output of printf("\tThe value of x = %d,\n\twhile y=%d.",x,y); will be
The value of x = 27,
while y = 117.
It is very important that there should be one-to-one correspondence between each
format conversion specifier and the list of variables or expressions. Since the % character
has a syntactic value in the control string, 2 consecutive occurrences %% are required in
the string, to print it as a literal in the output.

Example 3.10

/* Program to show printing of % character */


# include <stdio.h>
void main( )
{
int rain = 70;
printf("\n There\'s %d %% chances of rain today !",rain);
getch();
}
Output
There's 70 % chances of rain today !

3.5 WRITING AND SAVING THE FIRST C PROGRAM


To type and execute a C program, a special environment called the Integrated
Development Environment (IDE) is required. The IDE for C/C++ is the Turbo C++
compiler.
MANAGING INPUT AND OUTPUT OPERATIONS 113

Generally the compiler is installed on the computer in the C:\TC directory. Create a
folder in D: as IBSc and another folder TCTEMP. Save your programs in D:\IBSc.
TCTEMP will store all the .obj, .exe and .bak files of your C programs. Turbo C++ IDE
consists of menu driven environment giving all possible options for saving, opening,
compiling and running the C/C++ programs.
To start the IDE, a shortcut can be created on the desktop as follows :
(i) Open My Computer on the Desktop
(ii) Double click on C
(iii) Double click on TC folder
(iv) Double click on Bin folder
(v) Right click on TC (application) Fig. 3.7 MS-DOS
TC.EXE
(vi) Select and click on send to Desktop (create shortcut) (Figure 3.7)
Now a shortcut of Turbo C++ IDE is created on the desktop as shown.
Double click on the icon of TC++ IDE to get the opening screen as shown in Figure
3.8. Set the output folder to TCTEMP as follows:
i) Click Options.
ii) Select and click on Directories
iii) Type D:\TCTEMP under Output Directory.

Fig. 3.8 : TC++ IDE-Opening Screen


114 PROBLEM SOLVING TECHNIQUES USING C

Fig. 3.9 : Program Code

To create your first program, type as follows :


(i) Click on File.
(ii) Select New.
(iii) A new file with the name nonameoo.cpp will open
(iv) Type your program code, as shown in Fig. 3.9
(v) On completion, save the code as follows.
(vi) Click File and select Save As.
(vii) The dialog box shown in figure 3.10 will appear.

Fig. 3.10 : Save Dialog Box


(viii) Type the file name with the extension. C for example, sum C.
(ix) Click on OK button to save the file sum.C.
MANAGING INPUT AND OUTPUT OPERATIONS 115

3.5.1 TC ++ Editor Commands


The most often used commands is TC++ editor are as follows in Fig 3.11.

Command Meaning

Alt + FN Open a new file


F3 Open an existing file
F2 Save a file
Alt + FD Dos shell
Alt + Fx or Alt + X Close TC++
Ctrl + Ins Copy to clip board
Shift + Ins Paste
Ctrl + Del Clear
Shift + Del Cut
F9 Link
Ctrl + F9 Compile and Run
Alt + C Compile
Alt + R Run
Alt + F5 Output screen

Fig. 3.11 : TC++ Editor Commands

3.5.2 Compiling and Linking the Source Code


The source code of sum. C must be compiled and executed. To compile :
(i) Select the option compile in the menu bar and click on compile as shown in
figure 3.12. The other method is to type Alt + C and click on the first option.
(ii) The program now is compiled and shows a list of errors if any. If errors are
present, correct the errors.

Fig. 3.12 : Compilation


116 PROBLEM SOLVING TECHNIQUES USING C

(iii) Once the program becomes error free, linking is done as shown in figure 3.13.

Fig. 3.13 : Linking

(iv) The linking dialog box appears as in figure 3.14.

Fig. 3.14 Linking Dialog Box


MANAGING INPUT AND OUTPUT OPERATIONS 117

Executing the C program


The compiled and linked C program is now ready for execution. It can either be
executed from
 the IDE
 DOS prompt
To run the code from TC ++IDE
(i) Press Ctrl + F9 or Alt + R
(ii) To check the output, Press Alt + F5.
The output screen appears as in figure 3.15.

Fig. 3.15 : Output Screen

The program can also be executed on the DOS prompt by typing the file name. For
example, for the C program sum.C an executable file called sum.exe will be created in the
folder Tctemp. To execute the code :
(i) Select Alt + F and select DOS shell.
(ii) Type sum on the prompt.
The results will be displayed as shown in figure 3.16.

Fig. 3.16 : Output from DOS Prompt


118 PROBLEM SOLVING TECHNIQUES USING C

(iii) To go back to the IDE.type Exit.


(iv) The files created during compiling and linking are :

sum.C Source code


sum.obj Object code generated after compilation
sum.exe Executable code
sum.bak a backup of source code.

3.6 SOFTWARE ENGINEERING


Since this chapter is only an introduction to C language, some concepts of program
documentation, data naming and data hiding are discussed.

3.6.1 Program Documentation


The two levels of documentation are :
 General documentation
 Module documentation
General documentation starts at the beginning of any program containing the
following comment statements :
1. Name and aim of the program.
2. Name of the author.
3. Data of first version written.
4. Documentation of each change with the date on which it was changed. For
programs which are being used for several years, the change history could
become extensive.
Module documentation consists of brief description using comments for every
block of code. A block of code containing a set of statements which execute one
particular task.
Each block of code must be separated by a blank line. The brief description can
be about the purpose and the operations performed in that block of code.

3.6.2 Data Names


Another important concept of good programming technique is using relevant data
names. To construct good, relevant and intelligent data names, the following guidelines
can be used:
MANAGING INPUT AND OUTPUT OPERATIONS 119

1. The dataname must be as close as possible to the general terminology used. For
example to calculate the area of a circle using the formula area =  r2, the data
names can be area, pi and radius.
2. The datanames must not be too short or abbreviated so much that they lose their
identity. For example, simple interest should not be named as si. For such
datanames underscore can be used as in simple_interest.
3. In long datanames, the first letter of each word can be capitalized such as ProductId.
Since C is case sensitive, the programmer must be careful while typing these
datanames.
4. Do not create datanames that are too similar especially when there is a difference of
only one or two letters. For example total, totals. However, there can be a naming
pattern which makes it easy to remember those variable names.
5. Whenever abbreviations are used for datanames, they must clearly indicate the
word being abbreviated. Abbreviations must be used only for long words, not short
ones.
6. Try to avoid using generic datanames such as sum, total, emp etc.
7. Do not use literal values, if they change from system to system. Instead define
memory constants or defined constants in such cases. For example :

# define SPACE ‘‘
# define COMMA ‘,’

3.6.3 Data Hiding


Any data defined before main( ) becomes a global variable and is visible to all
other programs too, that are called. One of the main concepts of structured programming
is to hide the data structure from view. This leads to data hiding and data
encapsulation concepts. Data hiding protects data from accidental destruction by a
program segment that does not require this data. Therefore data must be encapsulated
along with the functions that use it and must be hidden from others which do not use it.
Therefore the first programming concept would be :

Never place variables in the global area of a program.

Since global variables can be used and changed by every part of the program which
is undesirable and against data hiding and data encapsulation.

3.7 TIPS AND COMMON PROGRAMMING ERRORS


1. Use defined constants but not global variables.
2. The function header for main must be written as :
120 PROBLEM SOLVING TECHNIQUES USING C

int main (void) //or void main( )


{


}

3. A compiler error will occur if you do not close the format string in scanf or printf
statements.
4. Reading an integer with a float conversion code leads to error.
5. No comma after the format string in a read or write statement is a compile
error.
6. When a block comment is not closed with a */, it leads to error.
7. Not including libraries such as stdio.h or math.h for some mathematical
computations, leads to errors.
8. Misspelt functions such as printf or scanf will compile without errors, but will
get linker error.
9. Missing address operator (&) in a scanf statement is a run-time error.
10. Do not use commas or other characters in the format string of scanf statement.
This will lead to run-time errors, if the user does not type commas while
inputting data. For example in the statement :

scanf (“%d, %d”, &x, &y) ;

the data input for x and y must be separated by a comma.


11. If you by mistake, use the address operator (&) with a variable in a printf
statement, it will lead to run-time error.
12. Never put a trailing whitespace at the end of a format string in a scanf
statement such as :

scanf (“ %f ”, &x) ;

This leads to fatal run-time error.

REVIEW QUESTIONS

Short Answer Questions (Input/Output)


1. What are the common input/output functions in C?
2. What is the standard header file used for input/output functions?
3. What is the purpose of getchar function and how is it used in C?
4. What does the control string in scanf( ) do? What are its constituents?
5. Explain the use of field width parameter.
6. What is the purpose of # include<stdio.h>?
MANAGING INPUT AND OUTPUT OPERATIONS 121

7. Write the general syntax of getchar( ) function.


8. What is the purpose of putchar( ) function?
9. What are format specifiers. Explain with examples. (2011)
10. What is conversion specifier?
11. Explain the unformatted input and output functions.
12. Give the default field width for integer data and float data types.
13. Compare getchar and putchar.
14. Compare getchar( ) and scanf( ).
15. Explain the function used to read and write a character in C with an example. (2008)
16. List the format specifiers for scanf( ) function, for different data types. (2011)
17. How do you input integers using scanf( ) function?
18. What are the format specifiers used to read real numbers?
19. How do you left justify or right justify the input?
20. How do you read a string using scanf( ) function? What is the disadvantage?
21. Describe the functions gets( ) and puts( ).
22. Compare printf( ) and puts( ).
23. Compare printf( ) and putchar( ).
24. Compare scanf( ) and gets( ).
25. What is the difference between the control string of printf( ) and scanf( )?
26. Is there a difference in the output when upper case conversion specifiers are used
instead of corresponding lower case specifiers? Justify.
27. What is the difference between gets( ) and puts( ) ?
28. What is the difference between getchar( ) and getch( ) and getche( ) ? (2011)
29. How do you print percent sign in the conversion string?
30. How do you print double quotes in the conversion string?
31. Write a C program that calculates the area of a circle.
32. Write a program to read a number n and print n 2, n3, n4, n5.
33. Write a program to calculate simple interest (SI = PTR/100).
34. Write a program to convert temperature in Fahrenheit to Celsius (C = (F-32) 5/9).
35. Write a program to input amount, calculate a discount of 15% and output amount,
discount and the final bill.
36. Write a program to input total days and find the numbers of years, months and days
in the input.
37. Write a program to input total seconds and find the number of hours, minutes and
seconds in the input.
122 PROBLEM SOLVING TECHNIQUES USING C

Long Answer Questions (Input/Output)


1. Explain any 5 functions available in ctype.h
2. Explain the printf( ) function.
3. What are the conversion specifiers for printf( ) function.
4. What are the different formats for printing integers?
5. What are the different formats for printing real numbers?
6. Explain the process of formatting outputs of various data types with suitable
illustrations.
7. Explain the use of formatted input and output functions with suitable examples.
(2012)
Programming Assignments (Input/Output)
1. Given
#include<stdio.h>
int i,j,k;
write scanf() statements to read the values of i, j and k as follows :
(a) Assume i, j, k are integers with maximum no. of characters to be 5.
(b) Assume the value of i as integer, j as octal integer, k a hexadecimal integer,
each quantity not exceeding 6 characters.
(c) Assume i and j are hexadecimal integers and k is octal integer.
2. Find errors if any in the following statements. Justify your answers.
Assume
int a,b;
float x, y;
char ch, city[10];
double z;
(a) scanf ("%c %f %d",city,&x,&a);
(b) scanf("%s,%d",city,x);
(c) scanf("\n%f",z);
(d) scanf("%c %d %ld",*ch, &b, &z);
3. Find the output of the following given
int a = 1500;
float b = 552.46;
static char city[10] = "BANGALORE",
(a) printf("%d %f", a,b); (b) printf("%s",city);
(c) printf("%-10d %-15s",a,city); (d) printf("%f %3f %8f",b,b,b);
(e) printf("%8.3f %e %12e",b,b,b); (f) printf("%8.2e %-8f %-8e",b,b,b);
(g) printf("%08f %08.2e %g",b,b,b);
4. Write the output of the following printf statements assuming :
char c1 = 'V', c2 = 'R',c3 = 'C'
MANAGING INPUT AND OUTPUT OPERATIONS 123

(a) printf("%c %c %c", c1,c2,c3) (b) printf("%c %c %c",c1,c2,c3)


(c) printf("%3c %3c %3c",c1,c2,c3) (d) printf("c1=%c c2=%c c3=%c",c1,c2,c3);
5. Find errors if any in the following printf() statements. Justify your answers.
Assume int a, b; float x,y; char ch, city[10];double z;
(a) printf(%d 7.2%f, a, x);
(b) printf("%-s,%c"\n, city, ch);
(c) printf("%c %d %f\n",x,ch,a);
6. Show the output of the following, given the declaration :
static char text[60] = "Learning c can be a very challenging and creative activity";
(a) printf("\n%s", text); (b) printf("%30s",text);
(c) printf("%-30s",text); (d) printf("%-40.10s",text);
(e) printf("%40.20s",text); (f) printf("%35.30s",text);
7. Write a program to read the values of x and y and print the results for the following

xy xy
(a) (b) (c) (x + y) (x – y)
xy 2
8. Write a program to read the numbers
25.45, 55.20  43.77 and –25.45
The result must be rounded off to the nearest integer.
9. Write a program to read temperature in fahrenheit and convert it to celsius using
the formula
c = 5/9*(F  32)
10. Write a program to input an amount in paise and convert it to rupees and paise.
11. Write a program to input value in feet. Convert feet to yards, inches, cms, meters,
using yards = feet/3, Inches = 12*feet, cms = 2.54*inches and m = cms/100.
12. Write a program to find the radius of a circle. Input circumference.
13. Write a program to calculate the hypotenuse of a right angled triangle, whose base
and height and given.
14. Program to find the real roots of a quadratic equation ax 2 + bx + c = 0 using the

b  b2  4ac
formulae x1 , x 2  . Input a, b, c.
2a
15. Write a program to calculate compound interest at the rate of R%, for a deposit of
Rs. P for N years, given
Amount = P(1 + R/100)N
16. Given the length of a side, write a C program to compute surface area and volume of
a cube.
124 PROBLEM SOLVING TECHNIQUES USING C

Decision Making

3.8 INTRODUCTION
The set of statements in a C program are normally executed sequentially in the
order in which they are written. Such programs have sequential structure. However, in
reality, the order of execution of statements may have to be changed, depending on certain
conditions. Such programs where decision making is involved are said to have selection
structure.
C provides us with statements which help to alter the flow of control, so that control
can be transferred from one part of the program to another. The control or decision
structures available are :
i) if() statement
ii) switch statement
iii) Ternary operator
iv) goto statement
goto statement is used for unconditional transfer of control.

3.9 THE IF() STATEMENT


The if() statement is one of the most powerful statement of any programming
language. It is used to carry out a logical test of the condition and take one of the two
possible actions depending on the result of the test (i.e., whether the condition is true or
false). Thus in its simples form, the statement can be written as :

If(conditional expression)
s1;
s2;

Where s1 and s2 are statements. The conditional expression is an expression which


can use any of the C operators.
 Generally every conditional expression has a value.
 An expression that has non-zero value is true, whereas one that has a zero value
is false. Thus the value of 5>3 is 1 and 5<3 is 0.
 The condition must be placed in parantheses.
 The statement s1 will be executed only when the condition is true (when the
expression has non-zero value). Further it continues with the execution of the
next statement s2.
DECISION MAKING AND LOOPING 125

If the codnition is false or has a zero value, then statement s1 will be ignored and s2
will be executed.
The statement s1 can either be simple or compound. A simple statement contains
a single statement. A compound statement contains more than one statement.
When the condition is true, if a set of
statements have to be executed, they must be
enclosed in braces i.e.,

If (condition)
{
s1;
s2;
s3;
:
:
}
sn;

Thus when the condition is true all the


statement within braces will be executed. The
simple if( ) can be depicted with a flow chart as
shown in figure 3.17

Fig. 3.17 : if() statement flowchart

Example 3.11

/*Program to show usage of simple if()*/


#include<stdio.h>
void main()
{
int x,y=10;
clrscr();
printf("\n Enter value of x :");
scanf("%d",&x);
if(x>0)
printf("\n Sum=%d",x+y);
}

Output
Enter value of x : 5
Sum=15
126 PROBLEM SOLVING TECHNIQUES USING C

Some more are examples of simple if() :


a) if(balance= =0)
printf("\n No more shopping!");

b) if(a>b && a>c)


printf("\n largest number is %d",a);

c) int rain = 1;
if(rain==1)
{
printf("\n Wear a Raincoat");
printf("\n or hold an umbrella");
}

d) if(a>0 && b<10)


{
sum=a+b;
diff=a-b;
printf("\nSum = %d diff=%d"sum,diff);
}
e) if(dues>0)
{
printf("\nAccount number%d is overdue", accno);
credit=0;
}

f) if(a = = b || a = = c || b == c)
printf("\n It is an isoceles triangle");
In example 3.12 == tests the equality of the value of the expressions on either side.
Instead if a = b (single =) is written, then the value of 'a' becomes equal to b and therefore
there is no comparison involved.

Example 3.12
/* Program to show what happens when = is given
instead of == in if statement */
#include<stdio.h>
void main()
{
int x=0;
clrscr();
if(x=0) //condition becomes false since x=0
printf(" x is 0, x==0 is true, but this statement will not be output \n");
if(x!=0)
printf(" x is 0, x!=0 is false, so this statement will not be output \n");
if(x=50)//condition becomes true since value of x is non zero
printf(" can you believe it, x is actually %d !\n", x);
}
Output
can you believe it, x is actually 50 !
DECISION MAKING AND LOOPING 127

In the above example, the first if() assigns a value 0 to x, so that the condition
becomes false. Hence the printf() statement is not executed.
In the second if() x! = 0 is false and therefore the printf() statement is not output. In
the third if() statement the value of x becomes 50 which is non-zero and hence the
condition becomes true. Thus the last printf() is executed.

3.10 THE IF() - ELSE STATEMENT


The if() -else statement provides two-way branching. The general form of if( ) – else
is :

If (condition)
s1;
else
s2;
s3;

 If the condition is true, s1 will be executed otherwise s2 will be executed (when


the expression is false).
 In either case, only one of the compound/simple statements (s1 or s2) will be
executed. Both s1 and s2 can never be executed.
 Whether the condition is true or false, the control is finally transferred to
statement s3 after executing either s1 or s2 (Fig. 3.18).

Fig. 3.18 : if()-else flowchart


128 PROBLEM SOLVING TECHNIQUES USING C

Example 3.13
/*Program to determine if a given number is even or odd*/
#include<stdio.h>
void main()
{
int num,remain;
clrscr();
printf("\n Enter the number to be tested :");
scanf("%d",&num);
remain=num%2;
if(remain==0)
printf("\n % d is Even",num);
else
printf("\n %d is odd",num);
getch();
}

Output
Enter the number to be tested : 1279
1279 is odd
Enter the number to be tested : 38
38 is Even
Enter the number to be tested : 0
0 is Even (why?)

Example 3.14
//*Program to check whether a given year is a leap year*/
#include<stdio.h>
void main()
{
int yr,rem_4,rem_100,rem_400;
clrscr();
printf("\n Enter the 4 digit year to be checked :");
scanf("%d",&yr);
/* To find the remainders of division by 4, 100 & 400 */
rem_4 = yr%4;
rem_100 = yr%100;
rem_400 = yr%400;
if((rem_4==0 && rem_100!=0)||rem_400==0)
printf("\n %d is a leap year.",yr);
DECISION MAKING AND LOOPING 129

else
printf("\n %d is not a leap year ok !",yr);
getch();

Output
Enter the 4 digit year to be checked :2012
2012 is a leap year.
Enter the 4 digit year to be checked :2013
2013 is not a leap year ok !
Enter the 4 digit year to be checked :3000
3000 is not a leap year ok !

Example 3.15
/* Program to calculate absolute value of an integer*/
#include<stdio.h>
void main()
{
int num;
clrscr();
printf("\n Type a number :");
scanf("%d",&num);
if(num<0)
{
num=-num; //converts negative to positive number
printf("\n The absolute value is %d", num);
}
else
printf("\n The absolute value is %d",num);
getch();
}

Output
Type a number :-500
The absolute value is 500
Type a number :360
The absolute value is 360
Type a number :0
The absolute value is 0 (how?)
130 PROBLEM SOLVING TECHNIQUES USING C

Example 3.16
/*Program to show usage of char in if() statement*/
#include<stdio.h>
void main()
{
char wish;
clrscr();
printf("\n Want to go to movie Y/N ?");
wish=getchar();
if(wish=='Y'||wish=='y')
printf("\n Go and get ready quickly !");
else
printf("\n Go and start studying!");
}
Output
Want to go to movie Y/N ? Y
Go and get ready quickly !
Want to go to movie Y/N ? n
Go and start studying!
Want to go to movie Y/N ? y
Go and get ready quickly !
Want to go to movie Y/N ? A
Go and start studying!

3.11 NESTED IF() STATEMENT


The object statmeent of an if() statement may be
another if() statement. Such statements are called
Nested if() statements. The most general form of a nested
if() is as in figure 3.19.
Where e1,e2 are logical expression and s1,s2,s3
and s4 are statements.
 when the condition el is true, the condition e2
is checked. If true, s1 is executed and control is
transferred to s4. If condition e2 is false, s2 is
executed followed by s4.
Fig. 3.19 : Nested if()
 When the condition e1 is false, s3 followed by
statement
s4 are executed.
 It is possible that s1, s2 and s3 may contain other if-else statements. This is
called as multi-layer nesting.
 The flowchart for nested if() statement is illustrated in figure 3.20.
DECISION MAKING AND LOOPING 131

Figure 3.20 : Flowchart of Nested if() statement

Example 3.17
/* Program to show usage of nested if()*/
#include<stdio.h>
void main()
{
float hrs;
clrscr();
printf("\n Type the time in hours :");
scanf("%f",&hrs);
if(hrs >= 0.0 && hrs < 12.0)
printf("\n Good Morning");
else
if(hrs >= 12.0 && hrs < 17.0)
printf("\n Good Afternoon");
else
if(hrs >= 17.0 && hrs < 21.0)
printf("\n Good Evening");
else
if(hrs >= 21.0 && hrs < 24.0)
printf("\n Good Night");
132 PROBLEM SOLVING TECHNIQUES USING C

else
printf("\n Wrong Input");
getch();
}

Output
Type the time in hours :20.6
Good Evening
Type the time in hours : 5.0
Good Morning
Type the time in hours : 22
Good Night
Type the time in hours : 15
Good Afternoon
Type the time in hours : 50
Wrong Input

Example 3.18
/* Program to read a character and determine whether
it is an alphabet,digit or a special character*/
#include<stdio.h>
void main()
{
char ch;
clrscr();
printf("\n Enter a single character please:");
scanf("%c",&ch);
if((ch>='a' && ch<='z')||(ch>='A' && ch<='z'))
printf("\n It is an Alpahbet");
else
if(ch>='0' && ch<='9')
printf("\n It is a digit");
else
printf("\n It is a Special character");
getch();
}

Output
Enter a single character please: u
It is an Alphabet
Enter a single character please: !
It is a Special character
Enter a single character please: 7
It is a digit
DECISION MAKING AND LOOPING 133

The above program checks for both if (e1) True


uppercase and lowercase alphabets. When ch is s1;
neither alphabet nor digit it is assumed to be a else if (e2)
True
special character. s2;
else if (e3)
3.12 THE ELSE-IF() LADDER True
s3;
Another way of describing nested if() –
else is the else-if() ladder where every else is
associated with an if() statement. The general
form of else-if() ladder is as shown in figure else if (en)
sn;
3.21. else
Fig. 3.21 : The else-if() ladder default-statement
sx;
 e1,e1,e3,........ en are
the expressions or
conditions and s1, s2,
...... sn, default-state-
ment and sx are
statements.
 In this construct the
conditions are
checked, starting
from the top of the
else-if ladder, moving
downwards.
 Firstly e1 is checked;
if true s1 is executed
and control is trans-
ferred to sx,
 Otherwise e2 is
checked. If true s2 is
executed and control
is transferred to sx
skipping the rest of
the statements.
 When all the
conditions are false
i.e., e1, e2, ...... en
then the default-
statement executed
followed by execution
of statement sx. Fig. 3.22 : Flowchart of else-if() ladder
134 PROBLEM SOLVING TECHNIQUES USING C

 The else-if() can be understood better with the help of a flowchart shown in
figure 3.22.

Examples 3.18 and 3.16 also demonstrate the else-if( ) ladder.

Example 3.19

An Instructor conducts 3 tests Test1, Test2 and final, each out of 50 marks. The
best marks out of Test1 and Test2 is selected and added to final test marks. This
gives the total marks scored out of 100. Next, grades are assigned as follows :

Marks Grade
0 – 39 F
40 – 49 D
50 – 59 C
60 – 74 B
75 – 100 A

Write a C program to input marks scored in the three tests and output the grade
of the student.
/* Program to print the grade of a student */
#include<stdio.h>
void main()
{
int test1,test2,final,marks;
char grade;
clrscr();
printf("\n Enter marks in Test1,Test2,final :");
scanf("%d %d %d",&test1,&test2,&final);
/* calculate total marks out of 100 */
if(test1 > test2)
marks = final + test1;
else
marks = final + test2;
/* assigning grades */
if(marks >= 0 && marks < 40)
grade = 'F';
else if(marks < 50)
grade = 'D';
else if(marks < 60)
grade = 'C';
else if(marks < 75)
DECISION MAKING AND LOOPING 135

grade = 'B';
else if(marks <= 100)
grade = 'A';
else
grade = 'X';
if(grade != 'X')
printf("\n Grade is %c",grade);
else
printf("\n Error in input!!");
}

Output
Enter marks in Test1,Test2,final :50 50 25
Grade is A
Enter marks in Test1,Test2,final :20 10 30
Grade is C
Enter marks in Test1,Test2,final :20 10 15
Grade is F
Enter marks in Test1,Test2,final :40 39 80
Error in input!!

Example 3.20
A company has 4 categories of employees. The rent allowance is based on the
following rules :
Category1  30% of salary
Category2  20% of salary
Category3  15% of salary
Category4  10% of salary
Write a C program to read employee category and salary and print the rent
allowance.
/* Program to calculate rent allowance based on employee category */
#include<stdio.h>
void main()
{
int cat;
float sal,rent;
clrscr();
printf("\n Enter the category and salary of Employee :");
scanf("%d %f",&cat,&sal);
if(cat == 1)
rent = sal * 0.3;
136 PROBLEM SOLVING TECHNIQUES USING C

else if(cat == 2)
rent = sal * 0.2;
else if(cat == 3)
rent = sal * 0.15;
else if(cat == 4)
rent = sal * 0.1;
else
{
printf("\n Wrong Input ");
exit();
}
printf("\n The rent allowance = %7.2f",rent);
getch();
}

Output
Enter the category and salary of Employee : 1 35000
The rent allowance = 10500.00
Enter the category and salary of Employee : 4 10000
The rent allowance = 1000.00
Enter the category and salary of Employee :23 3000
Wrong Input

3.13 THE SWITCH-CASE-DEFAULT STATEMENT


The switch-case-default statement is useful whenever flow of control must be
directed to one of the several possible statements. A chain of if() -else can be used in such
situations. However if() -else becomes cumbersome when the number of if() levels exceed 4.
At such times, the switch-case-default statement is more appropriate. Thus the general
syntax of switch statement is as in figure 3.23.

switch (variable or expression)


{
case Val1 : s1;
break;
case Val2 : s2;
break;
.......... :
.......... :
case Valn : sn
: break;
default : sd
break;
}
statement-x;

Fig. 3.23 : switch-case-default


DECISION MAKING AND LOOPING 137

 switch is the keyword, which checks the value of the variable or expression given
within parentheses with a list of case values val1, val2, ....... valn, known an
case labels.

 The variable or expression must result in an integer value (or a single


character). The case labels val1, val2, ...... valn are constants or constant
expressions which result in an integer constant.

 Each case value must be unique within a switch statement. The values can be in
any order.

 Statements s1, s2, etc can be a single statement or a block or statements. Case
value can also be given without any statements.

 Each case label is followed by a : (colon) and the cases are listed in a set of curly
braces.

 When the switch statement is executed depending on the value of the variable or
expression, the corresponding set of statements is executed. If the switch value
does not match with any of the case labels listed, the statements corresponding
to default are executed.

 The default case is optional. When default is not given control passes to
statement-x if no match is found.

 The break statement, the last statement of every case including the default, is
necessary. The break statement is used to transfer control to the first-statement
outside the switch block i.e., statement-x. If absent, control flows to the next case.
This property may be used to advantage when multiple values of the variable say
val1, val2 and val3 must execute the same set of statements. For example :

case 1 :

case 2 :

case 3 : printf ("\n Values are 1, 2 and 3");

 Float values are not allowed as case labels.


138 PROBLEM SOLVING TECHNIQUES USING C

Fig. 3.24 : Flowchart of switch-case-default statement


The flowchart of a switch-case-default statements is as shown in figure 3.24.
 Nested switch statement can also be written where a switch statement would be
part of a block of statements for a particular case value.
Some valid statements are :
i) switch(i+j) // i & j are integer values
ii) case 10 : // numeric value
iii) case 'a' : // char value
iv) case 'a'+'b': case value is 97+98=195
v) case 1 :
case 3 :
case 5 : printf ("\n odd values 1, 3 and 5");
Some invalid statements are :
i) switch (i + 2.5) // floating point numbers are
// not allowed
ii) case 7.2 : // floating point numbers not
// allowed
DECISION MAKING AND LOOPING 139

iii) case7 : // space must be given after


// the keyword case
iv) CASE7 : // keyword case must be in
// lowercase
v) case i+j: // variables are not allowed
vi) case "end" : // strings are not allowed
vii) case "a" : // strings are not allowed
viii) case 1 : 3 : 5 : // separate case statements
printf("\n multiple values"); // must be written

Example 3.21
/* Program to calculate rent allowance based on employee category */
#include<stdio.h>
void main()
{
int cat;
float sal,rent;
clrscr();
printf("\n Enter the category and salary of Employee :");
scanf("%d %f",&cat,&sal);
switch(cat)
{
case 1 :
rent = sal * 0.3;
break;
case 2 :
rent = sal * 0.2;
break;
case 3 :
rent = sal * 0.15;
break;
case 4 :
rent = sal * 0.1;
break;
default :
printf("\n Wrong Input ");
break;
}
printf("\n The rent allowance = %7.2f",rent);
getch();
}

Output
Enter the category and salary of Employee :2 36000
The rent allowance = 7200.00
140 PROBLEM SOLVING TECHNIQUES USING C

Example 3.22
/* Program to compute decimal value of a hexadecimal digit */
#include<stdio.h>
#include<ctype.h>
void main()
{
char hexa;
clrscr();
printf("\n Enter a hexadecimal digit :");
hexa = getchar();
/* converting all lower case to upper case
using toupper() function */
hexa = toupper(hexa);
switch(hexa)
{
case 'A' :
case 'B' :
case 'C' :
case 'D' :
case 'E' :
case 'F' : printf("\n Decimal value of hexadecimal digit is %d",hexa-65+10);
break;
/* Characters A-F use the same conversion formula.
Hence only one statement for cases A to F */
case '0' :
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' : printf("\n Decimal value of hexadecimal digit is %d",hexa-48);
break;
/* ASCII code of zero is 48 */
default : printf("\n you typed a non-hexadecimal digit ");
break;
}
getch();
}

Output
Enter a hexadecimal digit :F
Decimal value of hexadecimal digit is 15
Enter a hexadecimal digit :8
Decimal value of hexadecimal digit is 8
Enter a hexadecimal digit :*
you typed a non-hexadecimal digit
DECISION MAKING AND LOOPING 141

3.14 THE CONDITIONAL OPERATOR


Most often this operator is used for making two-way decisions. It is a combination
of ? and : and needs 3 operands. Its general form is

Expression1 ? Expression2: Expression3;

 Expression1 or the condition is evaluated first, If true or non-zero, expression2 is


executed. If the condition is false or zero, expression3 is evaluated.
 Either expression2 or expression3 is evaluated, but never both.
 Nested conditional operator is also possible where expression2 may be another
conditional operator.
 The equivalent if() - else statement will be of the form :
If(expression1)
expression2;
else
expression3;
The corresponding flowchart of a conditional or Ternary operator is as shown in
figure 3.25.

Fig. 3.25 : Flowchart of conditional operator

Example 3.23
A cloth showroom offers discount on purchase of items as follows :
Purchase amount Discount
0 – 100 5%
101 – 200 7.5%
201 – 300 10%
Above 300 15%
Write a program to calculcate the net amount to be paid after discount.
142 PROBLEM SOLVING TECHNIQUES USING C

/* Program to calculate net amount after discount using ? : operator */


#include<stdio.h>
void main()
{
float amount,net;
clrscr();
printf("\n Enter the purchase amount please :");
scanf("%f",&amount);
if(amount<=0)
{
printf("\n Invalid amount ");
exit();
}
/* computation of net amount */
net = (amount <= 100) ? amount - amount * 0.05 :
(amount <= 200) ? amount - amount * 0.075 :
(amount <= 300) ? amount - amount * 0.01 :
amount - amount *0.15;
printf("\n The amount after discount =%7.2f",net);
getch();
}
Output
Enter the purchase amount please :110
The amount after discount = 101.75
Enter the purchase amount please : 542.9
The amount after discount = 461.47

3.15 THE GOTO STATEMENT


goto statement transfers control unconditionally to another part of the program
which is marked by a label. The general form of goto is :
goto label;
Where label identifies the statement to which control must be transferred.
 A label is a valid variable name. Label names follow the same rules as
identifiers. i.e., They are built from alphabets, digits and underscore, where the
first character must be an alphabet.
 A label name followed by colon: is placed just before the statement where
control has to be transferred. The general forms of goto and label are :
goto label; label:
- s2 ;
- -
- -
- -
label: goto label;
s1;

Fig. 3.26 : Forward jump Backward jump


DECISION MAKING AND LOOPING 143

 When the label is placed after the goto statement, it is known as forward jump.
However when the label is placed before the goto statement, it is known as
backward jump as shown in figure 3.26.
 Each label in a program must be unique. No two statements can have the same
label.
 goto is also used in combination with if() statement as a looping structure.
 Sometimes goto statements result in endless loops known an infinite loops, due
to the uncodnitional transfer of control.
 goto can be used to transfer control out of a loop or nested loops, depending on
some condition.
 In structured programming goto statements must be avoided.

Example 3.24
/* Program to reverse a number using if() and goto */
#include<stdio.h>
void main()
{
int n,rem,rev = 0;
clrscr();
printf("\n Enter a number :");
scanf("%d",&n);
start :
if(n == 0)
/* terminates the loop when n=0 */
goto finish;
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
goto start;
finish :
printf("\n The reversed number is : %d",rev);
getch();
}
Output
Enter a number : 1234
The reversed number is : 4321
Enter a number : 5678
The reversed number is : 8765
144 PROBLEM SOLVING TECHNIQUES USING C

LOOPING

3.16 INTRODUCTION
Loops are required whenever a set of statements must be executed a number of
times. We know that a computer is capable of executing a set of statements repetitively
with precision. This looping capability allows programmers to develop programs
containing repetitive or iterative processes, which would otherwise require thousands of
statements to be executed.
A looping structure is one, where a sequence of statements are executed repeatedly
until some condition for termination of the loop is satisfied.
Thus a loop consists of two parts; the body of the loop and the control statement. The
control statement checks the given condition and then executes the set of statements in
the body of the loop.
Control structures can be classified into two categories depending on the position of
the control statement. They are :
a) Entry-controlled loops
b) Exit-controlled loops
Entry

Check False
Condition ?

Body of
loop

Exit
Fig. 3.27 : Entry-controlled Loop

The loops in which the control conditions are tested before looping are known as
Entry-controlled Loops. In such loops the body (or domain) of the loop will be executed
only when the condition is true. Otherwise the domain of the loop is not executed and
control is transferred to the next statement outside the domain of the looping structure.
Figure 3.27 depcits the working of an entry-controlled loop.
Thus the body of the loop will be executed repeatedly untill the control condition
becomes false.
DECISION MAKING AND LOOPING 145

The loops in which the control condition are tested at the end of the body of the loop
are known as Exit-controlled Loops.
In this case the body of the loop will be executed at least once since the condition is
tested at the end of the loop. Thus the looping statements will be executed repeatedly until
the control condition becomes false. Figure 3.28 iillustres the working of an exit-controlled
loop.
The test condition stated in the looping structure is very important. It must be such
that the control is eventually transferred outside the loop, once the desired number of
executions are performed.

Entry

Body of
loop

Check False
Condition ?

True

Next statement

Fig. 3.28 : Exit-controlled Loop

In a case where the test condition never becomes false, an infinite loop is set up and
the statements within the domain are executed repeatedly. Therefore care must be taken,
to avoid infinite loops.
In general, a looping structure consists of the following steps :
a) Initializing a counter.
b) Executing the statements in the domain of the loop.
c) Testing the condition in the control statement. The testing could be either to
match the given condition or to determine whether the loop has been executed
the specified number of times.
d) Incrementing the counter.
The three types of looping constructs available are :
1) The while() loop
2) The do-while () loop
3) The for(; ;) loop
146 PROBLEM SOLVING TECHNIQUES USING C

3.17 THE WHILE() STATEMENT


while() structure is an Entry-controlled structure. It’s general form is :

while (expression)
{
Statements;
...
Domain of
...
... Loop
}
next_statement;

Fig. 3.29 : Structure of while loop

The test expression is evaluated.


 The condition is checked next. If the condition is found to be true, the statements
in the domain are executed and control transferred back to the test expression.
 When the condition is false, control is transferred to the next statement outside
the loop.
 The body of the loop may contain one or more statements. A single statement in
the loop does not need braces. However, braces are required when more than one
statement exists in the loop.
 Thus the body of the loop is executed repeatedly, as long as the condition is true
and control is transferred to the next statement outside the loop, when the
condition becomes false.
In this example, first i is initialized to 1. Next the loop is executed 5 times, each
time incrementing the value of i by 1. When i becomes 6, the condition is false and the loop
is terminated.

Example 3.25

/* Program to find the sum of first n natural numbers 1+2+3+.....+n */


#include<stdio.h>
void main()
{
int sum = 0,i = 1,n;
clrscr();
printf("\n Enter the value of n :");
scanf("%d",&n);
while(i<=n)
{
sum = sum+i;
DECISION MAKING AND LOOPING 147

i++;
}
printf("\n Sum = %d",sum);
}

Output
Enter the value of n : 5
Sum = 15
Enter the value of n : 0
Sum = 0

Example 3.26
/* Program to calculate the LCM and GCD of two positive integers */
#include <stdio.h>
void main()
{
int m,n,temp,lcm,gcd;
clrscr();
printf("\n Enter two integers m & n :");
scanf("%d %d", &m, &n);

/* Assign m * n to temp to retain the original value of m and n */

temp = m * n;

/* Calculation of gcd */
while(m != n)
{
if(m > n)
m = m - n;
else
n = n - m;
}
gcd = n;
lcm = temp / gcd; // computing lcm
printf("\n LCM = %d GCD = %d", lcm, gcd);
getch();
}

Output
Enter two integers m & n :12 16
LCM = 48 GCD = 4
148 PROBLEM SOLVING TECHNIQUES USING C

Example 3.27
/* Program to reverse an integer number */
#include<stdio.h>
void main()
{
int num,rev,remain;
clrscr();
printf("\n Enter a number :");
scanf("%d",&num);
/* initialize rev to 0 */
rev = 0;
while(num !=0)
{
remain = num % 10;
rev = rev * 10 + remain;
num = num / 10;
}
printf("\n Reversed number is = %d",rev);
Dry Run
}
rev = 0, num = 678
Output
remain rev num
Enter a number : 590
8 8 67
Reversed number is = 95
7 87 6
Enter a number : 678
6 876 0
Reversed number is = 876

Example 3.28
/* Program to generate the first n Fibonacci Numbers */
#include<stdio.h>
void main()
{
int i = 3,fib1 = 0,fib2 = 1,fib,n;
clrscr();
printf("\n How many Terms ? ");
scanf("%d",&n);
printf("\n %d \n %d",fib1,fib2);
while(i < n)
{
fib = fib1 + fib2;
printf("\n %d",fib);
fib1 = fib2;
fib2 = fib;
i++;
}
DECISION MAKING AND LOOPING 149

getch();
}

Output Dry Run


How many Terms ? 5 n=5, i=3, fib1=0, fib2=1
0
i fib1 fib2 fib
1
3 0 1 1
1 4 1 1 2
2 5 1 2 3
3

3.18 THE DO-WHILE( ) STATEMENT


The do-while ( ) statement is an exit-controlled structure. Its general form is

do
{
Statements;
... Body of
...
Loop
...
}
while (condition);
next_statement;

Fig. 3.30 : Structure of do-while loop


 In the do-while( ) structure, the body of the loop is evaluated first.
 The test condition is checked next. If the condition is true, control is transferred
back to the beginning of the loop.
 When the condition is false, control is transferred to the next statement outside
the loop.

Example 3.29
/* Program to find the sum of digits of a number */
#include<stdio.h>
void main()
{
int num,sum = 0,rem;
clrscr();
printf("\n Enter a positive number ");
scanf("%d",&num);
do
150 PROBLEM SOLVING TECHNIQUES USING C

{
rem = num % 10;
sum = sum + rem;
num = num / 10;
}
while(num > 0);

printf("\n Sum of the digits = %d",sum); Dry Run


} sum = 0, num = 246
Output rem sum num
Enter a number 246 6 6 24
Sum of the digits = 12 4 10 2
Enter a positive number 0 2 12 0
Sum of the digits = 0

3.19 THE FOR(; ;) STATEMENT


The for(; ;) statement is one of the most versatile and popular looping structure of C.
It is an Entry-Controlled loop and its general form is :

False

for (first-exp;second-exp third-exp)


{ True
Statements;
 Domain of

Loop


{
next_statement
Fig. 3.31 : Structure of for loop

1) The first-exp is an assignment expression used to intialize the loop index or


counter, first-exp is evaluated before entering the body of the loop.
2) Next, the second-exp which is the test condition, is checked. The loop is entered
only if the condition is true, Otherwise control is transferred to the next statement
outside the loop.
3) When the condition is true, the statements in the loop are executed and control
is transferred to the beginning of the loop to evaluate the third-exp. The
DECISION MAKING AND LOOPING 151

third-exp is usually an assignment statement used to increment or decrement the


loop index.
4) The new value of the loop index is tested once again in the second-exp. If the
condition is true, the statements in the loop are executed. This process is repeated
until the test condition becomes false. For example, consider the following segment
of a program :

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


printf("\n%d",i);

In this example, i is set to 1 and the condition i < = 10 is checked. Since the
condition is true 1 is printed.
Next i is increment to 2 and again the condition is checked. Since the condition is
true, 2 is printed. This process continues until i becomes 11. Since the condition here
becomes false, the loop is terminated. The output is :
1
2
3
.
.
10

Similarly the numbers 10 to 1 can also be printed as follows :

for (i = 10; i > 0; i --)


printf("\n %d", i);

The output is :

10
9
8
:
1

5) Semi-colon must not be placed after the third-expression.

6) The two semi-colons are compulsory, but the three expressions are not.
Any one or all the them may be absent, for (; ;) is a valid statement. For example :
152 PROBLEM SOLVING TECHNIQUES USING C

for (i = 3; ;)
printf("\n%d",i);
and
i = 3;
for(; ;)
printf("\n%d", i);

are same. Since there is no test condition, they form infinite loops.

7) The body of the loop may be a single or a compound statement.

8) The advantage in a for (; ;) loop is that all the three actions of initializing, checking
and incrementing of the loop index is done in the for (; ;) statement itself. The
comparison of the three types of loops is as shown in figure 3.32.

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


{ while (i<=10) do
statements; { {
- statements; statements;
- - -
- - -
- - -
} i++; i++;
} }
while (i<10);
(a) (b) (c)

Fig. 2.32 : (a) for(; ;) loop (b) while( ) loop (c) do-while( )loop

9) Comma Operator in for (; ;) Loop


In a for (; ;) statement, more than one variable can be initialized at a time by using
the comma operator. When commas separate the expressions, they will be evaluated from
left to right. Consider the following program segment :

x = 2;
for (i = 1; i <=10;i++)
{
-
-
x++;
}

This can be re-written using comma operator as :


DECISION MAKING AND LOOPING 153

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


{
...
}

Thus the initialization section and the incrementation section have two variables.

10) The test condition in a for (; ;) loop can be a compound condition containing the
control variable and any other external variable. In the program segment below, i is
the control variable and sum is an external variable.

sum = 0,
for (i = 1; i<=10 & & sum <=100; i++)
{
sum = sum + i;
printf("\n%d%d", i, sum);

11) for (; ;) loop can be used as delay loop using the null statement as follows :

for (x = 1; x<=1500; x++);

This loop causes a time delay since it is repeated 1500 times without executing any
statements. The semi colon at the end of for( ) loop is known as a null statement.
Therefore C compiler will not give an error message, when a semi colon is placed at the
end of a for (; ;) and care must be taken to avoid such mistakes.

Example 3.30
/* Program to check whether a number is prime or not */
#include<stdio.h>
void main()
{
int n,i;
clrscr();
printf("\n Enter a positive number please :");
scanf("%d",&n);
if(n <= 1)
{
printf("\n %d is not prime",n);
getch();
exit();
}
154 PROBLEM SOLVING TECHNIQUES USING C

for(i=2; i <= n/2; i++)


{
if(n % i == 0)
{ Dry Run
printf("\n %d is not prime ",n); n = 11, n/2 = 5
getch(); i n%i i < = n/2
exit(); 2 11%2< >0 T
} 3 11%3< >0 T
} //end of for() 4 11%4< >0 T
printf("\n %d is prime",n); 5 11%5< >0 T
getch(); 6 11 is prime F
} // end of main()

Output
Enter a positive number please : 11
11 is prime
Enter a positive number please : 10
10 is not prime

Example 3.31

/* Program to find the sum of the series 1 + x + x^2 + ..... + x^n */


#include<stdio.h>
#include<math.h>
void main()
{
float i,x,sum = 1;
int n;
clrscr();
printf("\n Enter the number of terms :");
scanf("%d",&n);
printf("\n Enter the value of x :");
scanf("%f",&x);
for(i = 1; i <= n; i++)
sum = sum + pow(x,i);
printf("\n Summation of series = %7.3f",sum);
}

Output
Enter the number of terms :10
Enter the value of x :2
Summation of series = 2047.000
DECISION MAKING AND LOOPING 155

Example 3.32
/* Program to print the sum of the series S = 1 + 1/2 + 1/3 + ....+ 1/n */
#include<stdio.h>
void main()
{
int n,i;
float sum = 0;
clrscr();
printf("\n Enter value of n :");
scanf("%d",&n);
for(i = 1; i <= n; i++)
sum = sum + 1.0 / i;
printf("\n Summation = %7.3f ",sum);
}

Output
Enter value of n :10
Summation = 2.929

3.20 NESTED LOOPS


When a for() statement is enclosed in the domain of another for () statement, they
are said to be nested. The inner loop is executed for every index value of the outer loop.
Figure 3.33 illustrates the working of nested loops.

printf("\n i j");
for(i=1; i<=5;++i)
{
for(j=0;j<=9; j++)
outer
{ inner
printf("\n%d %d", i,j); loop
loop
}
}

Fig. 3.33 : Nested Loops

 Firstly i is initialized to 1 and the condition i <=5 is tested. Since the condition is
true control passes to the next for() statement.
 Next the value of j is initialized to zero and the condition j < = 9 is tested. Since
it is found to be true, the body of the inner loop is executed, giving the output.
1 0
156 PROBLEM SOLVING TECHNIQUES USING C

 The inner loop is repeatedly executed as long as the conditions is true. When j =
10 control is transfered back to the outer loop and i incremented. The condition
is again tested and control passes to the inner for() loop.
 This process continues until the outer loop is completed. The output of the nested
loop is as shown :

i j
1 0
1 1
1 2
:
1 9
2 0
2 1
:
5 9

The nesting may be continued upto 15 levels.

Example 3.33
/* Program to generate a given Pattern with numbers */
#include <stdio.h>
void main()
{
int r , c ; /* r is row and c is column */
clrscr();
printf("\n\n\n Number Pattern\n\n\n");
for(r = 1; r <= 4; r++) // Outer loop for rows
{
for(c = 1; c <= r ; c++) // Inner loop for columns
printf(" %d ",c);
printf("\n");
}
getch(); //to see the results
}

Output
Number Pattern
1
1 2
1 2 3
1 2 3 4
DECISION MAKING AND LOOPING 157

Example 3.34
/* Program to generate a given Pattern */
#include <stdio.h>
void main()
{
int r , c ,num = 6 ; /* r is row and c is column */
clrscr();
printf("\n\n\n Given Pattern\n\n\n");
for(r = num; r >= 1; r--) // Outer loop for rows
{
for(c = 1; c <= r ; c++) // Inner loop for columns
printf("%2d",r);
printf("\n");
}
getch(); // to see the results
}

Output
Given Pattern
666666
55555
4444
333
22
1

Example 3.35
/* Program to generate a given Pattern with numbers */
#include <stdio.h>
void main()
{
int r , c1 , c2 , n,m,p ; /* r is row and c1,c2 are columns */
clrscr();
printf("\n Enter the number of rows: ");
scanf("%d",&n);
printf("\n\n Number Pattern \n\n");
p = 1;
for(r = 1; r <= n; r++) // Outer loop for rows
{
for(c1 =1;c1<2*n-r;c1++)
printf(" "); // printing leading spaces
for(c2 = 1; c2 <= r ; c2++,p++) // Inner loop for columns
printf("%d",p); //p prints upto middle of row
for(c2 = r-1;c2>=1;c2--,p--)
{
m = p-2; //m prints latter half of row
158 PROBLEM SOLVING TECHNIQUES USING C

printf("%d",m);
}
printf("\n");
}
getch(); //to see the results
}

Output
Enter the number of rows: 5
Number Pattern
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5

Example 3.36
/* Program to generate a given Pattern with numbers */
#include <stdio.h>
void main()
{
int r , c , k = 10 , i; /* r is row and c is column */
clrscr();
printf("\n\n\n Triangle Pattern\n\n\n");
for(r = 1; r <= 4; r++) // Outer loop for rows
{
for(i = 1; i <= k; i++) // for printing spaces
printf(" ");
for(c = 1; c <= r ; c++) // Inner loop for columns
printf(" %d ",r);
printf("\n");
k = k - 2;
}
getch(); //to see the results
}

Output
Triangle Pattern
1
2 2
3 3 3
4 4 4 4
DECISION MAKING AND LOOPING 159

Example 3.37
/* Program to find prime numbers in the range m to n where m and n
are positive integers and m< n */
#include <stdio.h>
void main()
{
int m,n,i,j,isprime;
clrscr();
printf("\n Enter lower and upper limit of the range m & n : ");
scanf("%d %d",&m,&n);
if(m<= 1)
m=2; //starting value of the range is made 2
printf("\n The Prime numbers are :\n\n");
for (i = m;i<=n;i++)
{
isprime = 1;
/* This loop checks i for a prime number */
for (j = 2;j<= i/2;j++)
{
if(i % j ==0)
{
isprime = 0;
break;
}
} /* End of j loop */
if(isprime)
printf("\n %d",i);
} /* End of i loop */
getch();
}

Output

Enter lower and upper limit of the range m & n : 5 25


The Prime numbers are :
5

7
11
13

17
19
23
160 PROBLEM SOLVING TECHNIQUES USING C

Example 3.38
/* Program to sum Exponential series up to n terms
Exponential series is e = 1 + x/1! + x^2/2! + ..... + x^n/n! */
#include <stdio.h>
#include <math.h>
void main()
{
int n,i;
float expo,x,fact;
clrscr();
printf("\n How many terms ? ");
scanf("%d",&n);
printf("\n Enter value of x : ");
scanf("%f",&x);
expo =1; fact = 1; /* initialize expo and fact to 1 */
for(i=1; i<=n ; i++)
{
fact = fact * i;
expo = expo + pow(x,i)/fact;
}
printf("\n exp(x) from Summation of Series : %f",expo);
printf("\n Library function value of Exp(x) : %f",exp(x));
getch();
}

Output
How many terms ? 15
Enter value of x : 2
exp(x) from Summation of Series : 7.389057
Library function value of Exp(x) : 7.389056

3.21 JUMPS IN LOOPS


There are times when it is required to
a) Terminate the execution of a loop
b) Exit a loop
c) Skip part of a loop
d) Exit from inner loop to outer loop depending on some condition
There are several ways by which, the above requirements may be executed. They
can be accomplished with the help of goto, break, continue and exit statements.

3.21.1 goto statement


goto statement can be used to transfer control from within while, do-while and for
loops. It can also be used to exit from nested loops. Figure 3.34 illustrates use of goto to
exit from loops.
DECISION MAKING AND LOOPING 161

while (condition) for ( ; ; )


{ {
if (condition1) for ( ; ; )
goto finish; {

if (condition2)
if (condition2)
goto loop; Exit goto loop;
Jump from exit
within loop from
loop nested
loop : loops }
}
loop :
}
finish :

Fig. 3.31 : Usage of goto within loops

3.21.2 Break Statement


Break statement is not only used in switch case default statement, but also in
while, do-while and for ( ) loops. It is used to exit from a switch statement or a loop.
However break statement cannot exit from nested loops, since it can exit only from the
loop containing it. The general form of break statement is
break;
Some examples of break statement within loops is shown in figure 3.35.

while(condition) do for ( ; ; )
{ { {
if (condition) for ( ; ; )
break; {
if (condition)
break; if (condition)
Exit Exit Exit break;
from from from
} inner }
loop loop loop
} while (condition1);
}

Fig. 3.35 : Usage of break within loops


162 PROBLEM SOLVING TECHNIQUES USING C

3.21.3 Continue Statement


It is used to bypass the rest of the statements in a loop. The loop does not terminate
when a continue statement is encountered. Rather the remaining statements in the loop
are skipped and the execution proceeds directly to the next iteration of the loop. Its
general format is :

continue ;

The continue statement can be included within a for( ), while( ) or a do-while( ) loop.
Continue statement transfers control to the test condition in do-while ( ) and while ( )
loops. However in a for ( ) loop, the continue statement re-directs controls to the increment
expression, evaluates third-exp and then tests the condition in second-exp. Some examples
of continue within loops are shown in figure 3.36.
Continue should not be used outside loops since it does not do anything goto
statement in structured programming must be avoided.

while(condition1) do for ( ; ; )
{ { {

if (expr2) if (expr1) if (expr1)


continue; continue ;
continue;

} }
}
while (condition1);

Fig. 3.36 : Usage of Continue Statement within Loops

3.21.4 exit() Function


exit() function is used to terminate a program immediately. The general form is
exit (n);

 It closes all open files, flushes memory buffers and returns the value of n to the
function that called it.
 n represents the exit status of the program, n = 0 represents error free
termination and n! = 0 means otherwise.
 The value of n can be used to diagnose the error.
 The default value of n is taken as zero which need not be specified. Thus the
default form is exit();
DECISION MAKING AND LOOPING 163

3.22 POINTS TO REMEMBER - FOR(; ;) STATEMENT


i) Loop index can appear in a statement in the body of the loop, but its value must
not be altered.
ii) The loop will not be executed when the initial value is greater than the final
value.
iii) Control can be transfered out of the loop but not inside it.
iv) In the case of nested loops the outer loop and the inner loop cannot have the
same index variable.
v) Each inner (nested) loop must be completely embedded within an outer loop.
vi) Control can be transferred from an inner loop (nested) to a statement in the
outer loop or to a statement outside the entire nest. However control cannot be
transferred to a statement wihin a nest from a point outside the nest.
vii) Some examples are shown in figure 3.37 which must be avoided.

loop1 loop1 loop1 loop1


loop2
loop3 loop2 loop2

(a) (b) (c) (d)

Fig. 3.37 : The above types of goto must be avoided

viii)The number of times a loop gets executed is calculated using the formula:

 upper limit  lower limit 


n  int    1
 step size 
 

For example in the loop


for (i = 0; i < 10; i = i + 2)
{
---
}

9  0
n  int    1  5
 2 
164 PROBLEM SOLVING TECHNIQUES USING C

3.23 COMPARISON BETWEEN WHILE() AND DO-WHILE()

do-while while()
1. The condition is tested at the 1. The condition is examined at
end of the loop. It is an Exit- the beginning of the loop. It is
controlled loop. an Entry-controlled loop.
2. The do-while() loop operates 2. The while() loop continues to opera-
as long as the condition is true. tes as long as the condition is true.
3. The do-while() loop is executed 3. The while() loop may not be
at least once. executed at all.

3.24 COMPARISON BETWEEN BREAK AND CONTINUE


break continue
1. General form is break; 1. General form is continue;
2. It is used transfer control 2. It cannot be used in a switch
outside a switch statement statement
3. It is used to exit from a loop 3. It is used to skip the statements
following it and proceed to the
next iteration of the loop.
4. break cannot exit from nested 4. In nested loops continue cannot
loops. proceed to the next iteration of the
outer loop
5. Example 5. Example
i = 0; i = 0;
while (i < 5) while (i < 5)
{ {
i++; i++;
if(i==4) if(i==4)
break; continue;
printf("%3d",i); printf("%3d",i);
} }
Output Output
123 1235

3.25 SOFTWARE ENGINEERING


In this unit, the concepts required to write clear and understandable programs are
discussed as below :
(i) Keep your program simple and short. The code must be easy to read and should be
unambiguous. A block of code should not be longer than one screen.
(ii) Parentheses
One technique to simplify code is to use parentheses, even when not required. When
DECISION MAKING AND LOOPING 165

a statement consists of multiple expressions use parentheses to make sure that the
compiler will interpret it, as you need.
(iii) Use of Communication
Ensure that you communicate with the user from the very first statement in your
program. The first message could identify the program and the last with a display
that says the program is done.
(iv) Indentation Rules
 Indent statements that depend on previous statements.
 Align else statements with their corresponding if statements.
 Place the opening brace and on a separate line. The statements within braces
must be beyond the opening and closing braces.
 Code only one statement on a single line.
 Further indent nested statements according to the above rules.
(v) Negative Logic
Negative logic refers to expressions that start with not or those containing multiple
not expressions within negative logic is not simple or clear. Try to avoid it.
(vi) Selection statements
The rules for coding selection statements according to the order of importance are :
 Code positive statements whenever possible.
 Code the normal or expected condition first.
 Code the most probable conditions first.
(vii) Determining Algorithm Efficiency
While comparing two different algorithms which solve the same problem, often, one
algorithm is found to be more efficient than the other. Therefore the study of
algorithm efficiency was given a name algorithmic by Brassard and Bratley.
Algorithmics is defined as “the systematic study of the fundamental techniques used
to design and analyse efficient algorithms”
 If a function is linear, i.e., it contains no loops, then its efficiency is a function of
the number of instructions it contains. The general format is :
f (n) = efficiency
where n is the number of elements to be processed.

 Linear Loops
Consider the following segment of code :

for (int i = 1; i <= 500 ; i ++ )


{
Body ;
}
166 PROBLEM SOLVING TECHNIQUES USING C

The body of the loop is executed 500 times. Since the efficiency is proportionate to
the number of iterations, it is

f (n) = n

 Nested Loops
To analyse nested loops, the number of iterations of each loop must be determined
first. Then the total number of iterations would be:
Iterations = Outerloop iterations * Inner loop iterations.

Tips and Common Errors


1. Use decrement/increment operators wisely.
2. Complement of < is >= and complement of > is <=.
3. Dangling else statements are difficult to debug. Avoid dangling else statements by
using braces, even when they are not needed.
4. If there are more than one statements after if or else in an if ...... else statement,
enclose the statements inside braces.
5. Do not use equal (=) operator with a floating-point number, since these numbers are
never exactly equal to a required value. To test for equality such as a == b, use the
expression :

if (fabs (a – b) < 0.0000001)

6. It is poor programming practice to write a switch statement without a default label.


7. Be aware that the while and for loops are preset loops which may not be executed
at all. Use a do....while loop if you want the loop to be executed at least once.
8. Do not use equality or inequality in the control expression in loops. You may
accidentally create an infinite loop.
9. It is a compile error to use variables that have not be defined.
10. It is an error to forget the semicolon at the end of an expression statement.
11. It is a compile error to terminate a defined constant (# define) with a semicolon.
12. It is an error when the operand on the L.H.S. of the assignment operator is not a
variable. For example :
x + 3 = y + z;
13. It is a compile error to use the modulus operator (%) with anything other than
integers.
14. It is a logical error to modify a variable in an expression, when the variable appears
more than once.
15. It is a logical error to use a variable before it has been assigned a value.
DECISION MAKING AND LOOPING 167

16. It is an error to place a semicolon after the if expression.


17. It is a compile error to put space between the following relational operations :
= =, !=, >=, <=
18. Do not use a variable as a value in a case label.
19. The logical operators require 2 ampersands (&&) or 2 bars (||). It is a logical error
to code them with only one.
20. It is a compile error to omit the semicolon after the expression in a do....while
statement.
21. It is a logical error to place a semicolon after the expression in a while or for
statement.
22. It is a logical error to update the control variable in both for statement and in the
body of the loop :
for (int i = 0; i <= 10; i++)
{
...........
i=i+1; error
}

REVIEW QUESTIONS

Short Answer Questions (Decision Making)


1. What is the purpose of if structure?
2. Explain if-else statement. (2011)
3. How do you differentiate between = and ==?
4. What is the purpose of ternary operators?
5. Explain nested if statements.
6. What is the purpose of switch statement?
7. What is purpose of goto statement? (2011)
8. In which control structure can the break statement be used?
9. Can multiple case labels be associated with a simple block of statements? Justify.
10. Can one if( ) statement have more than one else? Justify.
11. What is the numerical equivalent of true and false?
12. How do you execute more than one statement when a condition is true?
13. What is the purpose of the else command?
14. List the different types of if statements.
15. Describe the else-if ladder.
168 PROBLEM SOLVING TECHNIQUES USING C

16. Write a flowchart for if-else statement.


17. Write a flowchart for else-if.
18. Give the difference between break, goto and continue statements in a loop. (2011)
19. Differentiate between switch and if-else.
20. What is the advantage of ternary operator over if-else statement.
21. Can you use a float value in a switch statement? Justify your answer.
22. What is difference between case labels and goto labels?
23. What are case labels? What type of expression must be used to represent a case
label?
24. Write a flowchart for simple if.
25. What are nested statements? How is nested if interpreted?
26. What is the purpose of break and exit( ) statements in C ?

Long Answer Questions (Decision Making)


1. Explain the working of if statement and if-else statement with a suitable
programming example.
2. Compare the working of the various conditional statements.
3. Explain switch statement with an example. (2011)

Short Answer Questions (Looping)


1. Define the term looping.
2. What are the different looping statements available in “C”?
3. What is the purpose of a while statement?
4. What is the minimum number of times a while loop can be executed?
5. How is the execution of a while loop terminated?
6. What is the purpose of a do-while loop?
7. What is the minimum number of times a do-while loop can be executed?
8. What is the purpose of the index variable in a for loop?
9. Explain the usage of comma operator in a for loop?
10. What do you mean by nested for? Explain.
11. What is the purpose of continue statement?
12. When should we use the while and do-while loop?
13. When should we use for loop?
14. When is parenthesis not required in a looping statement?
15. What is the purpose of the first expression in for statement?
16. What do you mean by infinite loops?
DECISION MAKING AND LOOPING 169

17. What are the advantages of a while loop?


18. How do you calculate the number of times a for loop is executed?
19. What are the advantages of for loop?
20. What are nested loops?
21. What happens when a break statement is given within the inner most loop of a
nested for loop?
22. Compare break and continue statements.
23. Compare while and do-while loops. (2011)
24. Compare continue and goto statements.
25. Give the differences between break, goto and continue statements.

Long Answer Questions (Looping)


1. Explain the for loop. (2008)
2. What are the functions of the 3 expressions in a for statement? Can any one of them
be omitted? Justify your answer.
3. Explain the working of while statement with a suitable programming example.
4. Explain the working of do-while statement with a suitable programming example.
5. Explain the different looping control structures available in C. (2012)
6. What do you mean by nested for loops ? Explain with an example. (2011)
7. Give the output of the following program segments :
a) {
int i = 0, j = 0;
while (i<20)
{
if(i%5 = =0)
{
j = j + i;
printf("%d",j);
}
++i;
}
printf("\nj=%d",j);
}

b) void main()
{
int i = 0, j = 0;
do
{
if(i%5 = =0)
{
170 PROBLEM SOLVING TECHNIQUES USING C

j++;
printf("%d",j);
}
++i;
}
while(i<20);
printf("\nj = %d", j);
}

c) void main()
{
int i = 0, j = 0;
for (i = 1, i<10, j++)
{
if(i%2 = = 1)
{
j = j + i;
else j - - ;
printf("%d",j);
continue;
}
printf("\nj = %d",j);
}
}

d) void main()
{
int i, j, k = 0;
for(i = 0; i<4; i++)
{
for(j = 0; j<i; ++j)
x+= i+j1;
printf("%d", k);
break;
}
printf("\nk = %d",k);
}
e) void main()
{
int i, j, k, x = 0;
for (i = 0; i<5; i++)
for (j = 0; j<i; j++)
{
switch (i + j  1)
{
case 1 ;
DECISION MAKING AND LOOPING 171

case 0 : x = x + 1;
break;
case 2 :
case 3 : x = x + 2;
defaut : x = x + 3;
} //end of switch
printf("%d",x);
}//end of for
printf("/nx = %d",x);
}//end of main()

f) What is value of i & j after the loop is executed ?


for (i = 0, j = 0; i<5 && j < 25; i++, j++)
printf("\n %d%d",i, j);

8. Determine how many times the body of each loop will be executed.
a) i = 5; j = 50; b) x = 1;
while(i<=j) do
{ {
i = j/i; -
- x += 2;
- }
} while (x<5);
c) int i;
for(i = 1; i<=5; i = i + 2/3)
{
-
}
d) int x = 10, y = 7;
while (x%y>=0)
{
x++;
y+=2;
}

9. Find errors if any, in each of the program segments. All variables contain valid
values.
a) while (K! = 10); b) n = 0;
{ do
K = 1; {
sum ++; printf("%d",n);}
count++; while(n=1)
}
172 PROBLEM SOLVING TECHNIQUES USING C

c) do; d) for(x=1; x>=10; x++;)


total = total+x; {
while (total!=10); =
}

e) m = 1; n = 0; f) int i = 1;
for(m + n<10;;); for(;;)
- {
printf("\n Hello"); printf("%d",i++);
- if(i>10)
break;
m = m + 15; }

10. Which of the following is not an infinite loop ? Justify your answer.
a) while(1) b) for(; ;) c) x = 0;
{ { do
- - {
- - /*no change*/
} } }
while (x==0);
d) #define TRUE 0
--
While (TRUE)
{
-
-
}

11. Given a = 0;
while(a<5)
printf("\n%d",a++);
How many times does the loop execute.

12. How many times do the following loops execute ?


a) for(i = 0; i<=10; i = i+2) b) int i = 10;
printf("\n Hello"); while(i>=0)
{
printf("\n%d",i);
i - -;}

Programming Assignments (Decision Making)


1. Find errors if any :
a) if(a + b = c && c<0)
printf("wrong");
DECISION MAKING AND LOOPING 173

b) if(x = = 1)
a+b =c
else
a = =0

c) if(p>0)| | (a>0)
printf("\n Negative");

2. Give the output of the following program segments :


a) n = 0;
x=1;y=1;
if(n>0)
x++;
y- -;
printf("\n%d%d",x,y);

b) #define VERY_HAPPY 1
#include<stdio.h
main()
{
if(VERY_HAPPY)
printf("\n Thank You Very Much, God");
else
(printf("\n Things could be better, God");
}
3. Write a program to read a single digit and print it in English (i.e., 2 must
produce Two on the screen).
4. Write a program to input two numbers and determine whether :
a) the first is positive, negative or zero.
b) the second is positive, negative or zero.
c) The first is even or odd.
d) The second is even or odd.
e) Whether the first is exactly divisible by the second.
5. Write a program to find the reminder of M divided by N.Do no use % operator.
6. Write a program to read temperature in Fahrenheit and convert it to Celsius. The
program must be terminated when input is 999. Print the temperatures in the form
of a table.
7. Write a program to read a number within 25 and print its corresponding Roman
number (1 – I, 2 – II)

8. Rewrite the following without using compound relations :


a) if(a>b&&a>c)
printf("\n large=%d",a);
174 PROBLEM SOLVING TECHNIQUES USING C

b) if(num>100||num<0)
printf("\n Range error");

c) if(marks1>60&&marks2>70)|| total>200)
printif("\nselected");
else
printf("\n Not Selected");

9. Rewrite the following using switch statement :


if(a= =0)
printf("\n ZERO");
else if(a= =1)
printf("\n ONE");
else if (a= =2 || a==3)
printf("\nTWO or THREE");
else
printf("\nAbove THREE");

10. Give the output of the following :


main()
{
int i = 1;
if(i/(5>3)?(int)2.3:(float)5)
printf("\n will this line be printed?");
else
printf("\n Or will this line be printed?")
}
(Hint : ternary operator groups from right to left)
11. Write a switch statement which checks a char-type variable called color and
prints one of the following messages :
a) RED, if color has the value r or R,
b) GREEN if color has the value g or G;
c) BLUE if color has the value b or B,
d) WHITE if color has the value w or W,
e) BLACK if color has any other value.

12. Write the corresponding statement to the following conditions, given temp is
a float type of variable.
a) print ICE, if value of temp <0.
b) print WATER, if value of temp is between 0 and 100.
c) print STEAM, if value of temp exceeds 100.

13. The eligibility criteria for admission to a course is as follows :


Marks obtained in Physics> = 50
Marks obtained in Chemistry> = 45
Marks obtained in Mathematics> = 65
DECISION MAKING AND LOOPING 175

Total of all subjects> = 200


OR
Total in mathematics and physics> = 130
Write a program to Input the marks obtained in 3 subjects and check whether the
candidate is eligible or not.
14. Write a program to print multiplication table of a number using if-else and
goto statements.
15. Write a program to find the sum of the digits of a number using if-else and goto statements.

Programming Assignments (Looping)


16. To generate the output
a) 1 b) *
2 3 * *
4 5 6 * * *
7 8 9 10 * *
(floyd's triangle) *

17. a) * * b) | | | | |
* * |
* |
* * |
* * | | | | |
18. To generate the first 5 perfect numbers.
19. Generate the pyramid using nested loops.
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 9 9 8 7 6 5
20. To generate factorials of 1 to n numbers.
21. To read the weight of 50 girls and count the number of girls whose weight is
between 45 and 55.
22. To find the sum of the cosine(x) series

x2 x4
cos x  1   .....
2! 4 !
1 1 1
23. To print the summation of  using the series  4  1    .......
3 5 7
24. To generate 3 digit armstrong numbers (like 153) such that 13 + 53 + 33 = 153.
25. To find the largest and smallest of n numbers.
176 PROBLEM SOLVING TECHNIQUES USING C

26. To find larger of two valid dates.


27. To find smaller of two valid dates.
28. a) Write a program to count the number of 1s in the binary representation of an integer.
b) Write a C program to inverse an integer.
29. Write a C program to compute the following :
x3 x5
sin( x )  x   .....
3! 5!
30. Write a C program to check whether a given 5 digit number is a palindrome or not.
31. Write a program to read 10 integers from the keyboard and print the sum of even
and odd numbers.
32. Write a program to input a number N. If the right most digit of N is 0, then output
“ZERO”.
33. Write a C program to print GCD of two given numbers.
34. Write a C program to find the reverse of an integer number. Check whether the
number is a palindrome or not.
35. Write a C program to calculate:

n!
nC =
r r ! * * (n  r )!

__________

View publication stats

You might also like