CS1111: Problem Solving�using Computers
Rupesh Nasre.
Mentor TAs: Returaj, Akshay, Narayana, Sankaranarayanan,
Ruheena, Pranshu, Dipanshu, Deepankar, Amit
IIT Madras
November 2022
Placement in Computer Science
CS1111 is a foundational
subject feeding into all the
other CS courses.
Learning Outcomes
Problem
A
p
p
r
o
a
c
A
h
e
s
I
m
p
l
e
m
e
A
n
t
a
t
i
A
o
n
s
...
...
Our first problem: Make tea.
// how much?
// where is it?
// what if I don't have milk?
// for how long?
Even for intellectuals such as humans, we need more information.
For dumb machines such as computers, we need to be precise.
Programming is about precise understanding;
so precise that even a machine should be able to follow.
foodviva.com
Data
Algorithm
Your laptop is unlikely to be able to make tea. But then ...
Is your tea vending machine a computer?
What if it can give you tea, coffee, milk, hot water, ...?
How about a calculator?
A computer is programmable.
A vending machine or a calculator are not. They can perform only pre-programmed computation.
Then how about your iPads or smart phones?
amazon.com
computerhope.com
Week | Problems | Tools |
0 | Solve equations, find weighted sum. | Data types, expressions, assignments |
1 | Find max, convert marks to grade. | Conditionals, logical expressions |
2 | Find weighted sum for all students. | Loops |
3 | Encrypt and decrypt a secret message. | Character arrays |
4 | Our first game: Tic-tac-toe | 2D arrays |
5 | Making game modular, reuse. | Functions |
6 | Find Hemachandra/Fibonacci numbers. | Recursion |
7 | Encrypt and decrypt many messages. | Dynamic memory, pointers |
8 | Maintain student records. | Aggregate data types |
9 | Search and sort student records. | Searching and sorting algorithms |
A | Reduce memory wastage. | Linked lists |
B | Implement token system in banks. | Queues |
C | IRCTC-like ticket booking system | File handling |
D | Putting it all together | All the above |
Logistics
Logistics
To get the MOST out of this course
First Program
print “Hello World!“
A line with # indicates a preprocessor directive (such as #if, #pragma, #define).
Hello World!
#include <stdio.h>
int main() {
printf("Hello World!\n");
}
Please allow me to use printf.
Entry function
Print this to the screen when the program is executed.
This is a header file.
(check /usr/include/stdio.h)
Returns an exit code (integer) to the shell.
Formatted printing
Newline
This semicolon is required.
End of statement (like a full-stop).
() indicate arguments to the function (e.g., sin(x)).
Block or body of the function in {…}.
#include <stdio.h>
int main( )
{printf ( "Hello World!\n")
;
}
Whitespace can be added freely (almost).
Whitespace means space, tab, newline.
main(){}
Smallest C program
#include <stdio.h>
int main() {
printf("Hello World!\n");
}
A Small Problem
#include <stdio.h>
int main() {
printf("Hello World!\n");
}
Compiler
11000110
01010011
01010100
11101000
11111110
Tamil
Bengali
C
Machine code
$ gcc hello.c
$ a.out
Hello World!
$
Command to compile. Translates .c file to a.out.
Run your program (or execute it).
Output of your program.
Command prompt to type the next command.
gcc is also a big program written by many people, such as you.
So are firefox, chrome, minesweeper, powerpoint, Windows OS, Android OS, ...
#include <stdio.h>
int main() {
printf("Hello World!\n");
}
#include <stdio.h>
int main() {
printf("Bye World!\n");
}
#include <stdio.h>
int main() {
printf("printf(printf)\n");
}
#include <stdio.h>
int main() {
printf("Hello “);
printf(“World!\n");
}
#include <stdio.h>
int main() {
printf("Hello "
“World!\n“);
}
#include <stdio.h>
int main() {
printf("Hello \
World\n");
}
#include <stdio.h>
int main() {
printf("3*5 = 15\n");
}
#include <stdio.h>
int main() {
printf(3*5);
}
#include <stdio.h>
int main() {
printf(TN‘s CM);
}
3*5 = 15
Compiler issues a warning,
but compiles to a.out.
a.out prints
Segmentation fault (core dumped)
Compiler issues a warning
and an error.
What does a.out print?
We need to understand printf a little better.
printf
Placeholders, to be replaced by people.
#include <stdio.h>
int main() {
printf("3*5 = %d\n", 3*5);
}
3*5 = 15
printf here took two arguments
“3*5 = %d\n“ and 3*5
The first argument in double-quotes
is called a format-string.
This format-string is our bus without people,
but with their placeholders.
Placeholder for decimal integer.
printf
Placeholders, to be replaced by people.
#include <stdio.h>
int main() {
printf("3*5 = %d, a-z are %d letters, 5 is 50%% of %d\n", 3*5, 26, 10);
}
3*5 = 15, a-z are 26 letters, 5 is 50% of 10
printf
#include <stdio.h>
int main() {
printf("3*5 = %d, a-z are %d letters, 5 is 50%% of %d\n", 3*5, 26, 10);
}
3*5 = 15, a-z are 26 letters, 5 is 50% of 10
There are more format specifiers,
which we will study soon.
Future Connect:
printf permits variable
number of arguments.
Classwork: Find outputs.
#include <stdio.h>
int main() {
printf("3*5\n = 15\n");
}
#include <stdio.h>
int main() {
printf("3*5 = %d\n", 16);
}
#include <stdio.h>
int main() {
printf("15 is 15% of 100\n");
}
3*5
= 15
3*5 = 16
15 is 1531263471240f 100
printf
#include <stdio.h>
int main() {
printf("3*5 = %d, a-z are %d letters, 5 is 50%% of %d\n", 3*5, 26, 10);
}
There are more format specifiers,
which we will study soon.
Format specifier | Meaning |
%d | Decimal integer |
%o | Octal integer |
%c | Character |
%f | Real number |
... | ... |
Data types
Why do we need data types?
Some of these are provided by C.
Others can be created by us.
Format specifier | Meaning | C type |
| Examples |
%d | Decimal integer |
|
|
|
%o | Octal integer |
|
|
|
%c | Character |
|
|
|
%f | Real number |
|
|
|
%s | String |
| "Hello World!", "CS21B018" |
|
%p | Pointer |
| 0xFF112233 |
|
%i, %u | Similar to %d (works for positive values) | |||
%x, %X | Hexadecimal (0-9, a-f or A-F) | |||
%e,%E,%g | Similar to %f, but for scientific notation or fixed-precision | |||
%ld, %li | Long integer (larger values) | |||
%lf, %Lf | Double (long float), Long double | |||
%hi, %hu | Short integer (smaller values) | |||
%n | Number of characters printed by this printf so far. | |||
%% | Character % |
printf Format Specifiers
Hello, which course is this?
1111
Hi! Welcome to CS1111.
printf(“%s of %s\n“,
“Summer“, “69“);
printf(“%s has %d students\n“,
“CS1111“, 87);
printf(“The value of PI“);
printf(“ is %f“, 3.1428);
printf(“%d“, 3);
printf(“ idiots“);
printf(“name = %s\n“, “Khan“);
printf(“age = %d\n“, 20);
printf(“height = %lf ft\n“, 5.8);
printf(“weight is 50kg\n“);
printf(“CS%d is %s course\n“,
1111, “foundational“);
printf(“Hexadecimal has \
%X symbols.\
\n“, 16);
printf(“32 1s is %x in hex \
and %o in octal\n“,
0xFFFFFFFF, 0xFFFFFFFF);
printf(“%cS%x\n“, ‘C‘, 4369);
We need to understand printf a little better.
This was output. Does C have a capability to take input?
We want this to be typed by the user.
Hello, which course is this?
1111
Hi! Welcome to CS1111.
We want this to be typed by the user.
printf(“Hello, which course is this?\n“);
What user enters here should appear below.
printf(“Hi! Welcome to CS%d\n“, ???);
We know how to print this.
How about this?
How does our brain remember?
It stores the information in memory cells.
Can we also do the same?
But which cell to access?
Hmm... Let's name the cells.
Hello, which course is this?
1111
Hi! Welcome to CS1111.
We want this to be typed by the user.
printf(“Hello, which course is this?\n“);
What user enters is stored in cell cell1.
printf(“Hi! Welcome to CS%d\n“, cell1);
We know how to print this.
How about this?
How does our brain remember?
It stores the information in memory cells.
Can we also do the same?
But which cell to access?
Hmm... Let's name the cells.
Where is this cell1 stored?
Inside your computer.
But where?
Well, in memory.
We call it random access memory.
Hello, which course is this?
1111
Hi! Welcome to CS1111.
We want this to be typed by the user.
printf(“Hello, which course is this?\n“);
What user enters is stored in cell cell1.
printf(“Hi! Welcome to CS%d\n“, cell1);
We know how to print this.
How about this?
Where is this cell1 stored?
Inside your computer.
But where?
Well, in memory.
We call it random access memory.
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
This code doesn't compile.
gcc says it doesn't know cell1.
Let's compile and run it.
Data
Algorithm
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Hello, which course is this?
1111
Hi! Welcome to CS1111.
We want this to be typed by the user.
printf(“Hello, which course is this?\n“);
What user enters is stored in cell cell1.
printf(“Hi! Welcome to CS%d\n“, cell1);
We know how to print this.
How about this?
Where is this cell1 stored?
Inside your computer.
But where?
Well, in memory.
We call it random access memory.
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Let's compile and run it.
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Hello, which course is this?
1111
Segmentation fault (core dumped)
A New Problem
Gives some information but the painter can‘t change the color.
Allows the painter to go and change the color.
In addition, the painter can get the other information also!
Coming back to the old problem
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Informs scanf of the value in cell1, but does not allow scanf to change it.
We need to send address of cell1.
???
cell1
670, New Nandanvan
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, 670, New Nandanvan);
printf(“Hi! Welcome to CS%d\n“, cell1);
Allows the painter to go and change the color.
In addition, the painter can get the other information also!
Coming back to the old problem
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Informs scanf of the value in cell1, but does not allow scanf to change it.
We need to send address of cell1.
???
cell1
670, New Nandanvan
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, 670, New Nandanvan);
printf(“Hi! Welcome to CS%d\n“, cell1);
???
cell1
670, RAM
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, &cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Note that printf is interested in the value, and not in changing it.
What if I
pass &cell1
to printf?
What if I
I pass cell1
to scanf?
Coming back to the old problem
???
cell1
670, RAM
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, &cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Hello, which course is this?
1111
Hi! Welcome to CS1111
Hello, which course is this?
6023
Hi! Welcome to CS6023
1111
cell1
670
6023
cell1
424
passed to scanf
passed to printf
syntactic sugar
address
value
Hello, which course is this?
CS1111
Hi! Welcome to CS0
0
cell1
35213944
int year;
scanf(“%d“, &year);
printf(“%s of %d\n“,
“Summer“, year);
int nstuds;
scanf(“%d“, &nstuds);
printf(“%s has %d students\n“,
“CS1111“, nstuds);
float pi;
printf(“Value of pi?“);
scanf(“%f“, &pi);
printf(“The value of PI“);
printf(“ is %f“, pi);
short nidiots;
scanf(“%d“, &nidiots);
printf(“%d“, nidiots);
printf(“ idiots“);
int age; double height;
scanf(“%d“, &age);
printf(“age = %d\n“, age);
scanf(“%lf“, &height);
printf(“height = %lf ft\n“, height);
printf(“weight is 50kg\n“);
long int course;
scanf(“%ld“, &course);
printf(“CS%d is %s course\n“,
course, “foundational“);
int base16;
scanf(“%x“, &base16);
printf(“Hexadecimal has \
%X symbols.\
\n“, base16);
int max32;
scanf(“%x“, &max32);
printf(“32 1s is %x in hex \
and %o in octal\n“,
max32, max32);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
18
age
4315348
5.88
431534C
height
Problem: Find age from birth year.
// create cell birthyear
// take input from user in cell birthyear
// create cell age
// calculate (2022 – birthyear) and store in age.
// output age
Algorithm and Implementation
Comment
Assignment
int A, b, C;
A = 0;
b = 1 - A;
C = A - b;
float celcius, farenheit;
scanf("%f", &celcius);
farenheit = 9*celcius/5 + 32;
scanf("%d", &num);
mod5 = num % 5;
printf("%d mod 5 is %d\n",
num, mod5);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
Modulus or remainder
// create cell birthyear
int birthyear;
// take input from user in cell birthyear
scanf("%d", &birthyear);
// create cell age
int age;
// calculate (2022 – birthyear) and store in age.
age = (2022 – birthyear);
// output age
printf("Your age is %d\n", age);
0
A
1
b
-1
C
Problem: Find your team number.
// create cell for last two digits of roll number
// take input from user in cell rollnumber
// create cell for team number
// find rollnumber / 10 + 1 and store in teamnumber
// output team number
Expect last two digits alone.
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
// create cell for last two digits of roll number
int rollnumber;
// take input from user in cell rollnumber
scanf("%d", &rollnumber);
// create cell for team number
int teamnumber;
// find rollnumber / 10 + 1 and store in teamnumber
teamnumber = (rollnumber / 10 + 1);
// output team number
printf("Your team is Team %d\n", teamnumber);
15
Your team is Team 2
78
Your team is Team 8
20
Your team is Team 3
Testing helps find bugs.
teamnumber = ((rollnumber - 1) / 10 + 1);
15
Your team is Team 2
78
Your team is Team 8
20
Your team is Team 2
Given a team number, find the first and the last roll numbers in that input team.
(assume 90 students)
Extent the program for full roll number.
Problem: Find team members.
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
// create data
char teamid;
int startroll, endroll;
// take input
scanf("%c", &teamid);
// find the roll numbers
startroll = (...);
endroll = startroll + 9;
// output
printf("%d to %d\n", startroll, endroll);
A
1 to 10
I
81 to 90
C
21 to 30
Given a team id, find the first and the last roll numbers in that team.
(assume 90 students)
Characters are stored as integers.
‘A‘ is 65, ‘B‘ is 66, …
(teamid + 5) is allowed in C.
startroll = (teamid – 65) * 10 + 1;
As a good programming practice
startroll = ((int)teamid – ‘A‘) * 10 + 1;
Problem: Find endsem percentage.
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
// create data
int labs, quizzes, endsem;
// take input
scanf("%d%d", &labs, &quizzes);
// do computation
endsem = (100 – (labs + quizzes));
// output
printf("Endsem %% is %d\n", endsem);
endsem = (100 – labs – quizzes);
int nonendsem;
nonendsem = labs + quizzes;
endsem = 100 – nonendsem;
int remaining;
remaining = 100;
scanf(“%d“, &labs);
remaining = remaining – labs;
scanf(“%d“, &quizzes);
remaining = remaining – quizzes;
printf(“Endsem %% is %d\n“, remaining);
???
labs
???
quizzes
???
remaining
100
30
70
30
40
30
30
Endsem % is 40
Problem: Find sum.
int n;
// read n
scanf("%d", &n);
// compute sum
int sum = n * (n + 1) / 2;
// print sum
printf("Sum of first %d numbers is %d\n", n, sum);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
Σn = 1 + 2 + 3 + ... + n
= n * (n + 1) / 2
Σ2i = 1 + 2 + 4 + 8 + ... n terms
= 2n – 1
Needs pow() function or a loop.
pow(x, y) returns xy.
Does your code compile?
Problem: Find probability.
int nCards = 52;
int nKings = 4;
int nSpades = 13;
int nKingAndSpade = 1;
int nNonkingNonspade = nCards -
(nKings + nSpades - nKingAndSpade);
float prob = nNonkingNonspade / nCards;
printf("Probability of nonking, nonspade is %f\n",
prob);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
A card is drawn at random from a deck of well-shuffled cards. Find the probability of it being neither a king nor a spade.
Find the issue
with this code.
Problem: Find the line.
float x1, y1, x2, y2;
scanf("%f%f%f%f", &x1, &y1, &x2, &y2);
float m = (y2 – y1) / (x2 – x1);
float c = (y1 – m*x1);
printf("Equation of the line is y = %.2fx + %.2f\n", m, c);
printf("Equation of the line is y = %gx + %g\n", m, c);
printf("Equation of the line is y = %.2ex + %.2e\n", m, c);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
Given two points on a line, find its equation in y = mx + c format.
3.2 3 9.6 5
Equation of the line is y = 0.31x + 2.00
Equation of the line is y = 0.3125x + 2
Equation of the line is y = 3.12e-01x + 2.00e+00
Problem: Print tabular.
char name1[20], name2[20], name3[20];
int m11, m12, m13, m21, m22, m23, m31, m32, m33;
scanf("%s%d%d%d", &name1, &m11, &m12, &m13);
scanf("%s%d%d%d", &name2, &m21, &m22, &m23);
scanf("%s%d%d%d", &name3, &m31, &m32, &m33);
int t1, t2, t3;
t1 = m11 + m12 + m13;
t2 = m21 + m22 + m23;
t3 = m31 + m32 + m33;
printf("%-12s%5d%5d%5d = %5d\n", name1, m11, m12, m13, t1);
printf("%-12s%5d%5d%5d = %5d\n", name2, m21, m22, m23, t2);
printf("%-12s%5d%5d%5d = %5d\n", name3, m31, m32, m33, t3);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
Read names and marks of three students and print the names and total in a table.
Rajesh 1 43 43 = 87
SomeshSingh 23 55 6 = 144
JK 21 21 21 = 63
char array or string
Future Connect:
Replacing &name1 with
name1 also works.
Homework Problem: Number game.
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
Choose a number from 0..9.
Multiply by 5.
Add 3 to it.
Double it up.
Choose another number from 0..9 and add to it.
Tell me the number. I will tell you both the chosen numbers.
Computer System
limbd.org
Your files reside here.
e.g., hello.c, a.out
printf
scanf
18
age
4315348
executes a.out
Hello World!
All C Keywords
auto | break | case | char |
const | continue | default | do |
double | else | enum | extern |
float | for | goto | if |
int | long | register | return |
short | signed | sizeof | static |
struct | switch | typedef | union |
unsigned | void | volatile | while |
www.programiz.com
Summary
CS1111: Problem Solving�using Computers
Rupesh Nasre.
Mentor TAs: Ahmed, Vivek, Vimala, Akash,
Kankan, Rahul, Swati, Akshay, Ashok, Keshav
IIT Madras
May 2022
Placement in Computer Science
CS1111 is a foundational
subject feeding into all the
other CS courses.
Learning Outcomes
Problem
A
p
p
r
o
a
c
A
h
e
s
I
m
p
l
e
m
e
A
n
t
a
t
i
A
o
n
s
...
...
Our first problem: Make tea.
// how much?
// where is it?
// what if I don't have milk?
// for how long?
Even for intellectuals such as humans, we need more information.
For dumb machines such as computers, we need to be precise.
Programming is about precise understanding;
so precise that even a machine should be able to follow.
foodviva.com
Data
Algorithm
Your laptop is unlikely to be able to make tea. But then ...
Is your tea vending machine a computer?
What if it can give you tea, coffee, milk, hot water, ...?
How about a calculator?
A computer is programmable.
A vending machine or a calculator are not. They can perform only pre-programmed computation.
Then how about your iPads or smart phones?
amazon.com
computerhope.com
Week | Problems | Tools |
0 | Solve equations, find weighted sum. | Data types, expressions, assignments |
1 | Find max, convert marks to grade. | Conditionals, logical expressions |
2 | Find weighted sum for all students. | Loops |
3 | Encrypt and decrypt a secret message. | Character arrays |
4 | Our first game: Tic-tac-toe | 2D arrays |
5 | Making game modular, reuse. | Functions |
6 | Find Hemachandra/Fibonacci numbers. | Recursion |
7 | Encrypt and decrypt many messages. | Dynamic memory, pointers |
8 | Maintain student records. | Aggregate data types |
9 | Search and sort student records. | Searching and sorting algorithms |
A | Reduce memory wastage. | Linked lists |
B | Implement token system in banks. | Queues |
C | IRCTC-like ticket booking system | File handling |
D | Putting it all together | All the above |
Logistics
Logistics
To get the MOST out of this course
Takeaways
First Program
print “Hello World!“
A line with # indicates a preprocessor directive (such as #if, #pragma, #define).
Hello World!
#include <stdio.h>
int main() {
printf("Hello World!\n");
}
Please allow me to use printf.
Entry function
Print this to the screen when the program is executed.
This is a header file.
(check /usr/include/stdio.h)
Returns an exit code (integer) to the shell.
Formatted printing
Newline
This semicolon is required.
End of statement (like a full-stop).
() indicate arguments to the function (e.g., sin(x)).
Block or body of the function in {…}.
#include <stdio.h>
int main( )
{printf ( "Hello World!\n")
;
}
Whitespace can be added freely (almost).
Whitespace means space, tab, newline.
main(){}
Smallest C program
#include <stdio.h>
int main() {
printf("Hello World!\n");
}
A Small Problem
#include <stdio.h>
int main() {
printf("Hello World!\n");
}
Compiler
11000110
01010011
01010100
11101000
11111110
Tamil
Bengali
C
Machine code
$ gcc hello.c
$ a.out
Hello World!
$
Command to compile. Translates .c file to a.out.
Run your program (or execute it).
Output of your program.
Command prompt to type the next command.
gcc is also a big program written by many people, such as you.
So are firefox, chrome, minesweeper, powerpoint, Windows OS, Android OS, ...
#include <stdio.h>
int main() {
printf("Hello World!\n");
}
#include <stdio.h>
int main() {
printf("Bye World!\n");
}
#include <stdio.h>
int main() {
printf("printf(printf)\n");
}
#include <stdio.h>
int main() {
printf("Hello “);
printf(“World!\n");
}
#include <stdio.h>
int main() {
printf("Hello "
“World!\n“);
}
#include <stdio.h>
int main() {
printf("Hello \
World\n");
}
#include <stdio.h>
int main() {
printf("3*5 = 15\n");
}
#include <stdio.h>
int main() {
printf(3*5);
}
#include <stdio.h>
int main() {
printf(TN‘s CM);
}
3*5 = 15
Compiler issues a warning,
but compiles to a.out.
a.out prints
Segmentation fault (core dumped)
Compiler issues a warning
and an error.
What does a.out print?
We need to understand printf a little better.
printf
Placeholders, to be replaced by people.
#include <stdio.h>
int main() {
printf("3*5 = %d\n", 3*5);
}
3*5 = 15
printf here took two arguments
“3*5 = %d\n“ and 3*5
The first argument in double-quotes
is called a format-string.
This format-string is our bus without people,
but with their placeholders.
Placeholder for decimal integer.
printf
Placeholders, to be replaced by people.
#include <stdio.h>
int main() {
printf("3*5 = %d, a-z are %d letters, 5 is 50%% of %d\n", 3*5, 26, 10);
}
3*5 = 15, a-z are 26 letters, 5 is 50% of 10
printf
#include <stdio.h>
int main() {
printf("3*5 = %d, a-z are %d letters, 5 is 50%% of %d\n", 3*5, 26, 10);
}
3*5 = 15, a-z are 26 letters, 5 is 50% of 10
There are more format specifiers,
which we will study soon.
Future Connect:
printf permits variable
number of arguments.
Classwork: Find outputs.
#include <stdio.h>
int main() {
printf("3*5\n = 15\n");
}
#include <stdio.h>
int main() {
printf("3*5 = %d\n", 16);
}
#include <stdio.h>
int main() {
printf("15 is 15% of 100\n");
}
3*5
= 15
3*5 = 16
15 is 1531263471240f 100
printf
#include <stdio.h>
int main() {
printf("3*5 = %d, a-z are %d letters, 5 is 50%% of %d\n", 3*5, 26, 10);
}
There are more format specifiers,
which we will study soon.
Format specifier | Meaning |
%d | Decimal integer |
%o | Octal integer |
%c | Character |
%f | Real number |
... | ... |
Data types
Why do we need data types?
Some of these are provided by C.
Others can be created by us.
Format specifier | Meaning | C type |
| Examples |
%d | Decimal integer |
|
|
|
%o | Octal integer |
|
|
|
%c | Character |
|
|
|
%f | Real number |
|
|
|
%s | String |
| "Hello World!", "CS21B018" |
|
%p | Pointer |
| 0xFF112233 |
|
%i, %u | Similar to %d (works for positive values) | |||
%x, %X | Hexadecimal (0-9, a-f or A-F) | |||
%e,%E,%g | Similar to %f, but for scientific notation or fixed-precision | |||
%ld, %li | Long integer (larger values) | |||
%lf, %Lf | Double (long float), Long double | |||
%hi, %hu | Short integer (smaller values) | |||
%n | Number of characters printed by this printf so far. | |||
%% | Character % |
printf Format Specifiers
Hello, which course is this?
1111
Hi! Welcome to CS1111.
printf(“%s of %s\n“,
“Summer“, “69“);
printf(“%s has %d students\n“,
“CS1111“, 87);
printf(“The value of PI“);
printf(“ is %f“, 3.1428);
printf(“%d“, 3);
printf(“ idiots“);
printf(“name = %s\n“, “Khan“);
printf(“age = %d\n“, 20);
printf(“height = %lf ft\n“, 5.8);
printf(“weight is 50kg\n“);
printf(“CS%d is %s course\n“,
1111, “foundational“);
printf(“Hexadecimal has \
%X symbols.\
\n“, 16);
printf(“32 1s is %x in hex \
and %o in octal\n“,
0xFFFFFFFF, 0xFFFFFFFF);
printf(“%cS%x\n“, ‘C‘, 4369);
We need to understand printf a little better.
This was output. Does C have a capability to take input?
We want this to be typed by the user.
Hello, which course is this?
1111
Hi! Welcome to CS1111.
We want this to be typed by the user.
printf(“Hello, which course is this?\n“);
What user enters here should appear below.
printf(“Hi! Welcome to CS%d\n“, ???);
We know how to print this.
How about this?
How does our brain remember?
It stores the information in memory cells.
Can we also do the same?
But which cell to access?
Hmm... Let's name the cells.
Hello, which course is this?
1111
Hi! Welcome to CS1111.
We want this to be typed by the user.
printf(“Hello, which course is this?\n“);
What user enters is stored in cell cell1.
printf(“Hi! Welcome to CS%d\n“, cell1);
We know how to print this.
How about this?
How does our brain remember?
It stores the information in memory cells.
Can we also do the same?
But which cell to access?
Hmm... Let's name the cells.
Where is this cell1 stored?
Inside your computer.
But where?
Well, in memory.
We call it random access memory.
Hello, which course is this?
1111
Hi! Welcome to CS1111.
We want this to be typed by the user.
printf(“Hello, which course is this?\n“);
What user enters is stored in cell cell1.
printf(“Hi! Welcome to CS%d\n“, cell1);
We know how to print this.
How about this?
Where is this cell1 stored?
Inside your computer.
But where?
Well, in memory.
We call it random access memory.
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
This code doesn't compile.
gcc says it doesn't know cell1.
Let's compile and run it.
Data
Algorithm
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Hello, which course is this?
1111
Hi! Welcome to CS1111.
We want this to be typed by the user.
printf(“Hello, which course is this?\n“);
What user enters is stored in cell cell1.
printf(“Hi! Welcome to CS%d\n“, cell1);
We know how to print this.
How about this?
Where is this cell1 stored?
Inside your computer.
But where?
Well, in memory.
We call it random access memory.
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Let's compile and run it.
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Hello, which course is this?
1111
Segmentation fault (core dumped)
A New Problem
Give some information but the painter can‘t change the color.
Allows the painter to go and change the color.
In addition, the painter can get the other information also!
Coming back to the old problem
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Informs scanf of the value in cell1, but does not allow scanf to change it.
We need to send address of cell1.
???
cell1
670, New Nandanvan
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, 670, New Nandanvan);
printf(“Hi! Welcome to CS%d\n“, cell1);
Allows the painter to go and change the color.
In addition, the painter can get the other information also!
Coming back to the old problem
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Informs scanf of the value in cell1, but does not allow scanf to change it.
We need to send address of cell1.
???
cell1
670, New Nandanvan
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, 670, New Nandanvan);
printf(“Hi! Welcome to CS%d\n“, cell1);
???
cell1
670, RAM
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, &cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Note that printf is interested in the value, and not in changing it.
What if I
pass &cell1
to printf?
What if I
I pass cell1
to scanf?
Coming back to the old problem
???
cell1
670, RAM
int cell1;
printf(“Hello, which course is this?\n“);
scanf(“%d“, &cell1);
printf(“Hi! Welcome to CS%d\n“, cell1);
Hello, which course is this?
1111
Hi! Welcome to CS1111
Hello, which course is this?
6023
Hi! Welcome to CS6023
1111
cell1
670
6023
cell1
424
passed to scanf
passed to printf
syntactic sugar
address
value
Hello, which course is this?
CS1111
Hi! Welcome to CS0
0
cell1
35213944
int year;
scanf(“%d“, &year);
printf(“%s of %d\n“,
“Summer“, year);
int nstuds;
scanf(“%d“, &nstuds);
printf(“%s has %d students\n“,
“CS1111“, nstuds);
float pi;
printf(“Value of pi?“);
scanf(“%f“, &pi);
printf(“The value of PI“);
printf(“ is %f“, pi);
short nidiots;
scanf(“%d“, &nidiots);
printf(“%d“, nidiots);
printf(“ idiots“);
int age; double height;
scanf(“%d“, &age);
printf(“age = %d\n“, age);
scanf(“%lf“, &height);
printf(“height = %lf ft\n“, height);
printf(“weight is 50kg\n“);
long int course;
scanf(“%ld“, &course);
printf(“CS%d is %s course\n“,
course, “foundational“);
int base16;
scanf(“%x“, &base16);
printf(“Hexadecimal has \
%X symbols.\
\n“, base16);
int max32;
scanf(“%x“, &max32);
printf(“32 1s is %x in hex \
and %o in octal\n“,
max32, max32);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
18
age
4315348
5.88
431534C
height
Problem: Find age from birth year.
// create cell birthyear
// take input from user in cell birthyear
// create cell age
// calculate (2022 – birthyear) and store in age.
// output age
Algorithm and Implementation
Comment
Assignment
int A, b, C;
A = 0;
b = 1 - A;
C = A - b;
float celcius, farenheit;
scanf("%f", &celcius);
farenheit = 9*celcius/5 + 32;
scanf("%d", &num);
mod5 = num % 5;
printf("%d mod 5 is %d\n",
num, mod5);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
Modulus or remainder
// create cell birthyear
int birthyear;
// take input from user in cell birthyear
scanf("%d", &birthyear);
// create cell age
int age;
// calculate (2022 – birthyear) and store in age.
age = (2022 – birthyear);
// output age
printf("Your age is %d\n", age);
0
A
1
b
-1
C
Problem: Find your team number.
// create cell for last two digits of roll number
// take input from user in cell rollnumber
// create cell for team number
// find rollnumber / 10 + 1 and store in teamnumber
// output team number
Expect last two digits alone.
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
// create cell for last two digits of roll number
int rollnumber;
// take input from user in cell rollnumber
scanf("%d", &rollnumber);
// create cell for team number
int teamnumber;
// find rollnumber / 10 + 1 and store in teamnumber
teamnumber = (rollnumber / 10 + 1);
// output team number
printf("Your team is Team %d\n", teamnumber);
15
Your team is Team 2
78
Your team is Team 8
20
Your team is Team 3
Testing helps find bugs.
teamnumber = ((rollnumber - 1) / 10 + 1);
15
Your team is Team 2
78
Your team is Team 8
20
Your team is Team 2
Given a team number, find the first and the last roll numbers in that input team.
(assume 90 students)
Extent the program for full roll number.
Problem: Find team members.
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
// create data
char teamid;
int startroll, endroll;
// take input
scanf("%c", &teamid);
// find the roll numbers
startroll = (...);
endroll = startroll + 9;
// output
printf("%d to %d\n", startroll, endroll);
A
1 to 10
I
81 to 90
C
21 to 30
Given a team id, find the first and the last roll numbers in that team.
(assume 90 students)
Characters are stored as integers.
‘A‘ is 65, ‘B‘ is 66, …
(teamid + 5) is allowed in C.
startroll = (teamid – 65) * 10 + 1;
As a good programming practice
startroll = ((int)teamid – ‘A‘) * 10 + 1;
Problem: Find endsem percentage.
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
// create data
int labs, midsem, endsem;
// take input
scanf("%d%d", &labs, &midsem);
// do computation
endsem = (100 – (labs + midsem));
// output
printf("Endsem %% is %d\n", endsem);
endsem = (100 – labs – midsem);
int nonendsem;
nonendsem = labs + midsem;
endsem = 100 – nonendsem;
int remaining;
remaining = 100;
scanf(“%d“, &labs);
remaining = remaining – labs;
scanf(“%d“, &midsem);
remaining = remaining – midsem;
printf(“Endsem %% is %d\n“, remaining);
???
labs
???
midsem
???
remaining
100
56
44
15
29
56
15
29
Problem: Find sum.
int n;
// read n
scanf("%d", &n);
// compute sum
int sum = n * (n + 1) / 2;
// print sum
printf("Sum of first %d numbers is %d\n", n, sum);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
Σn = 1 + 2 + 3 + ... + n
= n * (n + 1) / 2
Σ2i = 1 + 2 + 4 + 8 + ... n terms
= 2n – 1
Needs pow() function or a loop.
pow(x, y) returns xy.
Does your code compile?
Problem: Find probability.
int nCards = 52;
int nKings = 4;
int nSpades = 13;
int nKingAndSpade = 1;
int nNonkingNonspade = nCards -
(nKings + nSpades - nKingAndSpade);
float prob = nNonkingNonspade / nCards;
printf("Probability of nonking, nonspade is %f\n",
prob);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
A card is drawn at random from a deck of well-shuffled cards. Find the probability of it being neither a king nor a spade.
Find the issue
with this code.
Problem: Find the line.
float x1, y1, x2, y2;
scanf("%f%f%f%f", &x1, &y1, &x2, &y2);
float m = (y2 – y1) / (x2 – x1);
float c = (y1 – m*x1);
printf("Equation of the line is y = %.2fx + %.2f\n", m, c);
printf("Equation of the line is y = %gx + %g\n", m, c);
printf("Equation of the line is y = %.2ex + %.2e\n", m, c);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
Given two points on a line, find its equation in y = mx + c format.
3.2 3 9.6 5
Equation of the line is y = 0.31x + 2.00
Equation of the line is y = 0.3125x + 2
Equation of the line is y = 3.12e-01x + 2.00e+00
Problem: Print tabular.
char name1[20], name2[20], name3[20];
int m11, m12, m13, m21, m22, m23, m31, m32, m33;
scanf("%s%d%d%d", &name1, &m11, &m12, &m13);
scanf("%s%d%d%d", &name2, &m21, &m22, &m23);
scanf("%s%d%d%d", &name3, &m31, &m32, &m33);
int t1, t2, t3;
t1 = m11 + m12 + m13;
t2 = m21 + m22 + m23;
t3 = m31 + m32 + m33;
printf("%-12s%5d%5d%5d = %5d\n", name1, m11, m12, m13, t1);
printf("%-12s%5d%5d%5d = %5d\n", name2, m21, m22, m23, t2);
printf("%-12s%5d%5d%5d = %5d\n", name3, m31, m32, m33, t3);
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
Read names and marks of three students and print the names and total in a table.
Rajesh 1 43 43 = 87
SomeshSingh 23 55 6 = 144
JK 21 21 21 = 63
char array or string
Future Connect:
Replacing &name1 with
name1 also works.
Homework Problem: Number game.
char c;
int num;
scanf(“%c“, &c);
scanf(“%d“, &num);
printf(“%cS%x\n“, c, num);
Choose a number from 0..9.
Multiply by 5.
Add 3 to it.
Double it up.
Choose another number from 0..9 and add to it.
Tell me the number. I will tell you both the chosen numbers.
Computer System
limbd.org
Your files reside here.
e.g., hello.c, a.out
printf
scanf
18
age
4315348
executes a.out
Hello World!
All C Keywords
auto | break | case | char |
const | continue | default | do |
double | else | enum | extern |
float | for | goto | if |
int | long | register | return |
short | signed | sizeof | static |
struct | switch | typedef | union |
unsigned | void | volatile | while |
www.programiz.com
Summary