Introduction to Computer
Science, CSL1010
PALASH DAS |CSE DEPARTMENT | IIT JODHPUR |
11/6/2025 PALASH@IIT JODHPUR 1
One of the Prerequisite: Empathy
11/6/2025 PALASH@IIT JODHPUR 2
Any Standard books should be fine
11/6/2025 PALASH@IIT JODHPUR 3
Tentative Assessment Policy
Continuous Evaluations: 40%
• Assignments, Lab, attendance: 20%
• Project, Viva, Presentation: 20%
Primary Evaluations: 60%
• Minor: 20%
• Major: 40%
11/6/2025 PALASH@IIT JODHPUR 4
Any Guesses about this picture?
• Electronic Numerical Integrator and Computer (ENIAC), the first
programmable general-purpose electronic digital computer.
• Built during World War II by the United States.
• Speed: 5000 additions or 50 multiplications in one second.
• Weight: 30 tons ≈ 4 Maruti Alto Cars.
• Area: 1,500 square feet of floor space ≈ 19 IIT Jodhpur-
Hostel’s room.
• Power Consumptions: 174,000 watts ≈ more than 350 fans
iPhone:
Speed: 1-5 TFLOPS.
Weight: around 170gms.
Area: No need to mention.
Power consumption: Around 5-20 watts.
So, should we stop now?
11/6/2025 PALASH@IIT JODHPUR 5
How can we get high
performance/energy efficiency?
Example Analogy:
ISA is like a recipe, while microarchitecture is the kitchen
layout and tools used to prepare the dish.
11/6/2025 PALASH@IIT JODHPUR 6
How did this miracle happen?
Thanks to VLSI technology, billions of transistors can be
placed on a single chip to be used for computations.
5nm technology, 10 billion
transistors in each chip
Latest snapdragon 888 chip (2022-2023)
• A human hair is approximately 80,000- 100,000 nm
Image courtesy Bell System Memorial wide.
• A sheet of paper is about 100,000 nm thick.
11/6/2025 OS @ PALASH | IIT JODHPUR 7
What do we want from a system?
• Performance: Higher IPC, Higher GHz, Higher throughput (TFLOPS,TOPS,…), etc.
• Power/Energy efficiency: MIPS/W (millions of instructions per second per watt), TFLOPs/watt.
• Area overhead: small mm2
11/6/2025 OS @ PALASH | IIT JODHPUR 8
Computer System Structure
Computer system can be divided into four components:
◦ Hardware – provides basic computing resources
◦ CPU, memory, I/O devices
◦ Operating system
◦ Controls and coordinates use of hardware among various applications and users
◦ Application programs – define the ways in which the system resources are
used to solve the computing problems of the users
◦ Word processors, compilers, web browsers, database systems, video games
◦ Users
◦ People, machines, other computers
11/6/2025 OS @ PALASH | IIT JODHPUR 9
CPU/Processor
• All calculations are done by ALU (Adders, Multipliers, FPUs…).
• The Control Unit generates the sequence of control signals to carry out one
operation.
• Processor fetches instructions/data from memory for execution.
• What is an instruction?
• A program refers to set of instructions.
Any other types of processing units?
11/6/2025 OS @ PALASH | IIT JODHPUR 10
Processing Options in the present era
11/6/2025 OS @ PALASH | IIT JODHPUR 11
What do we want from a memory?
Old requirements
◦ Zero Cost
◦ Zero Latency
◦ Infinite Bandwidth
◦ Infinite capacity
DRAM and Memory Controller (as we know them today) are unlikely to satisfy these needs.
And now some new requirements
◦ Nonvolatility
◦ Low leakage or Zero standby power consumptions
11/6/2025 OS @ PALASH | IIT JODHPUR 12
Memory Hierarchy (Cont.…)
11/6/2025 OS @ PALASH | IIT JODHPUR 13
Modern System
11/6/2025 OS @ PALASH | IIT JODHPUR 14
Program to electron
• ISA is an interface between S/W and H/W
• How will instruction be interpreted?
• What all instructions are supported?
• Across the processor generations, the
ISA can be same, e.g., IBM 360 series,
Intel x86 series, etc.
• Implementation of the same ISA can
vary based on processor’s implementations.
11/6/2025 OS @ PALASH | IIT JODHPUR 15
Executable Code (*.EXE, *.out,
From Program to a Process etc.)
Metadata header +
01010000101
01010110101
11110000101
Loader + Kernel
Compilation
User’s Space
Process
Still in HDD/SDD?
• Two important pillars of computing
Main Memory
• Data
• Instructions
11/6/2025 OS @ PALASH | IIT JODHPUR 16
A high-level view of Program Execution
11/6/2025 OS @ PALASH | IIT JODHPUR 17
When press the power button….
11/6/2025 OS @ PALASH | IIT JODHPUR 18
Execution process using GCC (GNU Owner (creates the file), Group
Compiler Collection) (can be shared with a group), and
Others.
Check ls –l to see owner, group.
Check if gcc is installed? (In terminal, type gcc -v or gcc --version) rwx – read, write, execute.
If not installed, install the gcc. --- no permission.
MAC: Install Homebrew, Install GCC, make gcc use GNU GCC instead of Apple clang.
Ubuntu: sudo apt install gcc g++, check gcc –version.
gcc program_name.c (various options can be passed)---> Compilation
You can get to see the machine code--->[Link]
You can also rename the executable with option.
To run ./[Link] ----> why ./ is needed?------>current directory
Sometimes you might need to check the permission of a file.
11/6/2025 OS @ PALASH | IIT JODHPUR 19
Welcome to the world of C…. (in 1972 by Dennis Ritchie at Bell Labs.)
#include <stdio.h> Header file
int main (void) Usually the entry point of a c program
{ Library function,
uses write system call
printf (“Hello world”);
} Statement terminator
Formatted output
Role of startup code
Without main, you program won’t link ()--> Undefined reference to main. 1. Prepare the execution environment
When you compile and link a C program, the linker automatically includes startup code (stack, heap, global variables).
from the C runtime library. This code is not written by you, but it exists in your executable. 2. Call your main ()
3. Pass the return value of main to OS.
OS @ PALASH | IIT JODHPUR
11/6/2025 20
Main is User-defined. But it is so special .
A function inside the C standard library (glibc on Linux).
operating system and compiler dependent.
The very first function that runs in your program after the OS
loader jumps in. It is provided by the startup code linked into
every c library. It’s not written in C, but in assembly.
What does main returns to os?
11/6/2025 PALASH@IIT JODHPUR 21
Variables
Variables are containers for storing data values, like numbers and characters in the memory.
Can we change the content of a
container?
You can imagine
something like
this
How big container do we need to pack the content? Container type / Datatype
11/6/2025 OS @ PALASH | IIT JODHPUR 22
Datatypes: some built-in/primitive datatypes
The datatype of a variable determines how much space it occupies in memory and how the bit pattern
stored is interpreted.
11/6/2025 OS @ PALASH | IIT JODHPUR 23
Void
Is a type, but not a data type.
Functions can have a void return type, which means they do not return a value.
The parameter list of a function can also be void. It means the function takes no parameters.
For now, you can think of void more as a
placeholder for “nothing”.
11/6/2025 OS @ PALASH | IIT JODHPUR 24
Variable Naming Rules in C
Valid but try to avoid as it is reserved for compiler/system use.
Standard GCC
• At least 63 significant characters for internal identifiers (local
variables, macros)
• At least 31 significant characters for external identifiers (global
variables, function names)
11/6/2025 PALASH@IIT JODHPUR 25
Another demo code
#include <stdio.h> Format Specifiers
int main () Declaring variables
{ A few of them are as follows.
int a, b, c; %c --- character
%d --- Signed integer (%7d)
a = 5; %f --- Float values (%.3f)
%lf --- Long double
b = 6; %s --- Strings
%o --- Octal
c = a+b; Etc…………….
printf (“The sum is %d”, c);
} Assigning some value in the variables
11/6/2025 OS @ PALASH | IIT JODHPUR 26
User input
#include<stdio.h>
#include<stdio.h>
int main()
int main() {
{ int a, b, sum = 0;
int a, b, sum = 0; /*printf("Please input number 1:");
printf("Please input number 1:"); scanf("%d", &a); Commenting
printf("Please input number 2:"); Multiple lines
scanf("%d", &a); scanf("%d", &b);*/
printf("Please input number 2:"); printf("Please input the two numbers:");
scanf("%d", &b); scanf("%d %d", &a, &b);
sum = a + b; sum = a + b;
printf("The sum is %d \n", sum); //printf("The sum is %d \n", sum); Commenting Single line
} printf("The numbers are %d and %d, and the sum is %d\n", a, b, sum);
}
See the positions
11/6/2025 OS @ PALASH | IIT JODHPUR 27
User input
#include<stdio.h>
int main ()
{
float num1;
int num2;
char ch;
double data;
// float num1 = 0.0;
// int num2 = 1;
// char ch = 'c';
// double data = 4.5;
printf("Initial values |%f |%d |%c |%lf\n", num1, num2, ch, data);
printf("Enter a real, number, char, double\n");
scanf("%f %d %c %lf", &num1, &num2, &ch, &data);
printf("Initial values %f %d %c %.2lf\n", num1, num2, ch, data);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 28
Quick exercise for class
• Find the sum of natural number up to 10.
• Write a C program that takes the basic salary, Dearness Allowance (DA), and House Rent
Allowance (HRA) as input, adds them together to calculate the total monthly salary, and then
displays the result.
• Calculate the area of a circle.
11/6/2025 PALASH@IIT JODHPUR 29
11/6/2025 PALASH@IIT JODHPUR 30
Command line argument (User input)
#include<stdio.h>
#include<stdlib.h>
int main (int argc, char **argv)
{
int sum = 0;
printf("You have entered %d arguments\n", argc);
printf("You have entered %s\n", argv[0]);
printf("You have entered %s\n", argv[1]);
printf("You have entered %s\n", argv[2]);
sum = atoi(argv[1]) + atoi(argv[2]);
printf("The sum is %d\n", sum);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 31
Quick exercise for class
1. Write a C program that takes two integers from the command line, swaps them, and prints
the swapped values.
2. Write a C program that takes two integers from the command line, swaps them without
using a third variable, and prints the swapped values.
3. Write a C program that accepts three integers as command line arguments and prints their
average using integer division.
11/6/2025 PALASH@IIT JODHPUR 32
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
int a, b, temp; int a, b;
// Convert command line arguments to integers // Convert command line arguments to integers
a = atoi(argv[1]); a = atoi(argv[1]);
b = atoi(argv[2]); b = atoi(argv[2]);
// Swap using a temporary variable // Swap without using a third variable
temp = a; a = a + b;
a = b; b = a - b;
b = temp; a = a - b;
// Print swapped values // Print swapped values
printf(“a=%d b=%d\n", a, b); printf(“a=%d b=%d\n", a, b);
return 0; return 0;
} }
11/6/2025 PALASH@IIT JODHPUR 33
#include <stdio.h>
#include <stdlib.h> The key point: the counting happens before your program
even runs. The compiler doesn’t do it — the OS does.
int main(int argc, char *argv[]) {
int a, b, c;
// Convert three command line arguments to integers
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
// Average using integer division
printf("a = %d, b = %d, c = %d, argc = %d\n", a, b, c, argc);
printf("the average is = %d\n", (a + b + c) / (argc-1));
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 34
Operators in C
Operators are used to perform operations on variables and values.
increments/ decrements the values by 1
mathematical operations such as add, sub, etc.
checks the relationship between two operands
An expression containing logical operator returns either 0 or 1
depending upon whether expression results true or false.
Performs bit-level operations
Unary operator that returns the size of data
Assignment operator is used for assigning a value to a variable
11/6/2025 OS @ PALASH | IIT JODHPUR 35
#include <stdio.h>
Increment/Decrement
Operators
int main() {
int a = 5, b;
printf("Initial value of a = %d\n\n", a);
// Post-increment: value is used first, then incremented
b = a++;
printf("After b = a++:\n");
printf("a = %d, b = %d\n\n", a, b);
// Reset a
a = 5;
// Pre-increment: value is incremented first, then used
b = ++a;
printf("After b = ++a:\n");
printf("a = %d, b = %d\n", a, b);
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 36
Issues
#include <stdio.h> #include <stdio.h>
int main() { int main() {
int a = 5; int a = 5, b;
printf("a++ = %d, a = %d, ++a = %d\n", a++, a, ++a); a = a++;
printf("%d\n", a);
return 0; }
}
11/6/2025 PALASH@IIT JODHPUR 37
#include <stdio.h>
int main() { Arithmetic Operators
int a, b;
// Input two numbers
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
// Arithmetic operations
printf("\nArithmetic Operations:\n");
printf("%d + %d = %d\n", a, b, a + b); // Addition
printf("%d - %d = %d\n", a, b, a - b); // Subtraction
printf("%d * %d = %d\n", a, b, a * b); // Multiplication
printf("%d / %d = %d\n", a, b, a / b); // Division (integer division)
printf("%d %% %d = %d\n", a, b, a % b); // Modulus (remainder)
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 38
Relational Operator
#include <stdio.h>
int main() {
int a = 10, b = 20;
printf("a = %d, b = %d\n\n", a, b);
// Relational operators
printf("a == b : %d\n", a == b); // Equal to
printf("a != b : %d\n", a != b); // Not equal to
printf("a > b : %d\n", a > b); // Greater than
printf("a < b : %d\n", a < b); // Less than
printf("a >= b : %d\n", a >= b); // Greater than or equal to
printf("a <= b : %d\n", a <= b); // Less than or equal to
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 39
#include <stdio.h>
int main() {
Assignment
int a = 10, b = 3;
printf("Initial values: a = %d, b = %d\n\n", a, b); (shorthand) Operators
a += b; // a = a + b
printf("After a += b → a = %d\n", a);
a -= b; // a = a - b
printf("After a -= b → a = %d\n", a);
a *= b; // a = a * b
printf("After a *= b → a = %d\n", a);
a /= b; // a = a / b
printf("After a /= b → a = %d\n", a);
a %= b; // a = a % b
printf("After a %%= b → a = %d\n", a);
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 40
Ternary Operators
#include <stdio.h>
int main() {
int num = 10;
// Check if number is even or odd using ternary operator
(num % 2 == 0) ? printf("%d is Even\n", num) : printf("%d is Odd\n", num);
return 0;
}
The ternary operator is a three-operand operator (?:) that evaluates a condition and
returns one of two values depending on whether the condition is true or false.
11/6/2025 PALASH@IIT JODHPUR 41
Quick exercise for class
Write a C program to find the maximum of three numbers using ternary
operator.
11/6/2025 PALASH@IIT JODHPUR 42
#include <stdio.h>
int main() {
int a, b, c, max;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
// Using ternary operator to find maximum
max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
printf("The maximum number is: %d\n", max);
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 43
sizeof Operator
#include <stdio.h> The sizeof operator in C returns the size in bytes of a data type or a variable.
Its return type is size_t (an unsigned integer type).
int main() { The size depends on the system and compiler.
int a; When you use it with a variable or expression, parentheses are optional
double b; (unless needed for precedence):
char c; %zu is used for size_t return type.
printf("Size of int = %zu bytes\n", sizeof(int));
printf("Size of a = %zu bytes\n", sizeof a); //show a+1, (a+1)
printf("Size of double = %zu bytes\n", sizeof(b));
printf("Size of char = %zu bytes\n", sizeof(c));
//printf("Size of pointer to int = %zu bytes\n", sizeof(int*));
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 44
Bitwise Operators
Operator Symbol Meaning
AND & Sets bit to 1 if both bits are 1
Sets bit to 1 if at least one bit is
OR |
1
XOR ^ Sets bit to 1 if bits are different
NOT ~ Flips all bits (1→0, 0→1)
Left Shift << Shifts bits left (×2 per shift)
Right Shift >> Shifts bits right (÷2 per shift)
11/6/2025 PALASH@IIT JODHPUR 45
#include <stdio.h>
int main() {
unsigned int a = 5; // 0101 in binary
unsigned int b = 9; // 1001 in binary
printf("a = %u, b = %u\n", a, b);
// AND (&)
printf("a & b = %u\n", a & b); // 0101 & 1001 = 0001 (1)
// OR (|)
printf("a | b = %u\n", a | b); // 0101 | 1001 = 1101 (13)
// XOR (^)
printf("a ^ b = %u\n", a ^ b); // 0101 ^ 1001 = 1100 (12)
// NOT (~)
printf("~a = %u\n", ~a); // Bitwise negation
// Left Shift (<<)
printf("a << 1 = %u\n", a << 1); // 0101 << 1 = 1010 (10)
// Right Shift (>>)
printf("b >> 1 = %u\n", b >> 1); // 1001 >> 1 = 0100 (4)
}
11/6/2025 PALASH@IIT JODHPUR 46
Control Statements
Allow different sets of instructions to be executed depending on whether certain
conditions is evaluated to be true or false.
Also called branching.
A Condition can an expression
◦ Expression = non-zero value ---> True
◦ Expression = Zero value ------> False
Syntax
if(expression)
{
//code to be executed
}
11/6/2025 OS @ PALASH | IIT JODHPUR 47
If-else: Control Statements (Cont.…)
Syntax
if(expression)
{
//Statements
}
else
{
//Statements
}
• IF without a else is possible.
• Else without a if is not possible. simpleif1.c
11/6/2025 OS @ PALASH | IIT JODHPUR 48
#include <stdio.h>
int main() { #include <stdio.h>
int number;
printf("Enter a number: "); int main() {
scanf("%d", &number); int age;
// Check if number is positive printf("Enter your age: ");
if (number > 0) { scanf("%d", &age);
printf("The number is positive.\n");
} if (age >= 18) {
// Check if number is negative printf("You are eligible to vote.\n");
if (number < 0) { } else {
printf("The number is negative.\n"); printf("You are not eligible to vote yet.\n");
} }
// Check if number is zero
if (number == 0) { return 0;
printf("The number is zero.\n"); }
}
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 49
Nested if-else: Control Statements
(Cont.…)
if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{
statement-block 3;
} Any levels of nested if-else is possible.
11/6/2025 OS @ PALASH | IIT JODHPUR 50
if-else-if ladder: Control Statements
(Cont.…)
if(condition1)
{
//statements
}
else if(condition2)
{
//statements
}
else if(condition3)
{
//statements
}
else
{
//statements
} ***Dangling else problem
11/6/2025 OS @ PALASH | IIT JODHPUR 51
Difference
11/6/2025 PALASH@IIT JODHPUR 52
Quick exercise for class
Input a 3-digit number. Check whether it is a palindrome.
Write a program to check whether a given year is a leap year or not.
Input a character and check whether it is a vowel or a consonant.
11/6/2025 PALASH@IIT JODHPUR 53
#include <stdio.h>
int main() {
int num, first, last;
#include <stdio.h>
printf("Enter a 3-digit number: ");
scanf("%d", &num); int main() {
int year;
if(num < 100 || num > 999) { printf("Enter a year: ");
printf("Not a 3-digit number!\n"); scanf("%d", &year);
} else {
first = num / 100; // first digit if((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
last = num % 10; // last digit printf("%d is a Leap Year.\n", year);
} else {
if(first == last) { printf("%d is NOT a Leap Year.\n", year);
printf("%d is a Palindrome number.\n", num); }
} else {
printf("%d is NOT a Palindrome number.\n", num); return 0;
} }
}
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 54
#include <stdio.h>
#include <stdio.h>
#include <ctype.h> // for isalpha()
int main() {
char ch;
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
printf("Enter a character: ");
scanf("%c", &ch);
// check if vowel
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' ||
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' ||
ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') {
ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') {
printf("%c is a Vowel.\n", ch);
printf("%c is a Vowel.\n", ch);
}
}
// check if alphabet using ASCII ranges
else if(isalpha(ch)) {
else if((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) {
printf("%c is a Consonant.\n", ch);
printf("%c is a Consonant.\n", ch);
}
}
else {
else {
printf("%c is not an alphabet.\n", ch);
printf("%c is not an alphabet.\n", ch);
}
}
return 0;
return 0;
}
}
11/6/2025 PALASH@IIT JODHPUR 55
11/6/2025 PALASH@IIT JODHPUR 56
#include <stdio.h> #include <stdio.h>
int main() { int main() {
char ch; int ascii;
printf("Enter a character: "); printf("Enter an ASCII value (0-127): ");
scanf("%c", &ch); scanf("%d", &ascii);
printf("The ASCII value of %c is %d\n", ch, ch); printf("The character for ASCII %d is %c\n", ascii, ascii);
return 0; return 0;
} }
11/6/2025 PALASH@IIT JODHPUR 57
Some questions
If ASCII is an integer, then how can it be stored in a char (1 byte)?
If the binary for 65 (01000001) represents both the integer 65 and the character ‘A’,
how does the system distinguish between them?
11/6/2025 PALASH@IIT JODHPUR 58
Dangling Else Problem
#include <stdio.h>
#include <stdio.h>
int main() {
int main() { int x = -5, y = 10;
int x = -5, y = 10;
if (x > 0) {
if (x > 0) if (y > 0)
if (y > 0) printf("Both positive\n");
printf("Both positive\n"); }
else else
printf("x is not positive\n"); // Dangling else confusion printf("x is not positive\n"); // Dangling else confusion
return 0; return 0;
} }
In C, an else always binds to the nearest unmatched if. To avoid confusion, use braces {}.
11/6/2025 PALASH@IIT JODHPUR 59
Loops in C
Loop is used to execute the block of code several times according to the condition given in the
loop.
while
for
do-while
11/6/2025 OS @ PALASH | IIT JODHPUR 60
main ()
while loop {
int i = 0; // initialization
while (i < 5)
{
printf (“hi ”);
Why do we need a loop? Syntax i++; // increment or decrement
I want to print “hi” 5 times…. }
while(condition) {
main () statement(s); }
{ }
printf (“hi ”); main ()
printf (“hi ”); {
printf (“hi ”); int i = 5; // initialization
printf (“hi ”); while (i > 0)
printf (“hi ”); A smart solution {
could be printf (“hi ”);
} i--; // increment or decrement
}
11/6/2025 OS @ PALASH | IIT JODHPUR 61
int main ()
{
int i = 1, n, sum = 0, mul = 1;
printf ("Enter the range:");
While loop scanf("%d", &n);
printf("\nThe series is = ");
/*while (i <= n)
{
printf("%d ", i);
sum = sum + i;
mul = mul * i;
i += 2;
}*/
while (i <= n)
{
if (i%2 == 1){
printf("%d ", i);
sum = sum + i;
mul = mul * i;
//i++;
}
i++; // what if I put it in if ?
}
printf("\nThe sum and mul is : %d %d\n", sum, mul);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 62
Try to solve it
Some of the digits of a number.
11/6/2025 PALASH@IIT JODHPUR 63
While loop
int main()
{
int num = 0, sum = 0, rem;
printf("Enter a number greater than 0:");
scanf("%d", &num);
while(num != 0)
{ rem = num % 10;
printf("%d ", rem);
num = num / 10;
sum = sum + rem;
}
printf("The sum of digits is : %d\n", sum);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 64
Print the following two patterns
11/6/2025 PALASH@IIT JODHPUR 65
void main()
{
int i=0, j=0, n, c=1;
While loop printf("Enter the number of lines:");
scanf("%d", &n);
while(i < n)
{
while (j <= i)
{
printf("* ");
//printf("%d ", c);
//c++;
j++;
}
printf("\n");
j=0;
i++;
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 66
Homework (Line number is user input)
11/6/2025 PALASH@IIT JODHPUR 67
Quick exercise for class
Write a C program that takes an integer input from the user and reverses its digits using a
while loop. The program should repeatedly extract the last digit of the number, build the
reversed number, and finally display it.
11/6/2025 PALASH@IIT JODHPUR 68
#include <stdio.h>
int main() {
int num, reversed = 0, remainder;
printf("Enter a number: ");
scanf("%d", &num);
while (num != 0) {
remainder = num % 10; // get last digit
reversed = reversed * 10 + remainder; // build reversed number
num = num / 10; // remove last digit
}
printf("Reversed number = %d\n", reversed);
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 69
for loop
Syntax:
for (initialization; test Expression; increment/decrement)
{
// statements inside the body of loop
}
11/6/2025 OS @ PALASH | IIT JODHPUR 70
for
int main()
{
int i;
for (i = 1; i< 10; i++) // design loop differently, remove each and all ;
{
printf("%d\n", i);
}
printf ("\n");
}
11/6/2025 OS @ PALASH | IIT JODHPUR 71
void main()
{
// declare the local variables
int i, j, rows, k, m = 0;
printf (" Enter a number to define the rows: \n");
scanf ("%d", &rows);
printf("\n");
for ( i = rows; i >= 1; i--)
{
for ( j = 1; j <= m; j++)
{
printf (" "); // print the space
}
for ( k = 1; k <= (2 * i - 1); k++)
{
printf ("* "); // print the Star
}
m++;
printf ("\n");
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 72
Back to control statements: Switch case
switch (expression) • The switch statement allows us to execute one code block
{ among many alternatives.
case constant1:
// statements • You can do the same thing with the if...else..if ladder.
break; However, the syntax of the switch statement is much easier
to read and write.
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
11/6/2025 OS @ PALASH | IIT JODHPUR 73
Switch code void main()
{
int day = 0;
printf("Enter the day in integer\n");
scanf("%d", & day);
switch (day) {
What is the output? case 1:
printf("Sunday\n");
printf(":)\n");
case 2:
printf("Monday\n");
printf(":'(\n");
How is it different from if-else? case 3:
printf("Tuesday\n");
printf(":(\n");
case 4:
printf("Wednesday\n");
printf(":(\n");
case 5:
printf("Thursday\n");
printf(":|\n");
case 6:
printf("Friday\n");
printf(":D\n");
case 7:
printf("Saturday\n");
printf(":D\n");
default:
printf(“Invalid input!!!");
Default can be placed
} anywhere in the sequence
}
11/6/2025 OS @ PALASH | IIT JODHPUR 74
void main() {
int day = 0;
printf("Enter the day in integer\n");
scanf("%d", & day);
switch (day) {
case 1:
printf("Sunday\n");
printf(":)\n");
break;
The break is a keyword in C.
case 2:
printf("Monday\n");
printf(":'(\n");
break;
case 3:
printf("Tuesday\n");
printf(":(\n");
break;
case 4:
printf("Wednesday\n");
printf(":(\n");
break;
case 5:
printf("Thursday\n");
printf(":|\n");
break;
case 6:
printf("Friday\n");
printf(":D\n");
break;
case 7:
printf("Saturday\n");
printf(":D\n");
break;
default:
printf(“Invalid input!!!");
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 75
char operation;
int main() { double n1, n2;
switch(operation) printf("Enter an operator (+, -, *, /): ");
{ scanf("%c", &operation);
case '+': printf("Enter two operands: ");
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2); scanf("%lf %lf",&n1, &n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! operator is not correct");
}
return 0;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 76
void main()
{
char day;
printf("Enter the day in integer\n");
scanf("%c", & day);
switch (day)
{
case 'A':
printf("Sunday\n");
break;
case 'B':
printf("Monday\n");
break;
case 'C':
printf("Tuesday\n");
break;
case 'D':
printf("Wednesday\n");
break;
case 'E':
printf("Thursday\n");
break;
case 'F':
printf("Friday\n");
break;
case 'a':
printf("Saturday\n"); Can I make it ‘A’ ?
break;
default:
printf("Invalid input!!!");
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 77
void main()
{
int day = 0;
printf("Enter the day in integer\n");
scanf("%d", & day);
switch (day)
{ What about placing a variable here?
case day:
printf("Sunday\n");
break;
case day:
printf("Monday\n");
break;
case day:
printf("Tuesday\n");
break;
case day:
printf("Wednesday\n");
break;
case day:
printf("Thursday\n");
break;
case day:
printf("Friday\n");
break;
case day:
printf("Saturday\n");
break;
default:
printf("Invalid input!!!");
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 78
int main()
{
int day = 6; Is the sequence important?
switch (day) { What is the output?
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
default:
printf("Looking forward to the Weekend");
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 79
void main()
{
int day = 2;
switch () {
case 1: What is the output?
printf("Monday");
case 2:
printf("Sunday");
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 80
#include <stdio.h>
void main()
{ What is the output?
int a=10;
switch(a){
case 5+5:
printf("Hello\n");
default:
printf("OK\n");
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 81
int main() {
int a = 7, b = 3, c = 2;
// Complicated expression inside switch
switch ((a * b) % 5 + (c << 2)) {
case 0:
printf("Case 0: Exact match\n");
break;
case 4:
printf("Case 4: (a*b) mod 5 + (c<<1) = 4\n");
break;
case 6:
printf("Case 6: Got 6\n");
break;
case 8:
case 9:
printf("Case 8 or 9: Multiple matches\n");
break;
default:
printf("Default: No exact match\n");
}
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 82
break vs. continue (both are keywords)
int main() 000 int main() 0000
{ 012 { 0124
int i, j; 024 int i, j; 0248
036 0 3 6 12
for (i = 0; i < 5; i++) 048 for (i = 0; i < 5; i++) 0 4 8 16
{ {
for (j = 0; j < 5; j++) for (j = 0; j < 5; j++)
{ {
if(j == 3) if(j == 3)
break; continue;
printf("%d ", i * j); printf("%d ", i * j);
} }
printf("\n"); printf("\n");
} }
return 0; return 0;
} }
11/6/2025 OS @ PALASH | IIT JODHPUR 83
Tell me the outputs int main()
int main()
{
int i = 0; int i = 0;
{
int i = 0;
while (i < 10) {
if (i == 4) { while (i < 10) {
break;
while (i < 10) { if (i%2==0){
}
printf("%d\n", i); ++i;
if (i%2==0) continue;
i++;
continue; }
}
printf ("%d ", i); printf ("%d ", i);
i++; i++;
} }
break doesn’t belong to if.
return 0; return 0;
It only affects loops (for, while, do-while) and switch.
} }
11/6/2025 OS @ PALASH | IIT JODHPUR 84
Back to loop: do-while
Syntax #include <stdio.h>
do { int main ()
statement(s); {
} while( condition ); int i = 1;
Do not forget
do{
printf("hi\n");
i++;
}while (i<=5);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 85
Back to loop: do-while
11/6/2025 OS @ PALASH | IIT JODHPUR 86
When should I prefer do-while over while?
Write a program which allows users to enter an integer until a zero value is pressed.
int main()
int main()
{ {
int n; int n;
printf("Enter an integer: ");
do
scanf("%d", &n); {
Same code?? printf("Enter an integer\n");
while (n != 0)
scanf("%d", &n);
{ } while (n != 0);
printf("Enter an integer\n");
printf("Program ended");
scanf("%d", &n); }
}
printf("Program ended"); Think about the situation where loop body needs to be executed
} at least once and then you need to check condition…….
11/6/2025 OS @ PALASH | IIT JODHPUR 87
Array
What if we try to store more
Elements than 4?
void main()
In GCC, warning with garbage.
{
Output may change based on
int a[4] = {10, 21, 4 , 0}; // declaring and initializing an array
Compilers.
C does not give error, so be careful.
a[2] = 18;
Array bounds are not checked.
printf ("%d\n", a[0]);
printf ("%d\n", a[1]); If we remove the highlighted part,
printf ("%d\n", a[2]); What is the output?
printf ("%d\n", a[3]);
}
In C, always stay within the bounds of the array (0 to size-1). Anything
beyond that is undefined behavior.
11/6/2025 OS @ PALASH | IIT JODHPUR 88
Tell me the output
void main()
float a[4] = {10.3, 21, 4 , 0}; // declaring and initializing an array
a[2] = 18;
printf ("%lf\n", a[0]);
printf ("%lf\n", a[1]);
printf ("%lf\n", a[2]);
printf ("%lf\n", a[3]);
11/6/2025 OS @ PALASH | IIT JODHPUR 89
Accessing an Arrays in reverse order using loop
void main ()
{
int n, A[100], i;
printf("How many numbers to read?");
scanf("%d", &n);
for (i = 0; i < n; ++i) Why is the loop convenient?
scanf("%d", &A[i]);
for (i = n -1; i >= 0; --i)
printf("%d ", A[i]); Is the array also changed in the
memory?
printf("\n");
}
11/6/2025 OS @ PALASH | IIT JODHPUR 90
Output ?
int main()
{ What is the difference with previous reversing?
int arr[10], i, temp; Building block used is swapping.
for (i = 0 ; i<10 ; i++)
arr[i] = i;
for(i = 0; i<10/2; i++){
temp = arr[i];
arr[i] = arr[10-i-1];
arr[10-i-1] = temp;
}
for (i = 0 ; i<10 ; i++)
printf("%d ", arr[i]);
return 0;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 91
Output??
void main()
{
int i, data[10];
for (i=0; i<10; i++)
data[i]= i;
i=0;
while (i<10)
{
printf("Data[%d] = %d\n", i, data[i]);
i++;
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 92
2D array
11/6/2025 OS @ PALASH | IIT JODHPUR 93
Methods of initializing a 2D array.
Method 1
int arr[2][3] = { Local arrays with explicit initializer
{1, 2, 3}, Uninitialized local (automatic) arrays
{4, 5, 6}
};
Method 2
int arr[2][3] = {1, 2, 3, 4, 5, 6};
Method 3
int arr[2][3] = {
{1},
{4, 5} What will happen to the missing elements?
}
11/6/2025 PALASH@IIT JODHPUR 94
int main()
{
int a [3][3] = {1, 2, 3, In memory view?
4, 5, 6, Sum of 2 matrices?
7, 8, 9}; /// Can I write it in one line. Multiplication of two matrices?
int i, j;
for(i=0 ; i< 3; i++){
for (j=0; j<3; j++){
a[i][j] = a[i][j] * 2;
}
}
for(i=0 ; i< 3; i++){
for (j=0; j<3; j++){
printf ("%d ", a[i][j]);
}
printf("\n");
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 95
Sum of matrices
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
// adding two matrices
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}
// printing the result
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 96
Quick exercises
1. Search an element in the array.
2. Transpose a matrix.
11/6/2025 PALASH@IIT JODHPUR 97
Character array
int main()
{
char a[5];
int i;
a[0] = 'H';
a[1] = 'E';
a[2] = 'L';
a[3] = 'L';
a[4] = 'O';
for (i = 0; i < 5; ++i)
{
printf("%c", a[i]);
}
return 0;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 98
No string data type is directly available
A string in C is simply:
An array of characters terminated int main()
by a special character '\0' (null {
character). char a[5];
int i;
That '\0' at the end is what tells the a[0] = 'H';
compiler and standard library functions a[1] = 'E';
(like printf, strlen, etc.) where the a[2] = 'L';
string ends. a[3] = 'L';
a[4] = 'O';
special null character, denoted by '\0' a[5] = '\0'; //This should be explicitly inserted to treat it like a string
for (i = 0; i < 5; ++i)
{
printf("%c", a[i]);
}
printf("\n%c",a[i]);
printf("\n%s", a);
return 0;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 99
int main()
{
char a[6]="hello"; // make it 6 for safe side.
char b[] = "Welcome IITJ students"; // This is also possible
printf("%s\n", a);
printf("%s\n", b);
return 0;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 100
Output?
int main()
{
char b[] = "Welcome IITJ Students";
int count = 0,i = 0;
while (b[i] != '\0')
{
if(b[i] == 'S' || b[i] == 's')
count++;
i++;
}
printf("count: %d\n", count);
return 0;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 101
String library int main()
<string.h> {
char b[] = "Welcome IITJ Students";
char a[50], c[50];
int count = 0,i = 0;
count = strlen(b);
printf("The length is : %d\n", count);
for (i = 0; i < count; ++i)
{
a[i] = b[i];
}
a[i] = '\0';
strcpy(c, b); // (des, src);
if(strcmp(a, c) == 0)
printf("Both same\n");
return 0;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 102
Can we compare strings like this?
int main()
{
char s1[] = "This is IIT J.";
char s2[] = "This is IIT J.";
if (s1 == s2)
printf("Equal\n");
else
printf("Not Equal");
}
11/6/2025 OS @ PALASH | IIT JODHPUR 103
American Standard Code for Information
Interchange (ASCII)
int main()
{
// A = 65
// a = 97
// space = 32
// 0 = 48
char a[]="Aa 0";
for (int i = 0; i < 4; ++i)
{
printf("%d\n", a[i]);
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 104
String library <string.h>
int main()
{
char s1[] = "This is IIT J.";
char s2[] = "This ia IIT J.";
if(strcmp(s1, s2) == 0)
printf("Equal\n");
else if(strcmp(s1, s2) < 0)
printf("s1 < s2\n");
else if(strcmp(s1, s2) > 0)
printf("s1 > s2\n");
}
11/6/2025 OS @ PALASH | IIT JODHPUR 105
#include<string.h>
int main()
{
char src [11] = "1Abcde7890";
char dest1[50], dest2[5], dest3[50], dest4[50], dest5;
strcpy(dest1, src);
printf("dest1: %s\n", dest1);
strcpy(dest2, src); // working but will avoid for other compilers
printf("dest2: %s\n", dest2);
strncpy(dest3, src, 5);
dest3[5] = '\0'; /// might not need but it is safer to ensure with \0
printf("dest3: %s\n", dest3);
strncpy(dest4, src, 40); // will print up to null
printf("dest4: %s\n", dest4);
11/6/2025 OS @ PALASH | IIT JODHPUR 106
3D Array
Multidimensional arrays
11/6/2025 OS @ PALASH | IIT JODHPUR 107
A few quick problems on array
Write a program in C to find the sum of all elements of the array.
Write a program in C to count the total number of duplicate elements in an
array.
Write a program in C to print all unique elements in an array.
Write a program in C to count the frequency of each element of an array.
Write a program in C to find the maximum and minimum elements in an array.
Write a program in C to find the second largest element in an array.
Write a program in C to find the second smallest element in an array.
Write a program in C to find the sum of the right diagonals of a matrix.
Sorting an array.
11/6/2025 OS @ PALASH | IIT JODHPUR 108
Practice problems
1. Take a string reverse it.
2. Take two strings and concatenate them.
3. Count the number of words in a line.
4. Find substring in a string.
11/6/2025 PALASH@IIT JODHPUR 109
11/6/2025 PALASH@IIT JODHPUR 110
11/6/2025 PALASH@IIT JODHPUR 111
11/6/2025 PALASH@IIT JODHPUR 112
11/6/2025 PALASH@IIT JODHPUR 113
11/6/2025 PALASH@IIT JODHPUR 114
Function
A function is a group of statements that together perform a task.
◦ Library Function e.g. scanf, printf.
◦ User defined function (You need to make for various purpose).
Reuse of codes
How can you create your own function?
Declarations
Definition
Calling the function
11/6/2025 OS @ PALASH | IIT JODHPUR 115
A general way of creating your own function
#include<stdio.h> A function declaration tells the compiler about a function's name,
return type, and parameters.
int show(); //Declaration
void main ()
{
printf("I am from main\n");
show(); // Calling the function The result of function body will be placed from the place of call.
printf("I am back to main\n");
}
int show() // Definition A function definition provides the actual body of the function.
{
printf("Hi! all\n");
return 0;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 116
Parts of a Function
Return Type:
The return type is the data type of the value that the function returns to the caller. If a function
doesn’t return any value, its return type is void.
Function Name:
This is the actual name of the function, used to identify and call it in the program.
Parameters / Arguments:
Parameters are placeholders (variables) defined in the function declaration/definition to accept
input.
Arguments are the actual values passed to those parameters when the function is called.
Function Body:
The function body is the block of statements enclosed in { } that define what the function does —
i.e., the actual logic or task it performs.
11/6/2025 OS @ PALASH | IIT JODHPUR 117
A few ways of creating a function
1. No Argument Passed and No Return Value
2. No Arguments Passed but Returns a Value
3. Argument Passed but No Return Value
4. Argument Passed and Returns a Value
11/6/2025 OS @ PALASH | IIT JODHPUR 118
void sum (); void sum (int, int); int sum (int, int);
int main() int main()
{ { int main()
printf("From main\n"); int a, b, c; {
printf("From main\n"); int a, b, c;
sum(); scanf("%d %d", &a, &b); printf("From main\n");
sum(a, b); Arguments scanf("%d %d", &a, &b); Are these 2
printf("Back in main\n"); printf("Back in main\n"); c = sum(a, b); variables
return 0; return 0; printf("Back in main\n"); same ?
} } printf("The sum is %d", c);
void sum () return 0;
{ void sum (int x , int y) }
int a, b, c; { int sum (int x , int y)
int c; Parameters {
scanf("%d %d", &a, &b); c = x + y; int c;
c = a + b; printf("The sum is %d\n", c); c = x + y;
printf("The sum is %d\n", c); } return c;
} }
Local vs. Global variable
11/6/2025 OS @ PALASH | IIT JODHPUR 119
float sum (int, float);
int main()
{
• Can I call a function multiple times?
int a;
• Can I use loop to call a function?
float b, c;
• Parameter list can have more than 2
printf("From main\n");
parameters.
scanf("%d %f", &a, &b);
c = sum(a, b);
printf("Back in main\n");
printf("The sum is %f", c);
return 0;
}
float sum (int x , float y)
{
return x + y;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 120
Output?
void test (void); #include <stdio.h> void test (void);
int main() void test (void); int a = 6;
{ int a; int main()
int a = 5; int main() {
test(); { int a = 5;
} int a = 5; printf("%d\n", a);
void test () printf("%d\n", a); test ();
{ test ();
printf("%d", a); }
} } void test ()
void test () {
{ printf("%d\n", a);
printf("%d\n", a); }
}
11/6/2025 OS @ PALASH | IIT JODHPUR 121
Output? void test (void);
void test1 (void);
void test (void);
void test1 (void);
void test (void);
void test1 (void);
int test2 (); int test2 (); int test2 ();
int main() int main() int main()
{ { {
printf("I am main\n"); printf("I am main\n"); printf("I am main\n");
test(); test(); test();
printf("Back in main\n"); printf("Back in main\n"); printf("Back in main\n");
} } }
void test () void test () void test ()
{ { {
test1(); test1(); test1();
printf("I am test\n"); test2(); printf("I am test\n");
} printf("I am test\n"); }
void test1 () } void test1 ()
{ void test1 () {
test2(); { test2();
printf("I am test1\n"); printf("I am test1\n"); printf("I am test1\n");
} } }
int test2 () int test2 () int test2 ()
{ { {
printf("I am test2\n"); printf("I am test2\n"); main();
return 0; return 0; printf("I am test2\n");
} } return 0;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 122
Output?
void test (void);
void test (void);
int main()
int main()
{
{
printf("I am main\n");
printf("I am main\n");
test();
test();
main();
printf("Back in main\n");
printf("Back in main\n");
}
}
void test ()
void test ()
{
Do not {
printf("I am test\n");
forget!!! It is a printf("I am test\n");
test();
recursion. }
}
Quick exercise using a function:
Min-Max
Fact
Sum up to a range
11/6/2025 OS @ PALASH | IIT JODHPUR 123
Output?
11/6/2025 OS @ PALASH | IIT JODHPUR 124
Scopes of the variables
int main() {
int n1; // n1 is a local variable to main() Local variable void display();
printf("%d", n2);
int n = 5; // global variable
}
int main()
void func() {
{
int n2; // n2 is a local variable to func() ++n;
display();
printf("%d", n1);
int main () printf("n = %d", n);
} { return 0;
{ }
int main () int a = 5;
{ } void display()
for (int i = 0; i < 5; ++i) printf("%d\n", a); {
{ } ++n;
} printf("n = %d", n);
printf("%d\n", i); }
}
11/6/2025 OS @ PALASH | IIT JODHPUR 125
Every variable in C programming has two
properties: type and storage class.
Type refers to the data type of a variable. And storage class determines the scope, visibility and lifetime of a variable.
There are 4 types of storage class:
[Link]
[Link]
[Link]
[Link]
11/6/2025 OS @ PALASH | IIT JODHPUR 126
Static storage class
int test(void); int test(void); int test(void);
int test(void);
int main() int main() int main()
static int var = 5; Optional in some sense
{ { {
printf("%d ", test()); int main() {
printf("%d ", test()); printf("%d ", test());
printf("%d ", test()); printf("%d ", test());
printf("%d ", test()); printf("%d ", test()); var--; printf("%d ", test());
return 0; return 0; printf("%d ", var); var--;
} } return 0;
printf("%d ", var);
int test() int test() }
int test() return 0;
{ {
{ }
int var = 5; static int var = 5;
static int var = 5; int test()
var--; var--; var--; {
return var; return var; return var; var--;
} } }
return var;
}
11/6/2025 Static local vs. OSStatic
@ PALASHglobal
| IIT JODHPUR 127
Extern storage class
#include<stdio.h>
#include<stdio.h>
#include"palash.h"
int main()
int main()
{ Do you see any differences?
{
extern int var; • Standard library header
extern int var;
var = 9; • User defined header
printf("%d\n", var);
printf("%d ", var); The difference between the two types is in
return 0;
} the location where the preprocessor searches
}
for the file to be included in the code.
#include<stdio.h>
#include<stdio.h> #include"palash.h"
int main() extern int sum (int, int); palash.h
{ int main()
{ int var = 20;
extern int var;
int c = 0; int sum (int a, int b)
printf("Hi");
c = sum (5, 6); {
}
printf("%d ", c); return a+b;
return 0; }
}
11/6/2025 OS @ PALASH | IIT JODHPUR 128
Register Storage Class
int main()
{
register int a = 5, c;
int b = 6;
printf("The value is %d %d %d\n", a, b,c);
printf("The address is %p\n", &a); // It is register
printf("The address is %p\n", &b); // It is in RAM
return 0;
}
Output??
Points to remember No separate slide for auto
• You can get benefit for frequently used variables. because you have unknowingly used it.
• Stored value is limited by the size of CPU register.
int a is equivalent to auto int a (try it)
11/6/2025 OS @ PALASH | IIT JODHPUR 129
Recursion
Recursion is technique in which a function calls itself directly or indirectly.
For example
int func ()
{
func();
}
11/6/2025 OS @ PALASH | IIT JODHPUR 130
How to write a recursive program?
Divide the problem into smaller sub-problems.
Specify the base condition to stop the recursion.
— it reduces the problem size in each call.
11/6/2025 OS @ PALASH | IIT JODHPUR 131
A Demonstration of Recursion
int func (int); Base Case
int main () func (1)
{
int n = 3;
printf("%d\n", func(n));
return 0; func (2)
}
int func (int n)
{ func(3)
if (n==1)
{
return 1;
} main()
else Local variables,
return 1 + func (n-1); Parameters
}
Stack Section of a Process
11/6/2025 OS @ PALASH | IIT JODHPUR 132
A basic structure of writing a recursive procedure
Func ()
{
if()
Second, write the base
{ Base Case case (will become easy)
………..
}
else
{
…………. Recursive Case First, think about this
}
11/6/2025 OS @ PALASH | IIT JODHPUR 133
1. Divide the problem into smaller problems
Can we write a generalized recursive case?
Fact(n) = n * Fact (n-1)
Tell me the base case?
11/6/2025 OS @ PALASH | IIT JODHPUR 134
Replacing the code in the basic structure
Fact (n)
{
if(n==1) Stops the recursion,
{ Base Case so no recursive call
return 1; should be here.
}
else
{
return n * Fact (n-1); Recursive Case
}
11/6/2025 OS @ PALASH | IIT JODHPUR 135
So the full code of recursive factorial is…
#include <stdio.h>
int fact(int n)
{
if(n == 1)
return 1;
else
return n*fact(n-1);
}
int main()
{
int n;
printf("Enter the number: ");
scanf("%d", &n);
printf("Factorial is %d", fact(n));
} Solve sum of natural numbers using recursion
11/6/2025 OS @ PALASH | IIT JODHPUR 136
Iterative vs. Recursive, which is more efficient?
11/6/2025 PALASH@IIT JODHPUR 137
A few important types of recursion
• Direct Recursion
• Indirect Recursion
• Tail Recursion
• Non Tail/ Head Recursion
11/6/2025 OS @ PALASH | IIT JODHPUR 138
Direct Recursion
A function is called direct recursive if it calls itself.
int func ()
{
some code
func();
some code
}
11/6/2025 OS @ PALASH | IIT JODHPUR 139
Indirect recursion
A function (lets say fun) is called indirect recursive if it calls another function (lets say fun2)
and then fun 2 calls fun directly or indirectly.
11/6/2025 OS @ PALASH | IIT JODHPUR 140
Introduction to Pointers
11/6/2025 OS @ PALASH | IIT JODHPUR 141
Introduction to Pointers
11/6/2025 OS @ PALASH | IIT JODHPUR 142
#include<stdio.h>
void main()
{
int i = 3;
printf("Address of i = %p\n", &i); Address
printf("Value of i = %d\n", i);
printf("Value of i = %d\n",*(&i));
} Value at
11/6/2025 OS @ PALASH | IIT JODHPUR 143
#include<stdio.h>
void main()
{
int i = 3;
int *j;
j = &i;
printf("Address of i = %p\n", &i);
printf("Address of i = %p\n", j);
printf("Address of j = %p\n", &j);
printf("Value of j = %p\n", j);
printf("Value of i = %d\n", i);
printf("Value of i = %d\n", *(&i));
printf("Value of i = %d\n", *j);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 144
#include<stdio.h>
void main()
{
int i = 3;
int *j, **k;
j = &i;
k = &j;
printf("Address of i = %p\n", &i);
printf("Address of i = %p\n", j);
printf("Address of i = %p\n", *k);
printf("Address of j = %p\n", &j);
printf("Address of j = %p\n", k);
printf("Address of k = %p\n", &k);
printf("Value of j = %p\n", j);
printf("Value of k = %p\n", k);
printf("Value of i = %d\n", i);
printf("Value of i = %d\n", *(&i));
printf("Value of i = %d\n", *j);
printf("Value of i = %d\n", **k);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 145
#include<stdio.h>
void main()
{
char c, *cc;
int i, *ii;
float a, *aa;
c = 'A';
i = 54;
a = 3.14;
cc = &c;
ii = &i;
aa = &a;
printf("Address of c = %p\n", cc);
printf("Address of i = %p\n", ii);
printf("Address of a = %p\n", aa);
printf("Value of c = %c\n", *cc);
printf("Value of i = %d\n", *ii);
printf("Value of a = %f\n", *aa);
printf("Address of c = %p\n", cc + 1);
printf("Address of i = %p\n", ii + 1);
Pointer arithmetic
printf("Address of a = %p\n", aa + 1);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 146
#include<stdio.h>
54 = 00000000 00000000 00000000 00110110
void main()
{ 3.14 = 01000000 01001000 11110101 11000011 (IEEE 754 32-
bit format)
int i = 54;
float a = 3.14;
char *ii, *aa; Endian-ness determines the byte order of data in memory:
little endian vs big endian
ii = (char *)&i;
aa = (char *)&a;
printf("Address of ii = %p\n", ii);
printf("Address of aa = %p\n", aa);
printf("Value at the address contained in ii = %d\n", *ii);
printf("Value at the address contained in aa = %d\n", *aa);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 147
#include<stdio.h>
void swapv(int, int);
void main()
{
int a = 10;
int b = 20;
swapv(a, b); Call by value
printf("a=%d\n",a);
printf("b=%d\n",b);
}
void swapv(int x, int y)
{
int t;
t = x;
x = y;
y = t;
printf("x=%d\n",x);
printf("y=%d\n",y);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 148
#include<stdio.h>
void swapv(int *, int *);
void main()
{
int a = 10;
int b = 20;
swapv(&a, &b); Call by Reference
printf("a=%d\n",a);
printf("b=%d\n",b);
}
void swapv(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 149
#include<stdio.h>
int calculate (int, float *, float *);
void main ()
{
int radius;
float area, perimeter; Is not the function returning two values in some sense?
printf("Enter the radius of a circle\n");
scanf("%d", &radius);
calculate(radius, &area, &perimeter);
printf("Area=%f\n", area);
printf("Perimeter=%f\n", perimeter);
}
int calculate(int r, float *a, float *p)
{
*a = 3.14*r*r;
*p = 2*3.14*r;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 150
#include<stdio.h>
int * func ();
void main ()
{
int *p;
p = func();
printf("The address is %p\n", p);
printf("The value is %d\n", *p);
}
int * func()
{
int i = 20; Won’t work as it is out of scope….
return (&i); static will increase the scope
}
11/6/2025 OS @ PALASH | IIT JODHPUR 151
#include<stdio.h>
void display (int);
void main()
{
int i;
int marks[] = {1,2,3,4,5};
for (i = 0; i < 5; ++i)
{
display (marks[i]); /// call by value
}
}
void display(int m)
{
printf("%d\n", m);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 152
#include<stdio.h>
void display (int *);
void main()
{
int i;
int marks[] = {1,2,3,4,5};
for (i = 0; i < 5; ++i)
{
display (&marks[i]); /// call by reference
}
}
void display(int *m)
{
printf("%d\n", *m);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 153
void main (){
int i=3, *x;
float j = 1.5, *y;
char k = 'c', *z;
printf("The value of i=%d\n", i);
printf("The value of j=%f\n", j);
printf("The value of k=%c\n", k);
x = &i;
y = &j;
z = &k;
printf("%lu %lu %lu\n", sizeof(i), sizeof(j), sizeof(k));
printf("The address of i=%p\n", x);
printf("The address of j=%p\n", y);
printf("The address of k=%p\n", z);
x++;
Pointer
y++;
increments
z++;
printf("The address of i=%p\n", x);
printf("The address of j=%p\n", y);
printf("The address of k=%p\n", z);
11/6/2025 OS @ PALASH | IIT JODHPUR 154
#include<stdio.h>
void main ()
{
int num[] = {1,2,3,4,5}, i = 0;
while (i < 5)
{
printf("%p\n", &num[i]);
i++; Accessing each contiguous mem. Locs.
} of an array
11/6/2025 OS @ PALASH | IIT JODHPUR 155
#include<stdio.h>
void main ()
{
int num[] = {1,2,3,4,5}, i = 0, *j;
j = num; //&num[0]
while (i < 5)
{ Accessing the whole array through a
printf("%p\n", j); single pointer
printf("%d\n", *j);
j++; Array also uses implicit pointers (I
i++; did not tell before :D)
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 156
Passing an entire array to a function
#include<stdio.h>
void display (int *, int);
int main()
{
int num [] = {1, 2, 3, 4, 5};
display (&num[0], 5); /// can be num also
return 0;
}
void display (int *x, int n)
{
int i = 0;
while(i<n)
{
printf("Address of each elements %p\n", x);
printf("Elements = %d\n", *x);
printf("-----------------\n");
i++;
x++;
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 157
#include<stdio.h>
int main()
{
int num [] = {1, 2, 3, 4, 5};
int i = 0;
while(i < 5)
{
printf("Address = %p\n", &num[i]);
printf("element = %d\n", num[i]);
printf("%d\n", *(num+i));
printf("%d\n", *(i+num));
printf("%d\n", i[num]);
i++;
printf("--------------------\n");
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 158
#include<stdio.h>
int main()
{
int s[5][2] = {
{1, 2},
{3, 4},
{5, 6},
{7, 8},
{9, 0},
};
for (int i = 0; i < 5; ++i)
{
printf("%p\n", s[i]);
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 159
#include <stdio.h>
int main() {
int s[5][2];
printf("s = %p\n", s);
printf("s + 1 = %p\n", s + 1);
printf("s[0] = %p\n", s[0]);
printf("s[0] + 1= %p\n", s[0] + 1);
printf("&s[0] = %p\n", &s[0]);
printf("&s[0]+1 = %p\n", &s[0] + 1);
}
11/6/2025 PALASH@IIT JODHPUR 160
#include<stdio.h>
void display (int *, int);
int main()
{
int s[5][2] = { Explanation: *(*(s+1)+1)
{1, 2},
{3, 40},
{5, 6},
{7, 8},
{9, 0},
}, i, j;
for (i = 0; i < 5; ++i)
{
for (j = 0; j < 2; ++j)
{
printf("%d ", *(*(s+i)+j));
}
printf("\n");
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 161
Structures
Structures are collection of heterogeneous data.
Each variable in the structure is known as a member of the structure.
You can create a structure by using the struct keyword.
struct MyStructure { // Structure declaration
int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon
11/6/2025 OS @ PALASH | IIT JODHPUR 162
#include<stdio.h> hp1 = hp; //// copy like this is possible
struct laptop //Global decleration display(dell);
{ display(hp);
int id; display(hp1);
char model[20]; printf("Size of hp1 %lu\n", sizeof(hp1));
int price; }
}; void display (struct laptop temp)
static int i = 1; {
void display (struct laptop); printf("You have entered %d\n", [Link]);
void main() printf("You have entered %s\n", [Link]);
{ printf("You have entered %d\n", [Link]);
struct laptop dell, hp, hp1; printf("---------------End of the details of laptop %d------------------\n", i);
i++;
printf("Enter the details of 1st laptop\n"); }
printf("Enter id\n");
scanf("%d", &[Link]);
printf("Enter model\n");
scanf("%s", [Link]);
printf("Enter price\n");
scanf("%d", &[Link]);
printf("Enter the details of 2nd laptop\n");
printf("Enter id\n");
scanf("%d", &[Link]);
printf("Enter model\n");
scanf("%s", [Link]);
printf("Enter price\n");
scanf("%d", &[Link]);
11/6/2025 OS @ PALASH | IIT JODHPUR 163
#include<stdio.h>
struct laptop //Global decleration
{
int id;
char model[20];
int price;
};
void main() {
struct laptop companies[5]; Array of structure variables
int i = 0;
for (i = 1; i <= 2; ++i) {
printf("Enter the details of laptop %d\n", i);
printf("Enter id\n");
scanf("%d", &companies[i].id);
printf("Enter model\n");
scanf("%s", companies[i].model);
printf("Enter price\n");
scanf("%d", &companies[i].price);
}
printf("The details are as follows\n");
for (i = 1; i <= 2; ++i) {
printf("The details of laptop %d\n", i);
printf("Id = %d\n", companies[i].id);
printf("Model = %s\n", companies[i].model);
printf("Price = %d\n", companies[i].price);
printf("--------------------------------\n");
}
}
11/6/2025 OS @ PALASH | IIT JODHPUR 164
Idea of a Void Pointer
A void pointer is a pointer that has no associated data type with it.
A void pointer can hold address of any type.
Type casting is required to access the stored values.
One use case is dynamic memory allocation.
int main()
{
int n = 10;
float f = 2.45;
void *ptr = &n;
printf("%d\n", *(int *)ptr); // type casting is must.
ptr = &f;
printf("%f\n", *(float *)ptr);
return 0;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 165
Introduction to dynamic memory
Memory allocation during compile time is called static memory allocation.
The allocated memory is fixed and can not be increased or decreased during runtime.
int main()
{
int arr[5] = {1, 2, 3, 4, 5}; //mem. allocation is compiled time and fixed
}
Either wastage of memory or out of bound may need to abnormal behavior (no bound checks
for C).
Solution is dynamic memory allocation.
The process of allocating memory at the time of execution is called dynamic memory
allocation.
DM uses the heap section of a process.
11/6/2025 OS @ PALASH | IIT JODHPUR 166
Built-in support for DM
malloc()
calloc()
realloc()
free()
11/6/2025 OS @ PALASH | IIT JODHPUR 167
malloc()
malloc() is a library function declared in the header file <stdlib.h>
It is used to dynamically allocate a single large block of contiguous memory according
to the size specified.
Syntax:
(void *) malloc(size_t size) You should typecast the return type
Allocates the memory in heap based on the size specified
On success returns a pointer pointing to the first byte (if byte addressable) of the
allocated memory, else returns NULL.
size_t is defined in <stdlib.h> as an unsigned int.
It returns void pointer because it only reserves the memory of specified size, without
caring about the data to be stored there.
11/6/2025 OS @ PALASH | IIT JODHPUR 168
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i, n;
printf("Enter the number of integers:\n");
scanf("%d", &n);
int *ptr = (int *) malloc (n *sizeof(int));
if(ptr == NULL) {
printf("Memory not available\n");
exit(1);
}
for (i = 0; i < n; ++i)
scanf("%d", ptr+i); /// ptr[i], i[ptr] will also work Do I need a & here?
printf("You have entered\n");
for (i = 0; i < n; ++i)
printf("%d ", *(ptr+i));
printf("\nYou have entered\n");
}
11/6/2025 OS @ PALASH | IIT JODHPUR 169
calloc()
calloc() function is used to dynamically allocate multiple blocks of memory.
Syntax:
void * calloc (size_t n, size_t size)
Number of blocks Size of each blocks
11/6/2025 OS @ PALASH | IIT JODHPUR 170
Example
int *ptr = (int *) calloc(10, sizeof(int));
An equivalent malloc call:
Convert the previous code using calloc
int *ptr = (int *) malloc(10*sizeof(int));
Memory allocated by calloc is initialized to zero (garbage in malloc)
Who is faster?
11/6/2025 OS @ PALASH | IIT JODHPUR 171
11/6/2025 PALASH@IIT JODHPUR 172
realloc()
realloc() function is used to change the size of the memory block without losing the old data.
Syntax:
void * realloc(previous pointer, size_t newSize)
On failure, realloc returns NULL.
New Size
Moves the contents of the old block to a new block and the old data remains there.
However, you may lose the data when the new size is smaller than the old size.
11/6/2025 OS @ PALASH | IIT JODHPUR 173
#include <stdio.h>
#include <stdlib.h>
void main(){
int i;
int *ptr = (int *) malloc (2 *sizeof(int));
if(ptr == NULL) {
printf("Memory not available\n");
exit(1);
}
printf("Enter the two numbers\n");
for (i = 0; i < 2; ++i)
scanf("%d", ptr+i); /// ptr[i], i[ptr] will also work
ptr = (int *)realloc(ptr, 4 *sizeof(int));
if(ptr == NULL) {
printf("Memory not available\n");
exit(1);
}
printf("Enter two more numbers\n");
for (i = 2; i < 4; ++i)
scanf("%d", ptr+i); /// ptr[i], i[ptr] will also work
printf("You have entered\n");
for (i = 0; i < 4; ++i)
printf("%d ", *(ptr+i));
printf("\nYou have entered\n");
}
11/6/2025 OS @ PALASH | IIT JODHPUR 174
free()
free () function is used to release the dynamically allocated memory in heap.
Syntax
void free (ptr)
The memory allocated in heap will not be released automatically after using the memory. The
space remains there and can’t be used (of course till the program is alive in main memory).
It is a good practice to free up the used part.
11/6/2025 OS @ PALASH | IIT JODHPUR 175
#include <stdio.h>
#include <stdlib.h>
int * input()
{
int *ptr, i;
ptr = (int *) malloc (5*sizeof(int));
printf("Enter 5 numbers:\n");
for (i = 0; i < 5; ++i)
scanf("%d", ptr+i);
return ptr;
}
void main()
{
int i, sum = 0;
int *ptr = input();
for (i = 0; i < 5; ++i)
sum += *(ptr+i);
printf("Sum is: %d\n", sum);
free(ptr); // releasing the memory at the end
for (i = 0; i < 5; ++i)
printf("%d\n", ptr[i]);
ptr = NULL; // we do not want dangling pointer, so it is a good practice to assign NULL
}
11/6/2025 OS @ PALASH | IIT JODHPUR 176
File handling
[Link] a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
[Link] an existing file – fopen()
[Link] from file – fscanf() or fgets()
[Link] to a file – fprintf() or fputs() A few basic operations of file handling
[Link] to a specific location in a file- fseek(), rewind()
[Link] a file – fclose()
File Pointer a very useful tool: A file pointer is a reference to a particular position in the opened file.
Syntax: FILE * pointer_name;
11/6/2025 OS @ PALASH | IIT JODHPUR 177
Modes
File opening modes or access modes specify the allowed operations on the file to be opened. A few of them are as follows.
r Opens a file in read mode -> Only reading possible. Can not create the file
if it does not exist.
w Opens or create a file in write mode -> Only writing is possible. Create the
file if it does not exist; otherwise, erase the old content of the file and
open a blank file.
a Opens a file in append mode -> Only writing is possible. Create a file; if it
does not exist, otherwise open the file and write from the end of the file.
(Do not erase the old content). Basic Modes
r+ , w+ Both r+ and w+ can read and write to a file. However, r+ doesn't delete
the content of the file and doesn't create a new file if such file doesn't
exist, whereas w+ deletes the content of the file and creates it if it doesn't
exist.
a+ Open for reading and appending (writing at end of file). The file is created
if it does not exist. The initial file position for reading is at the beginning of
the file, but output is always appended to the end of the file.
11/6/2025 OS @ PALASH | IIT JODHPUR 178
11/6/2025 OS @ PALASH | IIT JODHPUR 179
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("[Link]", "r");
if(fp == NULL)
printf("Unable to create the file\n");
else
printf("File opened successfully\n");
fclose(fp);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 180
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char data[20] = "HI! Students.";
int len = strlen(data), i;
fp = fopen("[Link]", "w");
if (fp == NULL)
printf("Unable to open the file\n");
else{
for (i = 0; i < len; ++i)
{
printf("Writing the char %c\n", data[i]);
fputc(data[i], fp);
}
printf("Data written to the file successfully\n");
}
fclose(fp);
return 0;
}
11/6/2025 OS @ PALASH | IIT JODHPUR 181
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char input[20];
fp = fopen("[Link]","a");
printf("Enter a string to write to the file\n");
//gets(input);
fgets(input, 20, stdin); /// Recommended use.
if (fp == NULL)
printf("Unable to open the file\n");
else{
fputs(input, fp);
printf("Data is successfully entered\n");
}
fclose(fp);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 182
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char name[20];
int age;
fp = fopen("[Link]","a");
printf("Enter your name\n");
fgets(name, 20, stdin);
printf("Enter your age\n");
scanf("%d", &age);
if (fp == NULL)
printf("Unable to open the file\n");
else{
fprintf(fp,"%s%d\n", name,age); /// file pointer, format specifier, list of variables
printf("Data is successfully entered\n");
}
fclose(fp);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 183
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char temp_ch;
fp = fopen("[Link]","r");
if (fp == NULL)
printf("Unable to open the file\n");
else{
while(!feof(fp))
{
temp_ch = fgetc(fp);
printf("%c", temp_ch);
}
}
fclose(fp);
}
11/6/2025 OS @ PALASH | IIT JODHPUR 184
#include <stdio.h>
int main() {
FILE *fp;
int temp_ch; // must be int to store EOF
fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("Unable to open the file\n");
return 1;
}
while ((temp_ch = fgetc(fp)) != EOF) { // read and check EOF Solution
in one step
printf("%c", temp_ch);
}
fclose(fp);
return 0;
}
11/6/2025 PALASH@IIT JODHPUR 185
Quick Practice
Put Some text in a file and count the number of vowels.
Read the characters and print the ASCIIs.
Check if there are any digit present in the file
11/6/2025 PALASH@IIT JODHPUR 186