Module - 2
Module - 2
Console I/O
The C language does not have any special keywords for input and output. Instead, input and
output are done using library functions.
All these input and output functions are available in the header file <stdio.h>. They allow data
transfer between the program and devices like the keyboard, screen, or files.
There are two types of I/O in C. Console I/O is used for input from the keyboard and output to
the screen. File I/O is used to read from or write to files. Technically, both are similar, but
conceptually they are different.
Standard C only provides basic input and output, which is text-based (TTY). It does not
include functions for moving the cursor, drawing graphics, or creating windows and dialog
boxes. These features depend on the compiler or operating system, not on the C language
itself.
When we say console I/O, we usually mean keyboard input and screen output. But in reality,
these functions work on standard input and standard output. These can also be redirected, for
example, input can come from a file instead of the keyboard.
The simplest console I/O functions are getchar( ) and putchar( ). The getchar( ) function reads
a single character from the keyboard, while the putchar( ) function writes a single character to
the screen.
The getchar( ) function waits until a key is pressed and then returns the value of that key. The
pressed key is also shown (echoed) on the screen automatically.
The putchar( ) function displays a character on the screen at the current cursor position.
Although getchar( ) returns an integer, its value is usually stored in a char variable because the
character is contained in the lower byte. If an error occurs, getchar( ) returns EOF (defined in
<stdio.h> and usually equal to -1).
The putchar( ) function takes an integer as an argument, but normally a character is passed to it.
Only the lower byte of that integer is displayed on the screen. If successful, it returns the written
character, otherwise it returns EOF.
The following program shows the use of getchar() and putchar(). It reads characters from the
Dept of CSE
Programming in C Module - 2
keyboard and displays them in reverse case (uppercase becomes lowercase and lowercase
becomes uppercase). The program stops when a period (.) is entered.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
printf("Enter some text (type a period to quit).\n");
do {
ch = getchar( );
if(islower(ch))
ch = toupper(ch);
else
ch = tolower(ch);
putchar(ch);
} while (ch != '.');
return 0;
}
In many compilers, getchar( ) works in a line-buffered way. This means that the characters you
type are stored in a buffer and only sent to the program when you press ENTER.
So even though getchar( ) reads one character at a time, you still need to press ENTER first.
This can leave extra characters in the buffer, which is not convenient for interactive programs.
Alternatives to getchar( )
Since getchar( ) may not behave well in interactive environments, many compilers provide
other functions like getch( ) and getche( ). These functions are not part of Standard C, but they
are very commonly used.
Their prototypes are usually found in <conio.h> (in some compilers they have a leading
underscore, such as _getch( ) or _getche( ) in Visual C++).
The getch( ) function waits for a key to be pressed and immediately returns it, but does not
display it on the screen. The getche( ) function is similar, but it also echoes the character to the
screen.
Dept of CSE
Programming in C Module - 2
Here is the same program using getch( ) instead of getchar( ). Now, each character is read and
processed immediately without waiting for ENTER, and the input is no longer line-buffered.
#include <stdio.h>
#include<conio.h>
#include <ctype.h>
int main(void)
{
char ch;
printf("Enter some text (type a period to quit).\n");
do {
ch = getch( );
if(islower(ch))
ch = toupper(ch);
else
ch = tolower(ch);
putchar(ch);
} while (ch != '.');
return 0;
}
When this program runs, every key you press is instantly read and shown in reverse case. This
makes getch( ) and getche( ) very useful for interactive programs, even though they are not
part of Standard C.
The functions gets( ) and puts( ) are used to read and write strings. They allow handling
multiple characters at once instead of a single character.
The gets( ) function reads a line of text entered at the keyboard and stores it in the character
array passed as its argument. The input ends when the ENTER key is pressed, and a null
character '\0' is automatically added at the end of the string.
Here, str is a character array where the entered string will be stored, and gets( ) also returns the
same string.
The following program uses gets( ) to read a string and then prints its length:
#include <stdio.h>
#include <string.h>
int main (void)
{
char str[80];
Dept of CSE
Programming in C Module - 2
gets(str);
printf("Length is %d", strlen(str));
return 0;
}
When using gets( ), you must be careful because it does not check the size of the array. If the
user enters more characters than the array can hold, it can cause an overflow. For safe input,
functions like fgets( ) are preferred.
The puts( ) function is used to display a string on the screen followed by a newline character.
Its prototype is:
The puts( ) function understands escape sequences such as \t for tab or \n for newline. Unlike
printf( ), it cannot format numbers or variables—it simply prints a string. Because of this, it is
faster and takes less memory than printf( ).
For example, the following statement displays a message on the screen: puts("hello");
If successful, puts( ) returns a nonnegative value, otherwise it returns EOF. But in console
output, errors are rare, so its return value is usually ignored.
When using gets( ), you must be careful because it does not check the size of the array. If the
user enters more characters than the array can hold, it can cause an overflow. For safe input,
functions like fgets( ) are preferred, which will be explained later.
The puts( ) function is used to display a string on the screen followed by a newline character.
Its prototype is:
The puts( ) function understands escape sequences such as \t for tab or \n for newline. Unlike
printf( ),it cannot format numbers or variables,it simply prints a string. Because of this, it is
faster and takes less memory than printf( ).
For example, the following statement displays a message on the screen: puts("hello");
console output, errors are rare, so its return value is usually ignored.
Dept of CSE
Programming in C Module - 2
Function Operation
getchar( ) Reads a character from the keyboard; usually waits for carriage return.
getche( ) Reads a character with echo; does not wait for carriage return; not
defined by Standard C, but a common extension.
getch( ) Reads a character without echo; does not wait for carriage return; not
defined by Standard C, but a common extension.
The following program demonstrates the use of several I/O functions by creating a simple
dictionary. It asks the user to enter a word and then checks if the word exists in its list. If
found, it displays the meaning.
/* A simple dictionary. */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char word[80], ch;
char **p;
do {
puts("\nEnter word: ");
scanf("%s", word);
p = (char **)dic;
Dept of CSE
Programming in C Module - 2
puts(*(p+1));
break;
}
if(!strcmp(*p, word))
break;
p = p + 2; /* advance through the list */
} while(*p);
if(!*p)
puts("Word not in dictionary.");
printf("Another? (y/n): ");
scanf(" %c%*c", &ch);
} while(toupper(ch) != 'N');
return 0;
}
In C, the functions printf( ) and scanf( ) are used for formatted output and input. The printf( )
function writes data to the console, and scanf( ) reads data from the keyboard. Both can handle
different data types like integers, floating-point numbers, and strings.
printf( )
The control string in printf() has two parts. The first part is ordinary characters that are printed
directly. The second part contains format specifiers that decide how the given arguments will
be displayed.
For example:
displays:
Dept of CSE
Programming in C Module - 2
Code Format
%c Character.
%o Unsigned octal.
%s String of characters.
%p Displays a pointer.
%% Prints a % sign.
Dept of CSE
Programming in C Module - 2
Printing Characters
Printing Numbers
The %d or %i specifiers display signed integers in decimal format. The %u specifier is for
unsigned integers.
#include <stdio.h>
int main(void)
{
double f;
for(f=1.0; f<1.0e+10; f=f*10)
printf("%g ", f);
return 0;
}
Output:
Unsigned integers can also be displayed in octal (%o) or hexadecimal (%x or %X).
#include <stdio.h>
int main(void)
{
unsigned num;
for(num=0; num < 16; num++)
{
printf("%o ", num);
printf("%x ", num);
printf("%X\n", num);
}
return 0;
}
Output:
000
111
222
Dept of CSE
Programming in C Module - 2
333
444
555
666
777
10 8 8
11 9 9
12 a A
13 b B
14 c C
15 d D
16 e E
17 f F
Displaying an Address
#include <stdio.h>
int sample;
int main(void)
{
printf("%p", &sample);
return 0;
}
The %n Specifier
The %n specifier is different. It does not print anything but stores the number of
characters printed so far into a variable.
#include <stdio.h>
int main(void)
{
int count;
printf("this%n is a test\n", &count);
printf("%d", count);
Dept of CSE
Programming in C Module - 2
return 0;
}
Output:
this is a test 4
Format Modifiers
You can use modifiers with format specifiers to control output style. These include field
width, precision, justification, and type modifiers.
You can specify the minimum number of spaces a value should take. For example, %10f
prints a floating-point number in a field of at least 10 characters. Adding 0 before the number
pads with zeroes instead of spaces.
#include <stdio.h>
int main(void)
{
double item = 10.12304;
printf("%f\n", item);
printf("%10f\n", item);
printf("%012f\n", item);
return 0;
}
Output:
10.123040
10.123040
00010.123040
#include <stdio.h>
int main(void)
{
int i;
for(i=1; i<20; i++)
printf("%8d %8d %8d\n", i, i*i, i*i*i);
return 0;
}
Dept of CSE
Programming in C Module - 2
Output (sample):
111
248
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
11 121 1331
12 144 1728
13 169 2197
14 196 2744
15 225 3375
16 256 4096
17 289 4913
18 324 5832
19 361 6859
Precision Specifier
The precision specifier comes after the minimum field width specifier if there is one. It is
written as a period followed by a number. Its meaning changes depending on the type of data
used.
When used with floating-point numbers like %f, %e, or %E, it controls how many digits
Dept of CSE
Programming in C Module - 2
appear after the decimal point. For example, %10.4f prints a number with a total width of 10
characters and exactly 4 decimal places.
When used with %g or %G, it specifies how many significant digits will be displayed.
When used with strings, the precision specifier sets the maximum number of characters to
print. For example, %5.7s prints at least 5 characters but not more than 7. If the string is longer,
the extra characters are cut off.
When used with integers, it ensures a minimum number of digits. If the number has fewer
digits, zeros are added in the front.
#include <stdio.h>
int main(void)
{
printf("%.4f\n", 123.1234567);
printf("%3.8d\n", 1000);
printf("%10.15s\n", "This is a simple test.");
return 0;
}
Output:
123.1235
00001000
This is a simpl
Justifying Output
By default, all output in printf is right justified. This means if the field width is larger than the
data, the data will appear on the right side and spaces will fill the left.
You can make the output left justified by adding a minus sign after %. For example, %-
10.2f will left justify a floating-point number in a field of width 10 with two decimal places.
#include <stdio.h>
int main(void)
{
printf(" ........................ \n");
printf("right-justified: %8d\n", 100);
printf(" left-justified: %-8d\n", 100); return 0;
}
Dept of CSE
Programming in C Module - 2
Output:
.........................
right-justified: 100
left-justified: 100
There are also format modifiers for handling short and long integers. These modifiers can be
applied to d, i, o, u, and x specifiers. The l (ell) modifier tells printf that the value is a long
type. For example, %ld means a long int should be printed. The h modifier tells printf to print a
short integer. For example, %hu prints a short unsigned int.
The l and h modifiers can also be used with the %n specifier. In this case, they mean the
corresponding argument is a pointer to a long or short integer.
If the compiler supports wide characters, you can use l with %c to print a wide character, or
with %s to print a wide string.
The L modifier is used with e, f, or g specifiers to tell printf that the value is a long double.
C99 adds two more modifiers: hh and ll. The hh modifier can be used with d, i, o, u, x, or n. It
specifies that the value is a signed or unsigned char, or in case of %n, a pointer to a signed char.
The ll modifier also works with d, i, o, u, x, or n. It specifies that the value is a signed or
unsigned long long int, or a pointer to a long long int in case of %n.
C99 also allows the l modifier with a, e, f, and g, but in this case it has no effect.
The printf( ) function supports two extra modifiers for some format specifiers: * and #. The #
modifier forces certain symbols to appear in the output.
When used with %g, %G, %f, %E, or %e, it makes sure a decimal point is always displayed
even if there are no decimal digits. When used with %x or %X, the hexadecimal number is
printed with a 0x or 0X prefix. When used with %o, the number is printed with a leading zero.
The # modifier cannot be used with any other format specifiers. In C99, # can also be used
with %a so that a decimal point is displayed. The * modifier allows us to provide the minimum
field width and precision dynamically through arguments instead of constants.
When the format string is scanned, printf() will take the values for * from the arguments in
order.
Dept of CSE
Programming in C Module - 2
For example, if the minimum width is 10, the precision is 4, and the number is 123.3, it will be
displayed accordingly.
#include <stdio.h>
int main(void)
{
printf("%x %#x\n", 10, 10);
printf("%*.*f", 10, 4, 1234.34);
return 0;
}
scanf( )
The scanf( ) function is the general-purpose input function in C. It can read all built-in data
types and automatically convert the input into the proper internal format. It works like the
reverse of printf( ).
The function returns the number of data items successfully assigned to variables. If an error
occurs, it returns EOF. The control string decides how values are read into the variables given
in the argument [Link] control string can contain three types of characters :
Format specifiers
White-space characters
Non-white-space characters.
Dept of CSE
Programming in C Module - 2
Format Specifiers
Format specifiers start with a % symbol and tell scanf( ) what type of data to read. The format
specifiers are matched from left to right with the variables in the argument list.
Code Meaning
%s Reads a string.
%p Reads a pointer.
Inputting Numbers
To read a floating-point number in standard or scientific notation, you can use %e, %f, or %g.
In C99, %a can also be used to read a floating-point number.
You can also read integers in octal or hexadecimal form by using %o and %x. The %x format
can be written in either uppercase or lowercase, and when entering hexadecimal numbers, the
letters A to F can be typed in either case.
Dept of CSE
Programming in C Module - 2
The following program shows how octal and hexadecimal numbers can be read and printed:
#include <stdio.h>
int main(void)
{
int i, j;
scanf("%o%x", &i, &j);
printf("%o %x", i, j); return 0;
}
The scanf( ) function stops reading a number as soon as it encounters the first non- numeric
character.
For example, the following program reads an unsigned number and stores it in the variable
num:
#include <stdio.h>
int main(void)
{
unsigned num;
scanf("%u", &num);
printf("The unsigned number is %u", num);
return 0;
}
Individual characters can also be read using scanf() with the %c format [Link] %c is
used, scanf() reads characters exactly as they appear, including spaces, tabs, and newlines.
This is different from other format specifiers where spaces act as [Link] of line
buffering, %c may behave differently in interactive programs, but it still works well to read
characters one by one.
For example, in the input stream "x y", the following program will store 'x' in a, a space in b,
and 'y' in c:
Reading Strings
The scanf( ) function can read strings using the %s format specifier. It keeps reading characters
Dept of CSE
Programming in C Module - 2
until it finds a white-space character. The characters read are stored in a character array and the
string is automatically null terminated. In scanf( ), a white- space character can be a space, tab,
newline, vertical tab, or formfeed. Unlike gets( ), which reads until ENTER is pressed, scanf( )
stops at the first space. For this reason, you cannot use scanf( ) to read strings with spaces like
"this is a test".
Example:
#include <stdio.h>
int main(void)
{
char str[80];
printf("Enter a string: ");
scanf("%s", str);
printf("Here's your string: %s", str);
return 0;
}
If you enter "hello there", the output will only be "hello" because the space stops the reading.
Inputting an Address
To read a memory address, the %p format specifier is used. This makes scanf() read an
address in the format used by the computer’s CPU.
#include <stdio.h>
int main(void)
{
char *p;
printf("Enter an address: ");
scanf("%p", &p);
printf("Value at location %p is %c\n", p, *p);
return 0;
}
This program inputs an address and then shows the value stored at that memory location.
The %n Specifier
The %n specifier tells scanf() to store the number of characters read so far into an integer
variable. The value is stored in the variable whose address is passed in the argument list.
Using a Scanset
A scanset allows scanf( ) to read only specific characters. The scanset is written inside square
brackets [ ] after a %. For example, %[XYZ] tells scanf( ) to accept only X, Y, or Z. Input
continues until a character outside the set is found.
Dept of CSE
Programming in C Module - 2
Example:
#include <stdio.h>
int main(void)
{
int i;
char str[80], str2[80];
scanf("%d%[abcdefg]%s", &i, str, str2);
printf("%d %s %s", i, str, str2);
return 0;
}
If you enter 123abcdtye, the output will be 123 abcd tye. The scanset %[abcdefg] accepts abcd,
then stops at t since it is not in the set. The remaining tye is stored in str2.
You can also create inverted scansets by starting with ^. For example, %[^0-9] reads
everything except digits. Ranges like [A-Z] can be used to read all uppercase letters.
Remember that scansets are case sensitive, so [A-Z] and [a-z] are different.
In the control string of scanf(), a white-space character makes it skip any number of white
spaces in the input. This means spaces, tabs, or newlines are ignored until a non-white-space
character is found.
Non-white-space characters in the control string must match the input exactly. For example,
"%d,%d" makes scanf() read an integer, skip over a comma, and then read another integer. If
the comma is missing, scanf() will stop. To read a literal % character, use %%.
All variables in scanf() must be passed by their addresses because the function needs to modify
their values directly. For example:
scanf("%d", &count);
Here &count gives the address of count. For strings, the array name itself is the address of the
first element, so you don’t use &:
scanf("%s", str);
Format Modifiers
Like printf( ), scanf( ) supports modifiers for format specifiers.A maximum field length can be
given to limit how many characters are read. For example:
Dept of CSE
Programming in C Module - 2
scanf("%20s", str);
This reads at most 20 characters into str. If the input is longer, the rest stays in the input buffer
for the next scanf( ) call. For example, entering "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
will only store the first 20 letters in str. Another call to scanf( ) will then read the remaining
"UVWXYZ".
To read long and short integers, use l and h modifiers. For example, %ld reads a long integer
and %hd reads a short integer. For floating-point numbers, %f normally stores data in a float.
Adding l makes it a double and L makes it a long double.C99 also adds hh and ll. The hh
modifier is used for char, and ll is used for long long int.
Suppressing Input
You can tell scanf() to skip a field without storing it by placing * before the format specifier.
For example:
If you enter 10,10, the comma will be read but ignored, and the two integers will be stored in x
and y. This is useful when you only need specific parts of the input.
To read long and short integers, use l and h modifiers. For example, %ld reads a long integer
and %hd reads a short integer. For floating-point numbers, %f normally stores data in a float.
Adding l makes it a double and L makes it a long double.C99 also adds hh and ll. The hh
modifier is used for char, and ll is used for long long int.
STATEMENTS
A statement is a part of a program that performs an action. C statements are divided into:
Selection
Iteration
Jump
Label
Expression
Block
Selection statements include if and switch. Iteration statements include while, for, and do-
while, which are also called loops. Jump statements are break, continue, goto, and return.
Label statements include case, default, and the label used with goto. Expression statements are
made of valid expressions. Block statements are groups of statements enclosed within { and }.
In C, true and false values are important for decision making. Any nonzero value, including
Dept of CSE
Programming in C Module - 2
negative numbers, is considered true. Zero is considered false. This rule helps in writing
simple and efficient conditional checks.
if
(expression) statement;
else statement;
If the expression is true (nonzero), the statement under if executes. If it is false, the statement
under else executes. Only one of the two will run.
The condition inside an if must give a scalar result like an integer, character, pointer, or
floating-point [Link] floating-point values is rare because it slows execution compared to
integers or characters. The following program shows a simple "guess the magic number" game
using rand( ).
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int magic; /* magic number */
int guess; /* user's guess */
magic = rand(); /* generate the magic number */
printf("Guess the magic number: ");
scanf("%d", &guess);
if(guess == magic)
printf("** Right **");
return 0;
}
The else part can be added to give feedback when the guess is wrong.
#include <stdio.h>
#include <stdlib.h>
int main(void)
Dept of CSE
Programming in C Module - 2
{
int magic; /* magic number */
int guess; /* user's guess */
magic = rand(); /* generate the magic number */
printf("Guess the magic number: ");
scanf("%d", &guess);
if(guess == magic)
printf("** Right **");
else
printf("Wrong");
return 0;
Nested ifs
Nested if statements are when one if is inside another. An else always matches with the
nearest if in the same block. This helps to check multiple conditions step by step.
if(i)
{
if(j) dosomething1();
if(k) dosomething2(); /* this if */
else dosomething3(); /* is associated with this else */
}
else
dosomething4(); /* associated with if(i) */
Using nested ifs, the magic number program can be improved to give hints if the guess is
too high or too low.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
Dept of CSE
Programming in C Module - 2
{
printf("Wrong, ");
if(guess > magic)
printf("too high\n"); /* nested if */
else
printf("too low\n");
}
return 0;
}
It is a common way to check multiple conditions in sequence. It is also called the staircase
because of how it looks in code. Its general form is:
else statement;
The conditions are checked from top to bottom. As soon as one condition is true, its statement
runs, and the rest are skipped. If none are true, the final else runs. If the final else is missing,
nothing happens when all conditions are false.
Although deeply indented ladders are valid, they can be hard to read. So, they are usually
written in a simpler style like this:
if (expression) statement;
else if (expression)
statement;
else if (expression)
statement;
else statement;
Dept of CSE
Programming in C Module - 2
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int magic; /* magic number */
int guess; /* user's guess */
magic = rand(); /* generate the magic number */
printf("Guess the magic number: ");
scanf("%d", &guess);
if(guess == magic)
{
printf("** Right ** ");
printf("%d is the magic number", magic);
}
else if(guess > magic)
printf("Wrong, too high");
else
printf("Wrong, too low"); r
eturn 0;
}
The ? Alternative
You can use the ? operator to replace if-else statements of the general form:
if (condition)
var = expression;
else
var = expression;
The ? is called a ternary operator because it requires three operands. It takes the general
form
Here, Exp1 is checked first. If Exp1 is true, Exp2 becomes the result. If Exp1 is false, Exp3
becomes the result.
For example:
x = 10;
y = x > 9 ? 100 : 200;
Dept of CSE
Programming in C Module - 2
In this case, y becomes 100 because x > 9 is true. The same code using if-else would be:
x = 10;
if(x > 9)
y = 100;
else
y = 200;
The following program uses the ? operator to square an integer, but it keeps the sign:
#include <stdio.h>
int main(void)
{
int isqrd, i;
printf("Enter a number: ");
scanf("%d", &i);
isqrd = i>0 ? i*i : -(i*i);
printf("%d squared is %d", i, isqrd);
return 0;
}
The ? operator can also be used with function calls since functions return values. For example:
#include <stdio.h>
int f1(int n);
int f2(void);
int main(void)
{
int t;
int f1(int n)
{
printf("%d ", n); return 0;
}
int f2(void)
{
printf("entered "); return 0;
}
Dept of CSE
Programming in C Module - 2
In this program, if the input is 0, only printf( ) runs and prints "zero entered." If the input is any
other number, both f1( ) and f2( ) execute. Note that the value of the expression is not assigned
anywhere—it is just used to trigger the function calls.
Sometimes the compiler may change the order of evaluation to optimize performance, so
functions inside the ? operator may not always run in the expected sequence.
Finally, using the ? operator, the magic number program can be written again as:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int magic;
int guess;
magic = rand(); /* generate the magic number */
printf("Guess the magic number: ");
scanf("%d", &guess);
if(guess == magic)
{
printf("** Right ** ");
printf("%d is the magic number", magic);
}
else
guess > magic ? printf("High") : printf("Low");
return 0;
}
Here, the ? operator prints "High" or "Low" based on whether the guess is greater or smaller
than the magic number.
In C, you can use any valid expression to control an if or ? operator. Unlike some other
languages, you are not restricted to only relational or logical expressions. The expression just
needs to evaluate to true (nonzero) or false (zero).
For example, the following program reads two numbers and divides them. It checks if the
second number is not zero to avoid divide-by-zero error.
Dept of CSE
Programming in C Module - 2
int a, b;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
if(b) printf("%d\n", a/b);
else printf("Cannot divide by zero.\n");
return 0;
}
This works because if b is 0, the condition is false, and else executes. If b is not zero, the
condition is true, and division happens.
Writing if(b != 0) is unnecessary here. Just writing if(b) is enough and is considered better
style.
switch Statement
C provides the switch statement for multiple-branch selection. It tests an expression against a
list of integer or character constants. When a match is found, the corresponding statements
execute.
constant1:
case constant2:
...
default:
statement sequence
The expression must evaluate to an integer type. You can use int or char, but not float. If no
case matches, the default (if present) executes.
C89 requires at least 257 cases, and C99 requires at least 1,023 cases. In practice, you use fewer
for efficiency.
The break statement ends the current case. If break is missing, execution “falls through”
into the next case.
Dept of CSE
Programming in C Module - 2
void menu(void)
{
char ch;
printf("1. Check Spelling\n");
printf("2. Correct Spelling Errors\n");
printf("3. Display Spelling Errors\n");
printf("Strike Any Other Key to Skip\n");
printf(" Enter your choice: ");
ch = getchar(); /* read the selection */
switch(ch) {
case '1':
check_spelling();
break;
case '2':
correct_errors();
break;
case '3':
display_errors();
break;
default:
printf("No option selected");
}
}
If break is omitted, execution continues to the next case. This is called “fall through.”
/* Process a value */
void inp_handler(int i)
{
int flag; flag = -1;
switch(i)
{
case 1:
case 2:
case 3:
flag = 0; break;
case 4:
flag = 1;
case 5:
error(flag); break;
default:
process(i);
}
}
Dept of CSE
Programming in C Module - 2
Here, cases 1–3 share the same statements. If i = 4, flag is set to 1, but since there is no break,
execution continues to case 5 and calls error(flag).
Nested switches are also allowed, even with overlapping case constants.
switch(x) {
case 1:
switch(y) {
case 0: printf("Divide by zero error.\n"); break;
case 1: process(x, y); break;
}
break;
case 2:
...
}
Iteration Statements
Loops allow repeating a set of instructions until a condition is met. C provides for, while,
and do-while loops.
Initialization sets the loop variable, condition checks whether the loop continues, and increment
updates the variable.
Example:
#include <stdio.h>
int main(void)
{
int x;
for(x=1; x <= 100; x++)
printf("%d ", x);
return 0;
}
Here x starts at 1, increments by 1 each time, and stops when x > 100. Another example with
decreasing values:
for(x=100; x != 65; x -= 5)
{
z = x*x;
Dept of CSE
Programming in C Module - 2
If the condition is false at the start, the loop body does not run. x = 10;
for(y=10; y != x; ++y)
printf("%d", y);
printf("%d", y);
This will only print 10 once, since the loop never runs.
You can control loops with multiple variables using the comma operator.
#include <stdio.h>
#include <string.h>
This program copies characters from both ends of a string and converges in the middle.
Dept of CSE
Programming in C Module - 2
The condition in a for loop can be more complex, like allowing multiple exit
conditions:
void sign_on(void)
{
char str[20]; int x;
for(x=0; x<3 && strcmp(str, "password"); ++x)
{
printf("Enter password please:");
gets(str);
}
if(x == 3) return;
/* else log user in */
}
This function uses strcmp( ), the standard library function that compares two strings and
returns 0 if they match.
#include <stdio.h>
int sqrnum(int num);
int readnum(void);
int prompt(void);
int main(void)
{
int t;
for(prompt(); t=readnum();
prompt())
sqrnum(t);
return 0;
}
Dept of CSE
Programming in C Module - 2
Infinite Loops
for( ; ; )
ch = '\0';
for( ; ; )
{
ch = getchar();
if(ch == 'A') break;
}
printf("you typed an A");
In C99 and C++, you can declare variables inside the for initialization.
int j;
for(int i = 0; i<10; i++)
j = i * i;
Here i is local to the loop and not known outside.
while(condition) statement;
Example:
Dept of CSE
Programming in C Module - 2
char wait_for_char(void)
{
char ch;
ch = '\0';
while(ch != 'A')
ch = getchar();
return ch;
}
#include <stdio.h>
#include <string.h>
Dept of CSE
Programming in C Module - 2
while((ch=getchar()) != 'A');
General form:
do {
statement;
} while(condition);
Unlike while, do-while checks the condition at the bottom. It always executes at least [Link]
following do while will read numbers from the keyboard until it finds a number less than or
equal to 100.
do {
scanf("%d", &num);
} while(num > 100);
void menu(void)
{
char ch;
printf("1. Check Spelling\n");
printf("2. Correct Spelling Errors\n");
printf("3. Display Spelling Errors\n");
printf(" Enter your choice: ");
do {
ch = getchar();
switch(ch) {
case '1': check_spelling();
break;
case '2':
correct_errors();
break;
case '3':
display_errors();
break;
}
} while(ch!='1' && ch!='2' && ch!='3');
}
Dept of CSE
Programming in C Module - 2
Jump Statements
C provides four jump statements: return, goto, break, and [Link] and goto can be used
anywhere in a [Link] and continue are used with loops, and break is also used with
switch.
The return statement is used to exit from a function and go back to the place where the
function was [Link] is called a jump statement because it jumps control back to the calling
point.A return statement may or may not return a value. If the function is non-void, then return
must give back a value. If the function is void, return should not return any value.
In C89, a non-void function could return nothing, which resulted in garbage values. But in C99
(and C++), a non-void function must return a [Link] general form of return is:
return expression;
If the function has a return type, the expression value is returned.A function can have multiple
return statements, but execution stops at the first one encountered.A void function cannot use
return with a value.
The goto statement is rarely used because it can make programs confusing. But sometimes, it
is helpful for jumping out of deeply nested [Link] requires a label, which is an identifier
followed by a colon. goto and its label must be in the same [Link] general form is:
goto label;
.
.
.
label:
x = 1;
loop1:
x++;
if(x <= 100)
goto loop1;
Dept of CSE
Programming in C Module - 2
The break statement is used to stop execution immediately in loops or in a switch- [Link]
break is inside a loop, the loop ends immediately, and control moves to the statement after the
loop.
Example:
#include <stdio.h>
int main (void)
{
int t;
for(t=0; t < 100; t++)
{
printf("%d ", t);
if(t == 10)
break;
}
return 0;
}
This program prints 0 to 10 and then stops because break forces the loop to exit. break is often
used when a special condition is met. Example:
Here, kbhit() checks if a key is pressed. If true, break stops the loop.A break only exits the
innermost loop, not outer ones. Example:
This prints numbers 1 to 9, repeated 100 times. In switch, break only affects that switch,
Dept of CSE
Programming in C Module - 2
The exit( ) function is not a control statement but ends the whole program
immediately and returns control to the operating [Link] form:
Here, return_code is sent back to the OS. Usually, 0 means success, while other values
mean [Link] must include <stdlib.h> to use exit().
Example:
#include <stdlib.h>
int main(void)
{
if(!virtual_graphics())
exit(1);
play();
/* ... */
}
void menu(void)
{
char ch;
printf("1. Check Spelling\n");
printf("2. Correct Spelling Errors\n");
printf("3. Display Spelling Errors\n");
printf("4. Quit\n");
printf("Enter your choice: ");
do {
ch = getchar(); switch(ch)
{
case '1': check_spelling(); break;
case '2': correct_errors(); break;
case '3': display_errors(); break;
case '4': exit(0); /* quit program */
}
} while(ch!='1' && ch!='2' && ch!='3');
}
The continue statement skips the remaining part of the loop and forces the next [Link] a
Dept of CSE
Programming in C Module - 2
for loop, continue moves control to the increment and condition check. In while and do-while,
it moves directly to the condition test.
Example:
/* Count spaces */
#include<stdio.h>
int main(void)
{
char s[80], *str;
int space;
printf("Enter a string: ");
gets(s);
str = s;
for(space=0; *str; str++)
{
if(*str != ' ')
continue;
space++;
}
printf("%d spaces\n", space);
return 0;
}
This counts spaces in a string. continue skips when the character is not a space. Another
example:
void code(void)
{
char done, ch; done = 0;
while(!done)
{
ch = getchar();
if(ch == '$') {
done = 1;
continue;
}
putchar(ch+1);
}
}
Here, every character is shifted one step forward (A→B, B→C). The loop ends when
$ is entered.
Expression Statements
Examples:
Dept of CSE
Programming in C Module - 2
Even if a statement looks strange, it is still executed. An empty statement does nothing
but is allowed.
Block Statements
A block is a group of statements enclosed within { }. Blocks are often used when multiple
statements must be grouped together, such as inside if or loops. Here, the block is used
independently. Blocks are also called compound statements.
Example:
#include <stdio.h>
int main(void)
{
int i;
{ /* free-standing block */
i = 120;
printf("%d", i);
}
return 0;
}
An array is a collection of variables of the same type that are stored together and referred to by
a common name. Each element in an array is accessed by its index. In C, arrays are stored in
continuous memory locations. The lowest address is for the first element, and the highest
address is for the last element.
Arrays can be single-dimensional or multi-dimensional. The most common array is the string,
which is a character array ending with a null (\0). Arrays and pointers are closely related. You
will understand them fully by studying both topics.
Single-Dimension Arrays
type var_name[size];
Arrays must be declared before use so that memory can be allocated. Here, type is the base
type of each element and size is the number of elements.
Example:
double balance[100];
Dept of CSE
Programming in C Module - 2
This declares an array named balance that can store 100 double [Link] C89, the size of an
array must be fixed at compile time using a constant. In C99, the size can be given at run
[Link] access an element, we use indexing:
balance[3] = 12.23;
This stores 12.23 in the 4th element (index 3). All arrays in C start with index 0. For example:
char p[10];
program:
#include <stdio.h>
int main(void)
{
int x[100]; /* this declares a 100-integer array */
int t;
/* load x with values 0 through 99 */
for(t=0; t<100; ++t)
x[t] = t;
/* display contents of x */
for(t=0; t<100; ++t)
printf("%d ", x[t]);
return 0;
}
C does not check array bounds. If you access outside the array range, you may overwrite
other variables or even program code.
int count[10], i;
Example:
char a[7];
Dept of CSE
Programming in C Module - 2
If this starts at location 1000, then a[0] is at 1000, a[1] at 1001, and so on up to a[6] at 1006.
The name of the array itself gives the address of its first element. Example:
int *p;
int sample[10];
p = sample;
Both sample and &sample[0] give the same address, but in practice you usually write sample.
In C, you cannot pass the entire array directly to a function. But you can pass a pointer to the
array by writing only the array name.
Example:
int main(void)
{
int i[10];
func1(i);
/* ... */
}
Inside the function, you can declare the parameter in three ways: As a
pointer:
As a sized array:
As an unsized array:
Dept of CSE
Programming in C Module - 2
/* ... */
All three are the same because they mean the function is receiving a pointer to an [Link] size
in the parameter list does not matter because C does not do bounds checking.
/* ... */
Dept of CSE