Module2 Notes 2
Module2 Notes 2
VT
U
AD
Module-2
D
A
Introduction to I/O in C
• C does not have built-in keywords for input/output (I/O) like some
other languages.
VT
U
• Instead, I/O is done using library functions that are defined in the
AD
header file:
D
A
#include <stdio.h>
• The I/O system in C allows data transfer between the program
and devices such as the keyboard, screen, or files.
Types of I/O in C
• Console I/O
VT
• Deals with input from the keyboard and output to the screen.
U
AD
• Example functions: getchar(), putchar(), scanf(), printf()
D
A
• File I/O
• Deals with reading and writing files (covered in another chapter).
Character I/O Functions
The simplest console I/O functions are:
1. getchar()
• Reads one character from the keyboard.
• Waits until a key is pressed and returns that character.
VT
• Automatically echoes (displays) the pressed key.
U
Prototype:
AD
int getchar(void);
D
• Returns EOF (-1) if an error occurs.
A
Example:
char ch;
ch = getchar();
putchar()
• Writes one character to the screen.
Prototype:
int putchar(int c);
VT
• Returns the printed character, or EOF if an error occurs.
U
• Example:
AD
• putchar('A');
D
A
Example Program: Reverse the Case of Characters
#include <stdio.h>
#include <ctype.h>
OUTPUT:
Enter some text (type a period to quit).
int main(void) {
HeeLLo
char ch;
printf("Enter some text (type a period to quit).\n");
hEEllO
VT
do {
U
ch = getchar();
AD
if (islower(ch))
D
ch = toupper(ch);
A
else Explanation:
ch = tolower(ch); • Reads one character at a time from the keyboard.
putchar(ch); • Converts lowercase → uppercase and uppercase → lowercase.
• Stops when the user types a period (.).
} while (ch != '.');
return 0;
}
Problem with getchar()
VT
• So even if you press a key, the program waits for ENTER before
U
processing.
AD
• This behavior is not suitable for interactive programs (like games or
D
real-time input).
A
Alternatives to getchar()
C standard does not provide a truly interactive input function,
but many compilers include extra functions like:
1. getch()
• Reads a character immediately (no need to press ENTER).
• Does not echo the character to the screen.
VT
Prototype:
U
int getch(void);
AD
2. getche()
D
• Same as getch() but echoes the character on the screen.
A
• Prototype:
• int getche(void);
Both are found in <conio.h> (compiler-specific header).
Example using getch()
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
int main(void) {
char ch;
VT
printf("Enter some text (type a period to quit).\n");
U
do {
AD
ch = getch(); // reads without waiting for ENTER
if (islower(ch))
D
A
ch = toupper(ch);
else Explanation:
ch = tolower(ch); •Input is immediate, not line-buffered.
putchar(ch); •The program reacts as soon as a key is pressed.
•Output appears instantly with reversed case.
} while (ch != '.');
return 0;
}
Reading and Writing Strings
• A string is a group of characters (like words or sentences) stored in a
character array.
char name[20] = “Oxford";
Here, " Oxford " is a string, and it ends with a null character ('\0’).
gets( ) Function – Reading a String
VT
• Used to read a line of text (string) from the keyboard.
U
• Reads characters until ENTER is pressed.
AD
• The ENTER (carriage return) is not stored; instead, it adds a null
D
A
character '\0' at the end. Syntax:
char *gets(char *str);
Example: • gets(str) reads a whole line of text from the keyboard (until you press
char str[100]; Enter).
• It writes that line into the array whose address you gave as str.
gets(str); • It adds a terminating '\0' (null character) at the end so you can use the
buffer as a C string.
• It returns the same pointer str on success, or NULL if an error occurs.
Important:
• gets() does not check array limits, so if the user types too many
characters, it can cause overflow.
VT
• Because of this, gets() is unsafe and not recommended in new
U
programs.
AD
• Safe Alternative:
D
• Use fgets() instead of gets().
A
2. puts( ) Function – Writing a String
VT
• It is simpler and faster than printf() when only strings are printed.
U
AD
Example:
D
puts("Hello World");
A
Syntax:
VT
getche() Reads one character with echo No ENTER needed (not standard C)
U
AD
getch() Reads one character without echo No ENTER needed (not standard C)
D
A
gets() Reads a string from keyboard Unsafe, no limit check
What It Means:
• Formatted I/O means controlling the way data is displayed or read —
VT
for example:
U
• How many decimal places to show
AD
• How much space to leave
D
A
• Whether to show signs, etc.
printf( ) – Formatted Output
Prototype:
int printf(const char *control_string, ...);
• control_string → contains text + format specifiers
• returns → number of characters printed (or negative if error)
VT
U
How It Works:
AD
printf("I like %c %s", 'C', "programming!");
D
Output:
A
I like C programming!
• Here,
• %c → prints a character 'C'
• %s → prints a string "programming!"
Common Format Specifiers
Specifier Meaning
%c Character
%d or %i Signed integer
%u Unsigned integer
VT
%f Floating-point number
U
AD
%e / %E Scientific notation
D
%g / %G Automatically chooses shorter format
A
%o Octal number
%s String
%p Address (pointer)
VT
argument to be output, unmodified, to the screen.
U
AD
D
• To print a string, use “%s”.
A
Printing Numbers Examples
printf("%d", 25); // prints 25
printf("%f", 12.34); // prints 12.340000
VT
printf("%x", 15); // prints f (hexadecimal)
U
AD
printf("%o", 15); // prints 17 (octal)
D
A
Printing Numbers
Printing Integers
• You can print integer (whole number) values using:
%d or %i
Example:
int a = 25;
printf("%d", a);
VT
Output: 25
Both %d and %i display signed integers in decimal format (can be positive or negative).
U
AD
Unsigned Integers
D
• To display only positive numbers (unsigned):
A
%u
Example:
unsigned int b = 300;
printf("%u", b);
• Output: 300
Printing Floating-Point Numbers
• To print decimal (real) numbers:
VT
%f Normal decimal format 12.340000
U
AD
D
1.234000e+01 or
A
%e or %E Scientific notation
1.234000E+01
VT
e±yy → exponent (power of 10)
U
Uppercase ‘E’
AD
• Use %E to show capital E:
D
• printf("%E", num);
A
Output: 1.234567E+06
Using %g
• %g automatically decides whether to use %f or %e, depending on which is
shorter.
Example program:
#include <stdio.h>
int main(void)
{
double f;
for(f = 1.0; f < 1.0e10; f = f * 10)
VT
printf("%g ", f);
U
return 0;
AD
}
D
A
OUTPUT :
VT
666
U
for(num = 0; num <1 6; num++) {
777
AD
printf("%o ", num); // octal
printf("%x ", num); // hexadecimal (lowercase) 10 8 8
D
printf("%X\n", num); // hexadecimal (uppercase) 11 9 9
A
}
12 a A
return 0; 13 b B
} 14 c C
15 d D
16 e E
17 f F
Displaying an Address
If you want to display an address, use “%p”.
This format specifier causes printf( ) to display a machine address in a
format compatible with the type of addressing used by the computer.
VT
#include <stdio.h>
Explanation:
U
int sample; // global variable
•&sample → The ampersand (&) symbol gives the memory
AD
int main(void) address of the variable sample.
•%p → This format specifier in printf() is used to display an
D
{
A
printf("%p", &sample); address (pointer) in a format your computer understands.
return 0; •printf("%p", &sample);
} → Prints the address where the variable sample is stored in
memory.
Sample Output:
0x7ffee0b7a8c4
%n Format Specifier in C
What it Does
• %n is different from other format specifiers like %d, %f, or %s.
• It does not print anything on the screen.
• Instead, it stores the number of characters printed so far into a
VT
variable.
U
AD
How It Works
D
• The argument for %n must be a pointer to an integer.
A
• When printf() runs, it counts how many characters it has printed up
to the point where %n appears.
• That count is stored in the integer variable provided.
Example Program
#include <stdio.h>
int main(void)
{
int count; // variable to store the
number of characters printed
VT
U
return 0;
AD
} Explanation
• "this%n is a test\n" → When printf() reaches
D
%n, 4 characters ("t", "h", "i", "s") have been printed.
A
• %n stores 4 in the variable count.
• The next line printf("%d", count); prints the value
of count, which is 4.
Output
this is a test
4
Format Modifiers in printf()
What are Format Modifiers?
• Format modifiers are extra instructions that you can add between %
and the format code (like %d, %f, %s, etc.).
VT
• They control how output is displayed, such as:
U
• Field width
AD
• Number of decimal places
D
• Left or right justification
A
• Zero-padding
1. Minimum Field Width Specifier
Definition:
• A number placed between % and the format code sets the minimum
VT
field width (number of characters that the output should occupy).
U
• If the actual number or string is shorter than this width, it will be
AD
padded with spaces (by default).
D
• If the value is longer, it will be printed fully (not truncated).
A
Example Program
#include <stdio.h>
int main(void)
{
double item; item = 11.12304;
printf("%f\n", item); // Normal output
printf("%12f\n", item); // Minimum field width = 12
VT
printf("%013f\n", item); // Minimum field width = 13, padded with zeros
U
return 0;
AD
}
D
A
11.123040
11.123040
000011.123040
The minimum field width modifier is most commonly used to produce tables in which the columns line up.
For example, the next program produces a table of squares and cubes for the numbers between 1 and 5:
#include <stdio.h>
int main(void)
{
VT
int i; Output
/* display a table of squares and cubes */ 1 1 1
U
for(i = 1; i < 5; i++) 2 4 8
AD
printf("%8d %8d %8d\n", i, i*i, i*i*i); 3 9 27
4 16 64
D
return 0;
A
}
Precision Specifier in printf()
Definition
• The precision specifier controls how many digits, decimal places, or
VT
characters are printed in the output.
U
• It is written as:
AD
• %[field width].[precision]specifier
D
A
General Format
• A period (.) followed by a number indicates precision.
• Example:
%10.4f → Minimum width 10, 4 digits after the decimal point.
Usage Based on Data Type
Data Type Effect of Precision Example Output Explanation
VT
U
Controls number of
%g or %G %.3g
AD
Prints 3 significant digits
significant digits
D
A
Controls maximum Prints at most 5
String (%s) %10.5s
characters printed characters
Controls minimum
Adds zeros to make total
Integer (%d, %i) number of digits (adds %.6d
6 digits
leading zeros)
Example Program
123.1235
00001000
This is a simpl
#include <stdio.h>
int main(void)
{
VT
printf("%.4f\n", 123.1234567);
U
printf("%3.8d\n", 1000);
AD
printf("%10.15s\n", "This is a simple test.");
D
return 0;
A
}
Justifying Output in C
Default Justification
• By default, C output using printf() is right-justified.
➜ This means the printed value appears on the right side of the field
VT
U
if the field width is larger than the value.
AD
D
A
Left Justification
• You can make the output left-justified by adding a minus sign (-) right
after the % symbol in the format specifier.
➜ Example: %-10d (left-justified integer in a 10-character field)
Example Program
Output
#include <stdio.h> .........................
right-justified: 100
int main(void) left-justified: 100
{
printf(".........................\n");
VT
printf("right-justified: %8d\n", 100);
printf(" left-justified: %-8d\n", 100);
U
AD
return 0;
}
D
A
Handling Other Data Types in printf()
VT
special format modifiers to tell printf() what kind of data it’s
U
printing.
AD
• These modifiers go between % and the format specifier (d, f, x, etc.).
D
A
Common Format Modifiers
Modifier Used With Meaning / Data Type Example Description
h d, i, o, u, x short int / short unsigned int %hd, %hu Used for short integers
l (small L) d, i, o, u, x long int / long unsigned int %ld, %lu Used for long integers
VT
U
Used for long double (higher
AD
L (capital L) f, e, g long double %Lf
precision float)
D
A
For very small integers (char
hh (C99) d, i, o, u, x signed/unsigned char %hhd, %hhu
values)
VT
Adds 0x before a
%#x hexadecimal printf("%#x", 10); 0xa
U
number
AD
D
Adds 0 before an
%#o printf("%#o", 10); 012
A
octal number
Makes sure a
%#f decimal point is printf("%#f", 10.0); 10.
always shown
VT
• Width = 10
U
AD
• Decimal places = 4
•
D
With *:
A
• printf("%*.*f", 10, 4, 123.45);
• The first * → width (10)
• The second * → decimal places (4)
Example Program
#include <stdio.h>
int main(void) {
printf("%x %#x\n", 10, 10);
printf("%*.*f", 10, 4, 1234.34);
VT
return 0;
U
AD
}
D
A
Output:
a 0xa
1234.3400
VT
U
C Formatted Console Input — scanf()
AD
D
A
Definition
scanf() reads input from the keyboard and stores it in variables.
It is the reverse of printf().
Prototype
int scanf(const char *control_string, ...);
VT
Key Points
•Reads all built-in data types.
U
•Returns number of inputs successfully read.
AD
•Returns EOF (-1) if an error occurs.
D
•Needs addresses (&variable) except for strings.
A
The control string consists of three classifications of characters:
• Format specifiers
• White-space characters
• Non-white-space character
1. Format Specifiers
Code Meaning Example Input Example Code
VT
%o Reads octal number 075 scanf("%o", &num);
U
AD
%x Reads hexadecimal number 0xFF scanf("%x", &num);
D
%c A scanf("%c", &ch);
A
Reads single character
VT
Reading Floating-Point Numbers: scanf("%x", &hex);
• Use %f, %e, or %g → Reads floating-point numbers. printf("Octal to Decimal: %d\n", oct);
U
printf("Hex to Decimal: %d\n", hex);
AD
• %a (C99) → Hexadecimal floating-point form. return 0;
}
D
A
Reading Numbers in Other Bases: Note: scanf() stops reading when a non-numeric character
• %o → Octal (base 8) is found.
VT
char str[80];
scanf("%u", &num);
U
printf("Enter a string: ");
AD
scanf("%s", str);
Reading Individual Characters (using scanf):
D
printf("Here's your string: %s", str);
A
• Use %c to read characters.
• scanf() treats spaces, tabs, and newlines as normal characters. Note: Input 'hello there' → Output will be only 'hello'.
Example: Because scanf() stops at the first space.
scanf("%c%c%c", &a, &b, &c);
Input: x y → a='x', b=' ', c='y'
Inputting an Address:
• To input a memory address, use the %p format specifier.
• %p reads an address in the format defined by the computer’s CPU architecture.
Example Program:
Note:
#include <stdio.h> • The program reads a memory address and prints the value
int main(void) { stored at that address.
• %p is used for both input (scanf) and output (printf) of pointer
VT
char *p; addresses.
U
printf("Enter an address: "); • Be careful: accessing random memory addresses can cause
AD
errors or crashes.
scanf("%p", &p);
D
printf("Value at location %p is %c\n", p, *p);
A
return 0;
}
VT
→ 'count' will hold how many characters were read before
return 0;
U
%n.
AD
}
Using a Scanset:
Input: 123abcdtye → Output: 123 abcd tye
D
• A scanset defines a set of characters for scanf() to accept.
A
• 'abcd' fits scanset [abcdefg], 't' ends it, remaining go to str2.
• Syntax: %[characters]
Notes:
Example: %[XYZ] → reads only X, Y, or Z.
• Use ^ for inverted scanset → %[^] reads until newline.
• Stops reading when a character not in the set is
• %[A-Z] accepts uppercase A–Z.
encountered.
• Scanset is case-sensitive; specify both cases if needed.
2. white-space character (Discarding Unwanted White
Space)
• A white-space character in the control string causes scanf( ) to skip
over one or more leading whitespace characters in the input stream.
A white-space character is either
• a space How It Works
VT
•When scanf() sees a space (or any white-space) in the
• a tab
U
format string:
AD
→ It reads and ignores all white-space characters in the input
• vertical tab until it finds a non-white-space character.
D
• formfeed, or
A
Example:
• a newline. scanf("%d %d", &a, &b);
Any number of spaces, tabs, or newlines between two
numbers will be skipped automatically.
Input:
10 20 or 10↵20
Both work the same!
[Link]-White-Space Characters & Passing Addresses in
scanf()
1️⃣ Non-White-Space Characters
• If a non-white-space character (like ,, /, -, etc.) appears in the control
string, scanf() expects to find that exact same character in the input.
VT
U
AD
• Example:
• scanf("%d,%d", &a, &b);
D
A
• Input must be like: 10,20
Wrong input: 10 20 → will cause scanf() to stop.
• The comma , in the format string tells scanf() to read and discard
it from input.
2️⃣ Reading a Percent Sign
• To match and discard a % in input, use %% in the format string.
Example:
• scanf("%%d", &x); // expects input like %10
• Examples:
VT
int count;
U
scanf("%d", &count); // Correct
AD
Why use &?
D
Because scanf() needs to store the input value inside your variable.
A
Exception: Strings
• For strings, do not use & — the array name already represents its address.
• char str[20];
• scanf("%s", str); // Correct
Format Modifiers in scanf()
1️⃣ What are Format Modifiers?
• Format modifiers change how scanf() reads input — they limit size, or specify data type.
Used between % and the format specifier.
• Example:
• scanf("%20s", str);
VT
Reads maximum 20 characters into str.
If more characters are typed, they remain in the input buffer for the next scanf() call.
U
AD
2️⃣ Field Width
D
• Controls the maximum number of characters read.
A
• Input stops at whitespace or when the limit is reached.
• Example:
• Input: ABCDEFGHIJKLMNOPQRSTUVWXYZ
• scanf("%20s", str);
Stores: ABCDEFGHIJKLMNOPQRST
Remaining (UVWXYZ) stay in buffer for next scanf().
3️⃣ Integer Modifiers 4️⃣ Floating-Point Modifiers
VT
ll long long int %lld
U
AD
5️⃣ Wide Character Modifiers
D
A
•Used for Unicode (wide characters):
• %lc → wide char (wchar_t)
• %ls → wide string (wchar_t[])
Suppressing Input in scanf()
What It Means
• scanf() normally reads and stores input values into variables.
• But sometimes, we may want to read and ignore certain parts of
VT
input (like symbols, commas, or spaces).
U
• To do this, we use * (asterisk) right after %.
AD
D
Syntax:
A
• scanf("%*<specifier>");
• The * tells scanf() not to store that value in any variable.
Example:
int x, y;
scanf("%d%*c%d", &x, &y);
Input:
10,20
VT
Explanation:
U
•%d → reads and stores 10 into x
AD
•%*c → reads comma ( , ) but does not store it
D
•%d → reads and stores 20 into y
A
Output:
x = 10, y = 20
Statements
VT
U
AD
Module-2
D
A
Statements in C
Definition:
• A statement in C is a part of a program that performs an action.
It is something that can be executed by the computer.
C categorizes statements into these groups:
VT
• Selection
U
AD
• Iteration
D
• Jump
A
• Label
• Expression
Example:
• Block x = x + 1;
printf("Hello")
Types of Statements in C
C categorizes statements into six main groups:
Type of Statement Purpose / Meaning Examples
Used for decision-making. They choose
1. Selection Statements which part of the program to execute if, if-else, switch
based on a condition.
VT
Used for repetition (loops) — executing
U
2. Iteration Statements for, while, do-while
a block of code multiple times.
AD
Used to change the normal flow of
D
3. Jump Statements break, continue, goto, return
control in a program.
A
Used with goto or switch for marking a
4. Label Statements case, default, or any label like label1:
point in code.
Any valid expression followed by a
5. Expression Statements a = b + c;, i++;
semicolon.
A group of statements enclosed in
6. Block Statements braces {}. Also called compound { x = 10; y = 20; }
statements.
Additional Points:
• Selection statements are also called conditional statements.
→ They depend on a true or false test result.
• Iteration statements are commonly known as loop statements.
• Block statements can contain any number of statements inside { }.
VT
→ They are used to define the body of loops, conditionals, or functions.
U
AD
D
Concept of True and False in C:
A
• True → any non-zero value.
• False → zero (0).
These values are mainly used in conditions (like in if or while).
Selection Statements in C
What are Selection Statements?
• Selection statements are used to make decisions in a program.
They let the program choose which part of code to execute based on
a condition.
VT
C provides three types of selection mechanisms:
U
• if statement
AD
• if-else / nested if / if-else-if ladder
D
A
• switch statement
• ?: (ternary) operator – shortcut for if-else
1. The if Statement
➤ Syntax:
if (condition)
statement;
VT
else
U
statement;
AD
• The condition is tested first.
D
A
• If true (non-zero) → the if block runs.
• If false (0) → the else block runs (if present).
• Only one block executes — either if or else, never both.
Example 1: Simple if Example 2: if-else
#include <stdio.h> #include <stdio.h>
int main() { int main() {
int num; int num;
printf("Enter a number: "); printf("Enter a number: ");
VT
scanf("%d", &num); scanf("%d", &num);
U
AD
if (num > 0) if (num % 2 == 0)
D
printf("Even number");
printf("Positive number");
A
else OUTPUT:
return 0; Case 1:
printf("Odd number"); Enter a number: 10
} Even number
return 0; Case 2:
Output: Enter a number: 7
} Odd number
If you enter 5, → Positive number
EXAMPLE:
VT
the nearest unmatched if. scanf("%d", &num);
Too much nesting can make code
U
confusing — avoid deep levels. if (num > 0) {
AD
if (num % 2 == 0)
D
printf("The number is positive and even.\n");
A
else
printf("The number is positive and odd.\n");
}
else
printf("The number is not positive.\n");
return 0;
}
Example:
#include <stdio.h>
3. The if-else-if Ladder int main() {
Used to check multiple conditions in int marks;
sequence. printf("Enter your marks: ");
VT
if (condition1) if (marks >= 90)
printf("Grade A");
U
statement1;
AD
else if (marks >= 75)
else if (condition2)
D
printf("Grade B");
A
statement2;
else if (marks >= 50)
else if (condition3)
printf("Grade C");
statement3; else
else printf("Fail");
statementN; return 0;
}
4. The Conditional Operator (?:)
This is a short form of if-else, called the ternary operator.
➤ Syntax:
condition ? expression_if_true : expression_if_false;
Example:
int x = 10, y; Example: Using ?: in Program
VT
#include <stdio.h>
y = (x > 9) ? 100 : 200;
U
int main() {
AD
printf("%d", y); // Output: 100 int num, square;
printf("Enter a number: ");
Same as:
D
scanf("%d", &num);
A
if (x > 9)
square = (num > 0) ? num * num : -(num * num);
y = 100; printf("%d squared is %d", num, square);
else return 0;
}
y = 200; If you enter -4, output → -4 squared is -16
5. Conditional Expression Simplified
In C, any valid expression can be used inside if or ?:.
It just needs to evaluate to true (non-zero) or false (0).
Example:
#include <stdio.h>
int main() {
int a, b;
VT
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
U
AD
if (b)
D
printf("%d", a / b);
A
else
printf("Cannot divide by zero");
return 0;
}
Here,
•If b is not zero → if(b) is true
•If b is zero → else executes.
Writing if (b != 0) is unnecessary — if (b) is enough.
Switch Statement in C Explanation:
•The expression is evaluated once.
•Its result is compared with each case constant
What is a switch statement?
(integer or character).
The switch statement in C is a multi-branch selection
•When a match is found, the code under that case
statement.
It allows you to choose one option from many based on the runs.
value of an expression (like a menu system). •The break statement stops the execution of the
switch.
VT
•The default case runs if no match is found
Syntax: (optional).
U
switch (expression) {
AD
case constant1: Rules of switch:
statement(s);
D
[Link] expression must be of an integer or character
break;
A
case constant2:
type (not float or string).
statement(s); [Link] values must be unique inside the same
break; switch.
... [Link] is optional — if omitted, the program will
default: “fall through” to the next case.
statement(s); [Link] is optional — used when no case
} matches.
[Link] can nest switches inside another switch.
Example 1: Simple Menu Using switch
#include <stdio.h>
int main() {
int choice;
printf("1. Add\n2. Subtract\n3. Multiply\nEnter your
choice: ");
scanf("%d", &choice);
switch (choice) {
VT
case 1:
printf("You chose Addition");
U
break;
AD
case 2:
printf("You chose Subtraction");
D
A
break;
case 3:
printf("You chose Multiplication");
break;
default:
printf("Invalid choice");
}
return 0; Output Example:
} If user enters 2, → Output: You chose Subtraction
Example 2: Character Menu (Using getchar)
#include <stdio.h>
int main() {
char ch;
printf("1. Apple\n2. Banana\n3.
Cherry\nEnter your choice: ");
ch = getchar();
switch (ch) {
VT
case '1':
printf("You selected Apple");
U
break;
AD
case '2':
printf("You selected Banana");
D
break;
A
case '3':
printf("You selected Cherry");
break;
default:
printf("No option selected");
}
return 0;
}
Example 3: Drop-Through Behavior (No break)
If break is missing, execution continues into the next case.
#include <stdio.h>
int main() {
int num = 2;
switch (num) {
case 1:
printf("Case 1\n");
case 2:
VT
printf("Case 2\n"); // falls through
U
case 3:
AD
printf("Case 3\n");
break;
D
default:
A
printf("Default\n");
}
return 0;
}
Explanation:
Output:
No break after case 2 → program continues into case 3.
Case 2
Case 3
Example 4: Grouping Cases Together
Multiple case labels can share the same code.
#include <stdio.h>
int main() {
int day = 6;
switch (day) {
case 1:
case 2:
case 3:
VT
case 4:
case 5:
U
printf("Weekday");
AD
break;
case 6:
D
case 7:
A
printf("Weekend");
break;
default: Output:
printf("Invalid day"); Weekend
} Explanation:
return 0; Cases 1–5 print “Weekday”, and 6–7 print
} “Weekend”.
Example 5: Nested switch (switch inside another switch)
You can have one switch inside another.
#include <stdio.h>
int main() {
int x = 1, y = 0;
switch (x) {
case 1:
switch (y) {
VT
case 0: printf("Inner switch: y = 0\n"); break;
case 1: printf("Inner switch: y = 1\n"); break;
U
}
AD
break;
D
case 2:
A
printf("Outer switch: x = 2\n");
break;
}
return 0;
}
Output:
Inner switch: y = 0
Iteration Statements (Loops) in C
VT
• Iteration means repeating a set of statements multiple times until a
U
specific condition is met.
AD
• In C, there are three types of loops:
D
A
• for loop
• while loop
• do-while loop
The for Loop
Syntax:
for(initialization; condition; increment)
statement;
VT
How it works:
U
• Initialization → sets the starting value of loop variable.
AD
• Condition → checked before each iteration; if true, the loop runs.
D
A
• Increment/Decrement → updates the loop variable each time.
Printing numbers 1 through 100
Step-by-step explanation:
[Link]:
#include <stdio.h> x is set to 1 before the loop starts.
[Link] check:
int main(void)
The loop continues while x <= 100.
{ [Link] execution:
VT
int x; printf("%d ", x); prints the current value of x.
U
AD
[Link]:
for(x = 1; x <= 100; x++) After each iteration, x++ increases x by 1.
D
A
printf("%d ", x); [Link]:
When x becomes 101, the condition x <= 100 is false, so the loop stops.
return 0; Output:
} 1 2 3 4 5 ... 99 100
VT
Note:
[Link]:
This is called a negative running loop
U
x starts at 100.
because x decreases with each iteration
AD
[Link]:
The loop runs as long as x != 65. instead of increasing.
D
[Link]:
A
Each time, it calculates the square of x and prints it.
[Link]:
x -= 5 means subtract 5 from x every iteration.
[Link] of values:
x takes the values → 100, 95, 90, 85, 80, 75, 70, ... until it
becomes 65.
[Link] x equals 65, the condition x != 65 becomes false,
and the loop stops.
FOR LOOP VARIATIONS
Multiple variables for(x=1, y=5; x<=5 && y>=1; x++, y--) Two variables control the loop
VT
Stops when password is correct or
Logical condition for(x<3 && strcmp(str,"pass"))
U
tries end
AD
D
A
Functions inside for(prompt(); n=readnum(); prompt()) Calls functions each time
Two directions for(i=0, j=strlen(s); i<=j; i++, j--) Loop from both ends of a string
Concept Example Description
Initialization before loop int x=0; for(; x<5; x++) Variable initialized outside
VT
U
for(;;) Runs endlessly until break
AD
Infinite loop
D
A
No body for(t=0; t<1000; t++); Loop has no statements
Variable declared in loop for(int i=0; i<10; i++) Scope limited to loop (C99+)
The while Loop
• What is a while loop?
• A while loop is used to repeat a set of statements as long as a condition is true.
General form:
VT
while (condition)
statement;
U
AD
or
D
while (condition) {
A
// statements to repeat
}
• The loop checks the condition first.
If the condition is true (non-zero) → the statements run.
If the condition is false (zero) → the loop stops.
Example: Print Numbers from 1 to 5 using a while loop
Program:
#include <stdio.h>
int main() {
int i = 1; // initialization Output:
1
2
while(i <= 5) // condition 3
VT
{ 4
5
U
printf("%d\n", i); // loop body (what to do)
AD
i++; // increment
D
}
A
return 0;
}
The do-while Loop
Definition
The do-while loop is similar to the while loop, but it checks the condition at the
end of the loop.
This means the loop always runs at least once, even if the condition is false at the
start.
VT
Syntax
Do
U
AD
{
// statements
D
A
} while(condition);
do
{
printf("%d\n", i); // print the current value of i
i++; // increment i
VT
} while(i <= 5); // condition check after the loop body
U
AD
return 0;
}
D
A
Output:
Explanation (Step by Step): 1
[Link] loop starts with i = 1. 2
[Link] loop body executes first, printing 1. 3
[Link] the condition (i <= 5) is checked. 4
[Link] true, the loop repeats. 5
[Link] i becomes 6, the condition is false → the loop stops.
The menu is shown at least once.
Example 2 – Menu Selection Program The loop repeats until the user enters a valid option (1, 2, or 3).
void menu(void)
{
char ch;
VT
do {
U
ch = getchar(); // read user's choice
AD
D
switch(ch)
A
{
case '1': check_spelling(); break;
case '2': correct_errors(); break;
case '3': display_errors(); break;
}
} while(ch != '1' && ch != '2' && ch != '3'); // repeat until valid choice
}
Jump Statements in C
VT
There are four main jump statements in C:
U
• return
AD
• goto
D
A
• break
• continue
return Statement Example 1 – Returning a value:
Purpose: #include <stdio.h>
•Used to exit a function and optionally return a
value to the caller.
Syntax: int add(int a, int b) {
return; // used in void functions
return value; // used in non-void return a + b; // returns sum to main()
functions }
VT
U
AD
int main() {
int result = add(5, 3);
D
Output:
A
Sum = 8 printf("Sum = %d", result);
return 0; // returns control to OS
}
Example 2 – Return without value:
#include <stdio.h>
void greet()
{
VT
printf("Hello!\n");
return; // optional in void functions
U
AD
}
D
A
int main()
{
greet();
return 0;
}
goto Statement
Purpose:
•Used to jump to a labeled statement inside the same Example – Using goto to loop:
function. #include <stdio.h>
It can make programs confusing, so it’s rarely used.
Syntax: int main()
goto label; {
... int x = 1;
label:
loop_start:
VT
// statements
printf("%d ", x);
U
x++;
AD
if (x <= 5)
goto loop_start; // jump back
D
to label
A
return 0;
}
Output:
1 2 3 4 5
break Statement
Purpose:
Example 2 – In switch:
Used to immediately exit a loop or switch statement.
#include <stdio.h>
Example 1 – Breaking a loop:
#include <stdio.h> int main()
{
int choice = 2;
int main() {
VT
for (int i = 0; i < 10; i++)
{ switch(choice)
{
U
if (i == 5)
case 1: printf("One"); break;
AD
break; // stop loop when i = 5
case 2: printf("Two"); break;
printf("%d ", i);
D
case 3: printf("Three"); break;
}
A
}
return 0;
} return 0;
}
VT
int main()
U
{
AD
for (int i = 1; i <= 10; i++)
{
D
if (i % 2 == 0)
A
continue; // skip even numbers
printf("%d ", i);
}
return 0;
}
Output:
1 3 5 7 9
Bonus: exit() Function
Purpose:
Used to end the entire program immediately (not just a loop
or function).
•Defined in <stdlib.h>.
Syntax: Example:
exit(code); #include <stdio.h>
•exit(0) → normal termination
VT
#include <stdlib.h>
•exit(1) → abnormal termination (error)
U
int main() {
AD
int hasAccess = 0;
if (!hasAccess) {
D
printf("Access denied!\n");
A
exit(1); // stop program immediately
}
printf("Welcome!");
return 0;
}
Output:
Access denied!