Module - 2 - Notes C Programming
Module - 2 - Notes C Programming
● In C programming, console input and output (I/O) refers to taking input from the
keyboard and displaying output on the screen.
● Character I/O means reading or writing one character at a time.
● Used to read a single character from the standard input device (keyboard).
● It does not take any arguments.
● It returns the ASCII value of the character read.
Syntax:
int ch;
ch = getchar();
Example:
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
c = getchar(); // reads a single character
printf("You entered: ");
putchar(c); // prints that character
return 0;
}
Explanation:
Example:
#include <stdio.h>
#include <conio.h>
int main()
{
char c;
printf("Press any key: ");
c = getch(); // reads char without echo
printf("\nYou pressed: %c", c);
return 0;
}
Example:
#include <stdio.h>
#include <conio.h>
int main() {
char c;
printf("Press a key: ");
c = getche(); // reads and displays char
printf("\nYou pressed: %c", c);
return 0;
}
Syntax: putchar(character);
Example:
#include <stdio.h>
int main()
{
char ch = 'B';
putchar(ch); // displays B
return 0;
}
Example:
#include <stdio.h>
#include <conio.h>
int main()
{
char ch = 'Z';
putch(ch); // displays Z
return 0;
}
C provides several functions for reading and writing strings through the console.
Explanation:
Only Manoj is read, because scanf() stops reading at the first space.
Hence, it cannot read multi-word strings.
Syntax: gets(string_variable);
Example:
#include <stdio.h>
int main() {
char sentence[50];
printf("Enter a sentence: ");
gets(sentence);
printf("You entered: %s", sentence);
return 0;
}
⚠️ Note:
gets() is unsafe because it does not check for buffer overflow.
Explanation:
● fgets() reads at most (size – 1) characters.
● It includes the newline character \n if the user presses Enter before reaching the limit.
Example:
#include <stdio.h>
int main() {
char name[] = "C Programming";
printf("Welcome to %s!", name);
return 0;
}
Output: Welcome to C Programming!
Syntax: puts(string_variable);
Example:
#include <stdio.h>
int main() {
char msg[] = "Learning C is fun!";
puts(msg);
return 0;
}
These are standard I/O functions defined in the header file <stdio.h>.
1. Formatted Output Function — printf()
● The printf() function is used to display information on the console in a formatted way.
● It allows us to print text, numbers, characters, and strings with specific formatting.
%ld long int Prints a long signed integer. Example: printf("%ld", 123456L); →
123456
%lu unsigned long int Prints an unsigned long integer. Example: printf("%lu",
123456UL); → 123456
%lld long long int Prints a long long signed integer. Example: printf("%lld",
123456789LL); → 123456789
%llu unsigned long Prints an unsigned long long integer. Example: printf("%llu",
long int 123456789ULL); → 123456789
Example Program 1
#include <stdio.h>
int main() {
int roll = 101;
float marks = 89.75;
char grade = 'A';
char name[] = "Manoj";
Output:
Name: Manoj
Roll No: 101
Marks: 89.75
Grade: A
Example Program 2:
#include <stdio.h>
int main(void)
{
printf("%d\n", 25); // prints integer
printf("%u\n", 40000); // prints unsigned integer
printf("%f\n", 3.142); // prints floating-point number
printf("%e\n", 12345.5); // scientific notation
printf("%x\n", 255); // hexadecimal (lowercase)
printf("%X\n", 255); // hexadecimal (uppercase)
printf("%o\n", 255); // octal
Output:
25
40000
3.142000
1.234550e+004
ff
FF
377
%n format specifier
● The %n format specifier in printf() is a special code that does not print anything.
● Instead, it stores the number of characters printed so far into an integer variable
provided through a pointer.
● %n tells printf() to count the characters it has printed up to that point and store that
number in a variable whose address is given as an argument.
Example:
#include <stdio.h>
int main(void)
{
int count=0;
printf("this%n is a test\n", &count);
printf("Value stored in count: %d\n", count);
return 0;
}
output:
this is a test
Value stored in count: 4
Explanation:
Example:
#include <stdio.h>
int main()
{
float num = 3.141592;
printf("%.2f\n", num);
printf("%.4f\n", num);
printf("%.0f\n", num);
return 0;
}
Output:
3.14
3.1416
3
Explanation:
● %.2f → prints 2 digits after decimal → 3.14
Example:
#include <stdio.h>
int main() {
char str[] = "HelloWorld";
printf("%.5s\n", str);
printf("%.8s\n", str);
return 0;
}
Output:
Hello
HelloWor
Explanation:
● %.5s → prints first 5 characters of string → Hello
Example:
#include <stdio.h>
int main() {
double num = 123.456789;
printf("%.4g\n", num);
printf("%.6g\n", num);
return 0;
}
Output:
123.5
123.457
❖ Precision .n
● For integers, .n specifies the minimum number of digits to print.
● If the integer has fewer digits, leading zeros are added
● If the integer already has equal or more digits, it prints normally.
Rule:
If .n produces a number wider than m, m is ignored.
● .8 → 8 digits → "00000010".
Output: 00000010
Another example: printf("%10.3d", 10);
● .3 → "010" (3 digits).
Output: 010
Output: | 123|
(Spaces before the number)
2. Left Justification
● Left justification is done by adding a - flag before the width.
● Padding spaces are added after the value.
● This makes the value align to the left side of the field.
Output: |123 |
(Spaces after the number)
Examples:
long int a = 100000;
printf("%ld", a); // Prints long integer
2. The # Modifier
● The # flag changes the appearance of the output for certain format specifiers.
Format Specifier Effect
Example:
printf("%#x\n", 10); // Output: 0xa
printf("%#o\n", 10); // Output: 012
printf("%#f\n", 10); // Output: 10.000000
3. The * Modifier
● The * modifier allows dynamic control of minimum field width and precision.
● Instead of hardcoding width or precision in the format string, they are taken from
arguments.
Syntax: %*.*specifier
● First * → field width
● Second * → precision
Example:
#include <stdio.h>
int main(void) {
printf("%*.*f", 10, 4, 1234.34);
return 0;
}
Explanation:
● 10 → minimum field width
Output: 1234.3400
(Spaces added before number to make total width = 10, decimals rounded to 4 places.)
Output: a 0xa
& (address-of operator) → tells scanf() where to store the value in memory.
Example:
#include <stdio.h>
int main()
{
int age;
float height;
char grade;
char name[20];
printf("\nStudent Details:\n");
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
printf("Grade: %c\n", grade);
return 0;
}
Input:
Manoj 20 5.8 A
Output:
Student Details:
Name: Manoj
Age: 20
Height: 5.80
Grade: A
1. White-space handling
2. Maximum field width
3. Non-white-space characters in control string
4. Assignment suppression (*)
5. Scansets (%[...])
1. White-space Handling
● Any white-space character in the control string (space, tab, newline) tells scanf() to skip
all leading whitespace until the next non-whitespace character.
● Works for numeric and string inputs.
Example Program:
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers:\n");
scanf("%d %d", &a, &b);
printf("First: %d, Second: %d\n", a, b);
return 0;
}
Input:
10
20
Input:
HelloWorld
Output:
You entered: Hello
Input: 10,20
Output: x = 10, y = 20
(If you enter 10 20 → scanf fails.)
Example Program:
#include <stdio.h>
int main() {
int x, y;
printf("Enter two numbers separated by a comma:\n");
scanf("%d%*c%d", &x, &y);
printf("x = %d, y = %d\n", x, y);
return 0;
}
Input: 10,20
Output: x = 10, y = 20
(The comma is read but not stored.)
What %d%*c%d means
In scanf():
● %d → read an integer
So %d%*c%d means:
1. Read first integer → store in x
5. Scanset (%[...])
Example
#include <stdio.h>
int main() {
char str[20];
printf("Enter string with only a, b, c:\n");
scanf("%[abc]", str);
printf("Read string: %s\n", str);
return 0;
}
Input:
Enter string with only a, b, c:
abcashods
output:
Read string: abca
#include <stdio.h>
int main() {
char str[20];
printf("Enter string until digit is found:\n");
scanf("%[^0-9]", str);
printf("Read string: %s\n", str);
return 0;
}
Input: hello123world
1. if statement
2. if-else statement
3. if-else if statement
4. switch statement
1. if Statement
The if statement is the simplest decision statement. It executes a block of code only if a
condition is true.
Syntax:
if (condition)
{
// statements executed if condition is true
}
Explanation:
● The condition (age >= 18) is checked.
● If true → the message is printed.
● If false → nothing happens, the program moves to the next statement.
2. if-else Statement
● The if-else statement executes one of two blocks depending on whether the condition is
true or false.
● It executes the if block if the condition is true otherwise the else block is executed.
Syntax:
if (condition) {
// executed if condition is true
} else {
// executed if condition is false
}
Data Flow Diagram:
Examples:
a) Check Even or Odd Number
#include <stdio.h>
void main() {
int a;
printf("Enter a number: ");
scanf("%d", &a);
if(a % 2 == 0) {
printf("The number is even\n");
} else {
printf("The number is odd\n");
}
}
Example:
Input : 12
Output : The number is even
Input : 7
Output : The number is odd
Output: a is largest
Example:
Input Output
A Lowercase: a
k Uppercase: K
Example:
Input Output
Explanation:
● The condition is checked first.
● If true → the first block executes.
DataFlow Diagram:
Example:
Input (a,b,c) Output
4. Nested if Statement
A nested if statement is an if or if-else statement inside another if or else block. It is
used when a decision depends on another decision.
Syntax
if(condition1)
{
// executed if condition1 is true
if(condition2)
{
// executed if condition2 is true
}
else
{
// executed if condition2 is false
}
} else
{
// executed if condition1 is false
}
#include <stdio.h>
void main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if(a > b) {
if(a > c)
printf("a is largest\n");
else
printf("c is largest\n");
} else {
if(b > c)
printf("b is largest\n");
else
printf("c is largest\n");
}
}
Sample input/output:
5. switch Statement
Switch is used to select one block from many options based on the value of a variable.
Syntax:
switch(variable)
{
case value1:
// statements
break;
case value2:
// statements
break;
...
default:
// statements if no case matches
}
DataFlow Diagram:
#include <stdio.h>
void main()
{
int day;
printf("Enter a number (1-7): ");
scanf("%d", &day);
switch(day) {
case 1: printf("Sunday\n"); break;
case 2: printf("Monday\n"); break;
case 3: printf("Tuesday\n"); break;
case 4: printf("Wednesday\n"); break;
case 5: printf("Thursday\n"); break;
case 6: printf("Friday\n"); break;
case 7: printf("Saturday\n"); break;
default: printf("Invalid input\n");
}
Example
Input Output
1 Sunday
4 Wednesday
8 Invalid input
switch(op) {
case '+':
result = num1 + num2;
printf("Result: %.2f\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2f\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2f\n", result);
break;
case '/':
if(num2 != 0)
printf("Result: %.2f\n", num1 / num2);
else
printf("Error: Division by zero\n");
break;
default:
printf("Invalid operator\n");
}
}
Sample input/output
Input Output
*, 4, 6 Result: 24.00
%, 5, 2 Invalid operator
Const variable Valid const int x=5; case x: Const evaluated at compile-
time.
Iteration Statements
● Iteration statements, also called loops, allow a program to repeat a block of code
multiple times until a condition is satisfied.
● They are used when the same task needs to be performed repeatedly.
Purpose:
Types of Loops in C
1. while loop
2. do-while loop
3. for loop
4. Nested loops
1. while Loop
Syntax:
while(condition)
{
// statements
}
Flow Diagram:
Rules:
#include <stdio.h>
void main()
{
int i = 1, sum = 0;
while(i <= 5)
{
sum += i;
i++;
}
printf("Sum = %d\n", sum);
}
Output:
Sum = 15
2. do-while Loop
● do-while is also called post-test loop that means the loop body executes first, then the
condition is checked.
● Guarantees at least one execution even if the condition is false.
Syntax:
do {
// statements
} while(condition);
Flow diagram:
Rules:
1. Condition works same as while.
2. Useful when input or action must happen at least once, like reading user input.
3. Semicolon after while(condition); is mandatory.
#include <stdio.h>
void main()
{
int i = 1;
do {
printf("%d ", i);
i++;
} while(i <= 3);
}
Output:
123
3. for Loop
Syntax:
FlowDiagram:
Example: Print 1 to 5 using for
#include <stdio.h>
void main() {
int i;
for(i = 1; i <= 5; i++)
printf("%d ", i);
}
Output:
12345
Jump Statements
Jump statements transfer the control of program execution from one part to another.
1. break
2. continue
3. goto
4. return
1. break Statement
#include <stdio.h>
int main() {
for(int i=1; i<=5; i++)
{
if(i == 3)
break; // exit loop immediately
printf("%d\n", i);
}
return 0;
}
Output:
1
2
2. continue Statement
● The continue statement skips the current iteration of the loop and moves control to the
next iteration.
● Useful when we want to ignore some cases but continue looping.
Example:
#include <stdio.h>
int main() {
for(int i=1; i<=5; i++)
{
if(i == 3)
continue; // skip iteration when i=3
printf("%d\n", i);
}
return 0;
}
Output:
1
2
4
5
3. goto Statement
● The goto statement is used to jump to a labeled statement in the same function.
● Its use is discouraged in modern programming because it makes code difficult to read.
Syntax:
goto label_name;
...
label_name: statement;
Example:
#include <stdio.h>
int main() {
int i = 1;
start: // label
if(i <= 5)
{
printf("%d\n", i);
i++;
goto start; // jump back to label
}
return 0;
}
Output:
1
2
3
4
5
4. return Statement
● The return statement is used in functions to exit the function and optionally send a value
back to the caller.
Example:
#include <stdio.h>
int square(int n)
{
return n * n; // return value
}
int main()
{
int result = square(5);
printf("Square = %d", result);
return 0;
}
Output:
Square = 25
Block Statements in C
1. A block statement is a group of one or more statements enclosed within curly braces { }.
2. The compiler treats the whole block as a single statement, so it is also called a compound
statement.
3. A block can contain both declarations (like variable definitions) and executable
statements (like assignments, loops, function calls)
4. Blocks are required when C syntax allows only one statement but we need to write
multiple statements.
○ Example: after if, else, for, while, or do-while.
5. The body of every function in C is a block statement.
6. A block does not end with a semicolon. Only the statements inside it require semicolons.
7. A block introduces a new scope.
○ Variables declared inside a block exist only within that block.
○ They cannot be accessed outside the block.
8. Blocks can be nested, meaning a block can contain another block.
9. An empty block written as { } is allowed and is sometimes used as a placeholder.
General Form
{
statement1;
statement2;
...
statementN;
}
#include <stdio.h>
int main()
{
int x = 10;
if (x > 5)
{
// Block statement
printf("x is greater than 5\n");
x++;
printf("Now x = %d\n", x);
} else
{
// Another block
printf("x is 5 or less\n");
}
return 0;
}
#include <stdio.h>
int main() {
for(int i=1; i<=3; i++) {
// block
{
int square = i * i;
printf("Square of %d = %d\n", i, square);
}
}
return 0;
}
Important Notes
● A block creates a new scope.
● Variables declared inside a block are local to that block and cannot be used outside.
● Nested blocks (block inside another block) are allowed.
● A block may also be empty, like { }. This is sometimes used as a placeholder.