C Programming Introduction
C Programming Introduction
IIT Patna 1
General Information
• Instructors
• Suman Kumar Maji
• Joydeep Chandra
• Arijit Mondal
IIT Patna 2
Course syllabus
• Introduction to C
• Variables, data type
• Statement, Conditional statement
• Loop construct
• Array, structure, union
• Function, Recursion
• Pointers
• Stack, queue, tree
• Searching, Sorting
• File handling
IIT Patna 3
Books
• Programming with C by Byron Gottfried, Schaum’s Outlines Series
• The C Programming Language by Brian W Kernighan, Dennis M Ritchie
• Data structures by S. Lipschutz, Schaum’s Outline Series
• C: How to Program by Paul Deitel and Harvey Deitel
IIT Patna 4
Evaluation policy
• This is a 3-0-3-4.5 course
• For theory:
• Assignment — 20%
• Midsem — 30%
• Endsem — 50%
• Overall
• Weightage for theory – 2 (67%)
• Weightage for lab – 1 (33%)
IIT Patna 5
Introduction: Overview of computing
systems
IIT Patna 6
Why do we use computers?
• To solve problems with the help of machines, implementing automation for
monotonous jobs, etc.
• Find the maximum of 5 integers
• Find the maximum of 5,000,000 integers
• Second scenario needs a systematic method to find the maximum element
• In this course, we will learn how to write programs
• Program - set of instructions written for a given purpose. It tells computer
what to do
• Computers are good in obeying instructions but have no intelligence!
IIT Patna 7
What can a computer do
• Check prime number
• Palindrome recognizer
• Find shortest path between two points
• Telephone pole placement
• Spaceship control
• Finger-print recognition
• Play chess
• Image recognition
• Speech recognition
• Language recognition and many more!
IIT Patna 8
Simple view of computer
Write outputs
Read inputs Output peripherals
Input peripherals Central Processing
keyboard, mouse, printer, display
webcam, etc Unit (CPU) speaker, etc.
Fetch
Stores instructions
to be executed
Decode Main memory add a,b,c
store a,b
load a,b
Execute
IIT Patna 9
Overview of compilation
• Write the program using high-level language (C in our case)
• Compile the program (primarily gcc will be used) - it generates the binary (ex-
ecutable) code
• Run the executable code (a.out in our case)
Library
IIT Patna 10
Binary representation
• Normal number system uses decimal representation 0-9 which has base 10
• Example: 625 = 5 × 100 + 2 × 101 + 6 × 102
• Numbers in computer systems are represented in base-2, it has only two digits
0 and 1
• Example: 1011 = 1 × 20 + 1 × 21 + 0 × 22 + 1 × 23 = 11
• Octal representation (base-8) - 0-7 are used
• Hexadecimal representation (base-16) - 0-9, A, B, C, D, E, F are used
• A=10, …,F=15
• Conversion from binary to hexadecimal or vice-versa are easy
IIT Patna 11
Bits and Bytes
• Bit — a single binary digit that is either 0 or 1
• Byte — a consecutive sequence of 8 bits
• 4 bytes = 32 bits
• 8 bytes = 64 bits
• Range of integers that can be expressed depends on the representation size
• If 1 byte is used then the range of integers will be 0-255
• If 4 bytes are used then the range of integers will be 0-232
• Different datatypes (integers, float, double) can have different sizes
IIT Patna 12
Problem solving flow
• Describe the problem to be solved clearly. Specify inputs and outputs unam-
biguously
• Draw a flowchart of steps (or develop an algorithm) to be followed
• Convert the flowchart into a program, choose your preferred language (C in our
case)
• Compile the program and generate an executable code
• Run the executable code
• Test your code / program with different inputs
IIT Patna 13
Flow chart
• Representing the steps in a structured way and presenting the flow of execu-
tion of those steps
• Uses very simple basic blocks to describe the overflow of steps / algorithms
Computation
Start/stop
a = 5;
Input/Output
Connector
read x
Condition
Flow of control
x>0
IIT Patna 14
Flow diagram: Sum of 3 numbers
Start
Read a,b,c
S=a+b+c
Write S
Stop
IIT Patna 15
Flow diagram: Max of two numbers
Start
IIT Patna 16
Flow diagram: Max of two numbers
Start
Read a,b
IIT Patna 16
Flow diagram: Max of two numbers
Start
Read a,b
a>b
IIT Patna 16
Flow diagram: Max of two numbers
Start
Read a,b
yes
a>b
Write a
IIT Patna 16
Flow diagram: Max of two numbers
Start
Read a,b
yes
a>b
Write a
Stop
IIT Patna 16
Flow diagram: Max of two numbers
Start
Read a,b
yes no
a>b
Write a Write b
Stop
IIT Patna 16
Flow diagram: Max of two numbers
Start
Read a,b
yes no
a>b
Write a Write b
Stop Stop
IIT Patna 16
Flow diagram: factorial of a number
Start
IIT Patna 17
Flow diagram: factorial of a number
Start
Read n
IIT Patna 17
Flow diagram: factorial of a number
Start
Read n
factorial = 1
count = 1
IIT Patna 17
Flow diagram: factorial of a number
Start
Read n
factorial = 1
count = 1
count > n?
IIT Patna 17
Flow diagram: factorial of a number
Start
Read n
factorial = 1
count = 1
count > n?
No
factorial = factorial * count
IIT Patna 17
Flow diagram: factorial of a number
Start
Read n
factorial = 1
count = 1
count > n?
No
factorial = factorial * count
count = count + 1
IIT Patna 17
Flow diagram: factorial of a number
Start
Read n
factorial = 1
count = 1
count > n?
No
factorial = factorial * count
count = count + 1
IIT Patna 17
Flow diagram: factorial of a number
Start
Read n
factorial = 1
count = 1
Yes
count > n?
No
factorial = factorial * count Write factorial
count = count + 1
IIT Patna 17
Flow diagram: factorial of a number
Start
Read n
factorial = 1
count = 1
Yes
count > n?
No
factorial = factorial * count Write factorial
IIT Patna 17
Fundamentals of C
IIT Patna 18
First C program
#include <stdio.h>
void main()
{
printf("Hello, World!\n");
}
IIT Patna 19
First C program
#include <stdio.h>
void main()
{
printf("Hello, World!\n");
}
• Output:
Hello, World!
IIT Patna 19
Good practice for program writing
/*
Program: Print Hello World
Name: <your name> comments
Roll No: <roll number>
*/
IIT Patna 22
C program: you need to know
• Variables
• Constants
• Expressions (Arithmetic, Logical, Assignment)
• Statements (Declaration, Assignment, Control (conditional / branching, loop-
ing))
• Arrays
• Functions
• Structures
• Pointers
IIT Patna 23
The C character set
• C language alphabet
• Uppercase letters ’A’ to ’Z’
• Lowercase letters ’a’ to ’z’
• Digits ’0’ to ’9’
• Special characters: ! # % ^ & * - _ + = ~[ ] \ | ; : ' " {
} , . < > / ? and ‘blank’ (tab, space)
• A C program should not contain anything else
IIT Patna 24
Variables
• Very important concept for programming
• An entity that has a value and is known to the program by a name
• Can store any temporary result while executing a program
• Can have only one value assigned to it at any given time during the execution
of the program
• The value of a variable can be changed during the execution of the program
• Variables stored in memory
• Remember that memory is a list of storage locations, each having a unique
address
IIT Patna 25
Variables (contd.)
• A variable is like a bin
• The contents of the bin is the value of the variable 0
• The variable name is used to refer to the value of 1
the variable 2
3
• A variable is mapped to a location of the memory, ..
called its address ..
..
N-1
N
IIT Patna 26
Example
#include <stdio.h>
void main()
{
int x;
int y; = – does not denote equality
x=1;
y=3; Values are assigned to variables.
printf("x=%d, y=%d\n",x,y);
}
IIT Patna 27
Variables in memory
x = 10
x = 20
unknown x
x=x+1
x = x∗5
IIT Patna 28
Variables in memory
x = 10
x = 20
10
unknown x
x=x+1
x = x∗5
IIT Patna 28
Variables in memory
x = 10
x = 20
20
10
unknown x
x=x+1
x = x∗5
IIT Patna 28
Variables in memory
x = 10
x = 20
21
20
10
unknown x
x=x+1
x = x∗5
IIT Patna 28
Variables in memory
x = 10
x = 20
105
21
20
10
unknown x
x=x+1
x = x∗5
IIT Patna 28
Variables in memory
x = 20
x y
y = 15
20 ?
x=y+3
y = x/6
IIT Patna 29
Variables in memory
x = 20
x y
y = 15
20 15
?
x=y+3
y = x/6
IIT Patna 29
Variables in memory
x = 20
x y
y = 15
18
20 15
?
x=y+3
y = x/6
IIT Patna 29
Variables in memory
x = 20
x y
y = 15
18
20 15
3?
x=y+3
y = x/6
IIT Patna 29
Data types
• Each variable has a type, indicates what type of values the variable can hold
• Four common data types in C
• int - can store integers (usually 4 bytes)
• float - can store single-precision floating point numbers (usually 4 bytes)
• double - can store double-precision floating point numbers (usually 8 bytes)
• char - can store a character (1 byte)
IIT Patna 30
Data types
• Must declare a variable (specify its type and name) before using it anywhere in
your program
• All variable declarations should be at the beginning of the main() or other func-
tions
• There are exception too
• A value can also be assigned to a variable at the time the variable is declared.
• int speed = 30;
• char flag = 'y';
IIT Patna 31
Variable names
• Sequence of letters and digits
• First character must be a letter or ’_’
• No special characters other than ’_’
• No blank in between
• Names are case-sensitive (max and Max are two different names)
• Examples of valid names:
• i rank1 _MAX max Min class_rank
• Examples of invalid names:
• a's fact rec 2sqroot class,rank
IIT Patna 32
Variable names
• Valid identifiers • Invalid identifiers
• X • 10abc
• abc • my-name
• simple_interest • "hello"
• a123 • simple interest
• LIST • (area)
• stud_name • %rate
• Empl_1
• Empl_2
• avg_empl_salary
IIT Patna 33
C Keywords
• Used by the C language, cannot be used as variable names
• Examples:
• int, float, char, double, main, if else, for, while,
do, struct, union, typedef, enum, void, return, signed,
unsigned, case, break, sizeof,....
• There are others, see textbook...
IIT Patna 34
Example 1
#include <stdio.h>
void main(){
int x, y, sum; variable declaration
scanf("%d%d",&x, &y); read variables and assign
sum = x + y; computation and assign
printf("Summation of x=%d and y=%d is %d\n",x,y,sum);
}
IIT Patna 35
Example 1
#include <stdio.h>
void main(){
int x, y, sum; variable declaration
scanf("%d%d",&x, &y); read variables and assign
sum = x + y; computation and assign
printf("Summation of x=%d and y=%d is %d\n",x,y,sum);
} Output:
25 144
Summation of x=25 and y=144 is 169
IIT Patna 35
Example 2
#include <stdio.h>
int main(){
float x,y; /* two real numbers */
int d1=24,d2; /* integer d1 initialized to 24 */
scanf("%f%f%d",&x,&y,&d2);
printf("Summation of x=%f and y=%f is %f\n",x,y,x+y);
printf("%d minus %d is %d\n",d1,d2,d1-d2);
return 0;
}
IIT Patna 36
Input: scanf function
• Performs input from keyboard
• It requires a format string and a list of variables into which the value received
from the keyboard will be stored
• format string = individual groups of characters (usually ’%’ sign, followed by a
conversion character), with one character group for each variable in the list
IIT Patna 37
Input: scanf function (contd.)
• Examples
• scanf("%d", &size);
• reads one integer and stores it in variable named size
• scanf("%c", &nextchar);
• reads one character and stores in char variable
• scanf("%f", &temperature);
• reads a floating (real) number
• scanf("%lf", &length);
• reads a double (real) number
• scanf("%d%d", &x, &y);
• reads in two integers
IIT Patna 38
Input: scanf function (contd.)
• scanf() will wait for you to type the input from keyboard
• You must type the same number of inputs as the number of %’s in the format
string
• Example: scanf(”%d%d%d”,...) this expects 3 integers to be typed from key-
board. Execution will not proceed unless it receives three inputs
IIT Patna 39
Reading a single character
• A single character can be read using scanf with %c
• It can also be read using the getchar() function
char c;
c=getchar();
• Program waits at the getchar() line until a character is typed, and then reads
it and stores it in c
IIT Patna 40
Output: printf function
• Performs output to the standard output device (typically defined to be the
screen). It requires a format string in which we can specify:
• The text to be printed out
• Specifications on how to print the values
printf("The number is %d\n", num);
• The format specification %d causes the value listed after the format string to
be embedded in the output as a decimal number in place of %d
• Output will appear as: The number is 25
IIT Patna 41
Output: printf function
• General syntax:
printf (format string, arg1, arg2, ..., argn);
• format string refers to a string containing formatting information and data
types of the arguments to be output
• the arguments arg1, arg2, ... represent list of variables/expressions
whose values are to be printed
• The conversion characters are the same as in scanf
IIT Patna 42
Examples of printf
printf("Average of %d and %d is %f", a, b, avg);
printf("Hello! \n Good Afternoon\n");
printf("%3d %5d %7d", a, b, a*a+b*b);
printf("%7.2f %5.1f", a, b);
Many more options are available for both printf and scanf. Read from book.
IIT Patna 43
Read only variable
• Variables whose values can be initialized during declaration, but cannot be
changed after that
• Declared by putting the const keyword in front of the declaration
• Storage allocated just like any variable
• Used for variables whose values need not be changed
• Prevents accidental change of the value
IIT Patna 44
Read only variable
• Correct • Incorrect
IIT Patna 45
Constants
• Integer constants
• Consists of a sequence of digits, with possibly a plus or a minus sign before
it
• Embedded spaces, commas and non-digit characters are not permitted be-
tween digits
• Floating point constants
• Two different notations
• Decimal notation: 25.0, 0.0034, .84, -2.234
• Exponential (scientific) notation 3.45e23, 0.123e-12, 123e2
• e means ”10 to the power of”
IIT Patna 46
Constants
• Character constants
• Contains a single character enclosed within a pair of single quote marks
• Examples :: ’2’, ’+’, ’Z’
• Some special backslash characters
• \n — new line • \’ — single quote • \\ — backslash
• \t — horizontal tab • \” — double quote • \0 — null
IIT Patna 47
Example-1
#include <stdio.h>
void main()
{
printf("Hello, World!\n");
printf("Hello,\n World!\n");
}
IIT Patna 48
Example-2
#include <stdio.h>
void main()
{
printf("Hello, World!\n");
printf("Hello,\n World!\n");
printf("Hello,\t World!\n");
}
IIT Patna 49
Example-3
#include <stdio.h>
void main()
{
int number;
scanf("%d",&number);
printf("Student count in this class is %d\n",number);
}
IIT Patna 50
Example-4: Centigrade to Fahrenheit
#include <stdio.h>
void main()
{
float cent,fahr;
scanf("%f",¢);
fahr=cent*(9.0/5.0)+32;
printf("%f C equals to %f\n",cent,fahr);
}
IIT Patna 51
Example-5: Maximum of two numbers
#include <stdio.h>
void main()
{
int x,y;
scanf("%d%d",&x,&y);
if(x>y) printf("Largest is %d\n",x);
else printf("Largest is %d\n",y);
}
IIT Patna 52
Example-6: What will be the output?
#include <stdio.h>
void main()
{
int x,y;
scanf("%d%d",&x,&y);
if(x>y) printf("Largest is %d\n",x);
printf("Largest is %d\n",y);
}
IIT Patna 53
Linux commands
• ls — Lists all files in a directory. Try — ls, ls -l, ls -al, ls -lrt
• cat — cat <filename> - displays the content of the file
• cd — cd <dirname> - change directory
• cp — cp <src> <dest> - copies file
• mv — mv <src> <dest> - renaming a file
• pwd — print present working directory
• mkdir — mkdir <dirname> - create a new directory
• rm — rm <filename> - remove / delete a file. Deleted file cannot be recov-
ered
• man — man <help-topic> - manual page
IIT Patna 54
Practice problems
• Read two integers and two double numbers, each in separate scanf() statement
and print them in a single printf() statement.
• Repeat above for float and char data types
• Read two integers and print them in separate lines such that the last digit of
each integer is exactly 8 spaces away from the beginning of the line it is printed
in
IIT Patna 55