Syllabus: 3.25CS23.
pdf
Text Book 1: C The Complete Reference 4th Ed Herbert
Schildt[[Link]].pdf
Text Book 2:
Console I/O (Input/Output)
● A console is the screen and keyboard interface used to interact
with a computer.
● Taking input from the keyboard and displaying output on the
screen.
● C does not have built-in I/O keywords
● Input and output are done using library functions
● Unformatted I/O functions can handle Characters and strings.
● formatted I/O functions can handle all the datatypes scanf()
and printf().
Formatted I/O Vs Unformatted I/O
Feature Formatted I/O Unformatted I/O
Format Takes input/output in a Takes input/output as raw
specific format (user- characters (no format)
defined)
Specifiers Uses format specifiers No format specifiers
(%d, %f, %c)
Data Types Works with all data types Characters & strings
Usage Structured input/output Direct input/output
Examples printf(), scanf() getchar(), putchar(),
gets(), puts()
Types of Unformatted Console I/O
● Character I/O: works with single characters
getchar(), putchar()
● String I/O: works with group of characters (string)
gets(), puts()
● Header file used:
#include <stdio.h>
1. Reading and writing Characters( I/O Functions)
i) getchar()
● Reads one character from keyboard and waits for Enter key (line
buffered)
char ch;
ch = getchar();
ii) putchar()
● Prints one character on screen
char ch = 'A';
putchar(ch);
Problem with getchar():Needs Enter key, Not good for interactive
programs
🔹 Alternatives (Non-standard)
Header: <conio.h>
Function Description
getch() Reads char without
echo(print), no Enter needed
getche() Reads char with echo, no
Enter needed
2. Reading and writing Strings ( I/O Functions)
1. gets()
● Reads a string from the keyboard.
● It keeps reading characters until you press Enter.
● Adds null character \0 at the end ( if you type "Hi", in memory it
stores H i \0)
● Unsafe because there is no size checking
char a[50];
gets(a);
printf("You entered: %s", a);
2. puts()
● Prints a string followed by a newline.
puts(str);
char a[] = "Hello World";
puts(a);
Formatted Console I/O in C
Formatted I/O
● Formatted I/O allows input and output in a controlled format.
● Formatted I/O uses:
○ printf() to print output to screen
○ scanf() used to enter input from keyboard
1. Formatted output: printf() Function
Syntax
printf("format specifier", values);
Example
printf("Hello");
printf("Value = %d", a);
● Purpose of printf() is to print data to console in formatted way
Format Specifiers
Specifier Meaning
%c Character
%d / %i Integer
%f Float
%e / %E Scientific notation
%g / %G Shortest format printf("%g", 10000000.0);
1e+07
%s String
%u Unsigned integer
%o Octal
%x / %X Hexadecimal
%p Address
%n Stores number of characters printed
printf("Hello%n World", &count); #5
%% Print % symbol
Example
printf("I like %c %s", 'C', "very much!");
Output:
I like C very much!
Printf Features
a) Field Width(right justification): Specifies minimum number of
spaces for output.
Print integer 10 in a minimum width of 5 spaces
printf("%5d", 10);
Output:
10
b) Precision: Controls number of digits after decimal
printf("%.2f", 3.456);
Output:
3.46
c) Left Justification:Aligns output to the left.
printf("%-5d", 10);
%5d → ___10 (right side)
%-5d → 10___ (left side)
d) Zero Padding
printf("%05d", 10);
Output:
00010
Total width 5, number 10 (2 digits), so remaining spaces filled with 0
→ 00010
e) Special Modifiers
Modifier Meaning
H → short int
L→ long int
Ll → long long int
L→ long double
f) Special Symbols
● # → Adds prefix to numbers (like x for hex, o for octal)
Example: printf("%#x", 10);
Output: 0xa
● * → Takes width/precision value from argument
Example : printf("%*d", 5, 10);
Output:
- - - 10
2. Formatted Input:Scanf() Function
Scanf is a function used to read formatted input from the keyboard
and store it in variables
Syntax
scanf("format_specifier", &variable);
Purpose
● Reads input from user
Always use address operator (&)
Example
int age;
scanf("%d", &age);
Format Specifiers
Specifi Meaning
er
%d Integer
%f Float
%c Character
%s String
%u Unsigned
%o Octal
%x Hexadeci
mal
%p Address
%[ ] Scanset
%% Read %
Scanf Concepts
a) Reading Integer
scanf("%d", &x);
b) Reading String
scanf("%s", str);
Stops at space
c) Reading Character
scanf("%c", &ch);
d) Scanset
scanf("%[abc]", str);
Reads only a, b, c
e) Skip Input:Skips unwanted character
scanf("%d%*c%d", &x, &y);
f) Limit Input Size
scanf("%5s", str);
Summary
Example Program
#include <stdio.h>
int main() {
int a;
float b;
char str[20];
printf("Enter int, float and string: ");
scanf("%d %f %s", &a, &b, str);
printf("You entered: %d %.2f %s", a, b, str);
return 0;
}
Statement in C
A statement is any instruction in a program that performs an action.
Example:
x = 5;
printf("Hello");
Types of Statements in C
1. Selection Statements (Decision making)
Used to choose between options.
● if, switch
Example:
if (x > 0)
printf("Positive");
else
printf("Negative");
2. Iteration Statements (Loops)
Used to repeat actions.
● while, for, do-while
Example:
for(int i=0; i<5; i++)
printf("%d", i);
3. Jump Statements
Used to transfer control.
● Break, continue, goto, return
Example:
break; // exits loop
return 0; // exits function
4. Label Statements
Used with goto or in switch.
● Case, default, user-defined labels
Example:
case 1: printf("One"); break;
5. Expression Statements
Statements that contain expressions.
Example: a = b + c;
6. Block Statements (Compound)
Group of statements inside { }.
Example:
{
int x = 10;
printf("%d", x);
}
Statements - Summary
True and False in C
● True is any non-zero value (1, -5, etc.)
● False is 0
Example:
if(5) // TRUE
if(0) // FALSE
Selection Statement
● A selection statement is used to make decisions in a program.
● It chooses which code to execute based on a condition.
● if statement and switch statement
1. if Statement:
An if statement is used to execute a block of code only when a specified
condition is true.
General Syntax:
if (condition)
statement1;
else
statement2;
Only one block executes
Example
if(x>0)
printf("Positive");
else
printf("Negative");
2. Nested if: Inside if another if.
Example:
if (age >= 18)
{
if(age>=60)
printf(“Senior Citizen”);
else
printf(“Adult”)
}
else
printf(“Minor”)
3. if-else-if Ladder: Used for multiple conditions.
Syntax:
if(condition1)
statement;
else if(condition2)
statement;
else if(condition3)
statement;
else
statement;
Example:
if (marks >= 90)
printf("A");
else if (marks >= 75)
printf("B");
else
printf("C");
? Operator (Shortcut for if-else)
Syntax:
condition ? value1 : value2;
Meaning
● If condition is true then will take value1
● If condition is false then will take value2
Example: y = (x > 9) ? 100 : 200;
Same as:
if (x > 9)
y = 100;
else
y = 200;
Switch Statement ( Multi- Way Decision Statement)
● A switch statement selects one block of code from many
options based on a value of expression.
Syntax
switch(expression)
{
case constant1:
statements;
break;
case constant2:
statements;
break;
default:
statements;
}
● Expression must be integer or character
● Each case must have a unique constant value
● default is optional
● break stops execution of the switch
● Without break, execution continues (fall-through)
The expression is evaluated, compared with each case, executes the
matched block, stops at break or end, and runs default if no match is
found.
switch vs if:
● Switch checks only equality and is faster for multiple choices,
● if can check any condition and is more flexible.
Break Statement
● Break is used to exit switch
● Without break next cases also run
Fall-Through
● Happens when break is missing
● Control moves to next case automatically
Example:
case 1:
printf("One");
case 2:
printf("Two");
Output for 1 → OneTwo (fall-through)
Default Case: Runs when no case matches
default:
printf("Invalid choice");
Nested switch
● Inside switch another switch
switch(x)
{
case 1:
switch(y)
{
case 0:
printf("Error");
Break;
case 1:
printf("Success\n");
break;
}
break;
}
Example: Lab program 03
Iteration Statements (Loops)
● Used to repeat a set of instructions until a condition is true.
● Types in C:
○ for
○ while
○ do-while
for Loop
● Used when number of iterations is known
Syntax:
for(initialization; condition; increment)
statement;
Initialization → Condition check → Execute the statement →
Increment → Repeat until condition false
Example
for(int x = 1; x <= 5; x++)
printf("%d ", x);
Output: 1 2 3 4 5
● Condition checked at the beginning
● May execute zero times if condition is false
● Loop control variable changes each iteration
for Loop Variations
Multiple Variables
A for loop can use more than one variable in initialization and
increment using the comma ( , ) operator.
for(int x=0, y=5; x<y; x++, y--)
printf("%d %d\n", x, y);
Output:
05
14
23
Infinite Loop
An infinite loop is a loop that runs forever because no condition is
given (always true).
for(;;)
printf("Runs forever");
No Increment
A no increment for loop is a loop where the increment/decrement part
is left empty, and the update of the variable is done inside the loop
body.
for(x=0; x!=5; )
scanf("%d", &x);
The loop continues until user enters 5
No Initialization
A no initialization for loop is a loop where the initialization part is left
empty because the variable is already initialized before the loop.
x = 1;
for(; x<=5; x++)
printf("%d", x);
Output: 1 2 3 4 5
Empty Body Loop
Loop runs but does nothing
for(x=0; x<5; x++);
Declaring Variables in a for Loop
● In C99 and C++, you can declare variables inside the for loop
● Not allowed in C89
● Variable declared inside for is local to that loop only
Syntax
for(int i = 0; i < 10; i++)
statement;
While Loop
A while loop repeats a statement as long as the condition is true.
Syntax
while(condition)
{
statements;
}
● Condition is checked first
● If condition is true then loop runs
● If false then loop stops
● Executes 0 or more times
int i = 1;
while(i <= 5)
{
printf("%d ", i);
i++;
}
Output: 1 2 3 4 5
Example
while(ch != 'A')
ch = getchar();
Keeps running until user types A
While loop checks condition at the top, so it may not execute even once.
Empty while loop
while((ch = getchar()) != 'A');
● Loop runs but has no body
● while loop executes statements repeatedly as long as the
condition is true.
Do-While Loop
A do-while loop checks the condition after executing the loop body, so
it runs at least once.
Syntax
do {
statement;
}
while(condition);
● Condition is checked at the bottom
● Loop runs minimum one time
● Continues until condition becomes false
Example
int num;
do
{
scanf("%d", &num);
}
while(num > 100);
Keeps taking input until number ≤ 100
● Menu is shown at least once
● User keeps entering choice until valid option is given
Example 1:
Example 2(Textbook)
do-while executes first, then checks condition (runs at least once).
Jump Statements in C
● Jump statements stop current execution and move to another part
of the program immediately.
● Jump statements change the normal flow of a program
immediately.
There are 4 jump statements:
● return
● goto
● break
● continue
1. return Statement
Return is used to exit from a function
With value (non-void function)
int add()
{
return 5;
}
Without value (void function)
void show()
{
printf("Hello");
return;
}
● Ends the function immediately
● Can return a value or not
● Many return statements allowed
2. goto Statement
● Used to jump to a label inside the same function
Syntax:
goto label;
…..
Label:
statement;
Example1:
OUTPUT
Example 2:
#include <stdio.h>
int main() {
int x = 1;
loop:
printf("%d ", x);
x++;
if(x <= 5)
goto loop;
return 0;
}
#12345
● Makes code hard to read
● Avoid in most cases
3. break Statement
● break statement is used to stop a loop immediately
Example:
#include <stdio.h>
int main()
{
int i;
for(i = 0; i < 10; i++)
{
if(i == 5)
break;
printf("%d ", i);
}
} Output: 0 1 2 3 4
● Exits loop instantly
● Used in for, while, do-while, and switch
4. continue Statement
● Used to skip current iteration and go to next loop
Example:
#include <stdio.h>
int main() {
int i;
for(i = 1; i <= 5; i++)
{
if(i == 3)
continue;
printf("%d ", i);
}
}
Output: 1 2 4 5
● Skips only one iteration
● Loop continues normally
Summary
Expression Statements
● An expression is a combination of variables, constants, and
operators that produces a value.
● Every expression returns a value
Example:
5 + 3 // result is 8
a + b // sum of a and b
x = 10 // assigns 10 to x
a * b + c // calculation
;does nothing (empty statement)
func(); → calls a function
Block Statements
A block statement is a group of statements inside { }
Example:
{
int x = 10;
printf("%d", x);
}
● Starts with { and ends with }
● Treats multiple statements as one unit
● Used in:
○ if
○ for
○ while
○ functions
Example
#include <stdio.h>
int main()
{
int i;
{ // block statement
i = 120;
printf("%d", i);
}
return 0;
}