SlideShare a Scribd company logo
1
COL 100:
Introduction to Programming
Smruti R. Sarangi
Dept. of Computer Science & Engineering
2
Course Materials
Books:
1. Programming with C (Second Edition)
Byron Gottfried, Third Edition, Schaum’s Outlines
Series,
2. The C Programming Language
Brian W Kernighan, Dennis M Ritchie
3
Attendance
REALLY
matters
 Important for understanding the course
 Any student with low attendance may be
deregistered from the course
 Leave due to medical reasons must be certified
by the IIT Hospital
4
Introduction
What is a Computer ?
A computer is a general purpose device that can be programmed to process
information, and yield meaningful results.
5
6
Predicted in 1954
Reality
How does it work ?
 Program – List of instructions given to the computer
 Information store – data, images, files, videos
 Computer – Process the information store according
to the instructions in the program
Computer
Program
Information
store
results
7
What does a computer look
like ?
 Let us take the lid off a desktop computer
CPU
Memory
Hard disk
8
 Memory – Stores programs and data. Gets
destroyed when the computer is powered off
 Hard disk – stores programs/data permanently
Computer
Memory Hard disk
9
Let us make it a full system
...
Computer
Memory Hard disk
Keyboard
Mouse
Monitor
Printer
10
Food for Thought...
 What is the most intelligent computer ?
11
Answer ...
 Our brilliant brains
12
How does an Electronic Computer
Differ from our Brain ?
 Computers are ultra-fast and ultra-dumb
Feature Computer Our Brilliant Brain
Intelligence Dumb Intelligent
Speed of basic calculations Ultra-fast Slow
Can get tired Never After sometime
Can get bored Never Almost always
13
How to Instruct a Computer ?
 Write a program in a high level language – C, C++,
Java
 Compile it into a format that the computer
understands
 Execute the program
Program Executable Output
compile execute
14
What Can a Computer Understand ?
 Computer can clearly NOT understand
instructions of the form
 Multiply two matrices
 Compute the determinant of a matrix
 Find the shortest path between Mumbai and Delhi
 They understand :
 Add a + b to get c
 Multiply a + b to get c
15
The Language of Instructions
 Humans can understand
 Complicated sentences
 English, French, Spanish
 Computers can understand
 Very simple instructions
The semantics of all the instructions supported by a processor is known
as its instruction set architecture (ISA). This includes the semantics of
the instructions themselves, along with their operands, and interfaces
with peripheral devices.
16
Features of an ISA
 Example of instructions in an ISA
 Arithmetic instructions : add, sub, mul, div
 Logical instructions : and, or, not
 Data transfer/movement instructions
 Also called low level instructions …
 Most programmers avoid writing programs in low level
instructions. Very complicated, and difficult.
17
18
Problems with programming using
instruction sets directly
 Instruction sets of different types of CPUs are
different
 Need to write different programs for computers with
different types of CPUs even to do the same thing
 Solution: High level languages (C, C++,
Java,…)
 CPU neutral, one program for many
 Compiler to convert from high-level program to low
level program that CPU understands
 Easy to write programs
19
20
Fundamentals: Binary
Numbers
Representing Positive Integers
Ancient Roman System
Issues :
 There was no notion of 0
 Very difficult to represent large numbers
 Addition, and subtraction (very difficult)
21
Symbol I V X L C D M
Value 1 5 10 50 100 500 1000
 Uses the place value system
Indian System
Bakshali numerals, 7th century AD
5301 = 5 * 103 + 3 * 102 + 0 * 101 + 1*100
Example in base 10
22
Number Systems in Other Bases
 Why do we use base 10 ?
 because ...
23
What if we had a world in which
...
 People had only two fingers.
24
25
Representing Numbers
102310 = 1 * 103 + 0 * 102 + 2 * 101 + 3 * 100 Decimal
base
1710 = 1 * 24 + 0 * 23 + 0 * 22 + 0 * 21 + 1 * 20 = 100012
Binary
Base = 2
Binary Number System
They would use a number system with
base 2.
Number in decimal Number in binary
5 101
100 1100100
500 111110100
1024 10000000000
26
MSB and LSB
 MSB (Most Significant Bit)  The leftmost bit
of a binary number. E.g., MSB of 1110 is 1
 LSB (Least Significant Bit)  The rightmost
bit of a binary number. E.g.,
LSB of 1110 is 0
27
Hexadecimal and Octal
Numbers
 Hexadecimal numbers
 Base 16 numbers – 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
 Start with 0x
 Octal Numbers
 Base 8 numbers – 0,1,2,3,4,5,6,7
 Start with 0
28
Examples
Convert 110010111 to the octal format : 110 010 111 = 0612
Convert 111000101111 to the hex format : 1110 0010 1111 = 0xC2F
Decimal Binary Octal Hexadecimal
9 1001 0 11 0x 9
12 1100 0 14 0x C
17 10001 0 21 0x 11
28 11100 0 34 0x 1C
30
Bits and Bytes
 Computers do not understand natural human languages, nor
programming languages
 They only understand the language of bits
Bit 0 or 1Bit 0 or 1
Word
0 or 1
Byte
0 or 1
0 or 10 or 10 or 18 bits
0 or 10 or 10 or 14 bytes
kiloByte 0 or 10 or 10 or 11024 bytes
megaByte 0 or 10 or 1106 bytes
30
31
Fundamentals of C
32
First C program – print on screen
#include <stdio.h>
void main()
{
printf ("Hello, World! n") ;
}
33
More printing … (code and see)
#include <stdio.h>
void main()
{
printf ("Hello, World! ") ;
printf ("Hello n World! n") ;
}
34
Some more printing
#include <stdio.h>
void main()
{
printf ("Hello, World! n") ;
printf ("Hello n World! n") ;
printf ("Hellno t World! n") ;
}
35
#include <stdio.h>
void main()
{
int num ;
scanf ("%d", &num) ;
printf (“No. of students is %dn”, num) ;
}
Reading values from keyboard
36
Centigrade to Fahrenheit
#include <stdio.h>
void main()
{
float cent, fahr;
scanf(“%f”,&cent);
fahr = cent*(9.0/5.0) + 32;
printf( “%f C equals %f Fn”, cent, fahr);
}
37
Largest of two numbers
#include <stdio.h>
void main()
{
int x, y;
scanf(“%d%d”,&x,&y);
if (x>y) printf(“Largest is %dn”,x);
else printf(“Largest is %dn”,y);
}
largest-1.c
38
What does this do?
#include <stdio.h>
void main()
{
int x, y;
scanf(“%d%d”,&x,&y);
if (x>y) printf(“Largest is %dn”,x);
printf(“Largest is %dn”,y);
}
largest-2.c
39
The C Character Set
 The C language alphabet
 Uppercase letters ‘A’ to ‘Z’
 Lowercase letters ‘a’ to ‘z’
 Digits ‘0’ to ‘9’
 Certain special characters:
A C program should not contain anything else
! # % ^ & * ( )
- _ + = ~ [ ] 
| ; : ‘ “ { } ,
. < > / ? blank
40
Structure of a C program
 A collection of functions (we will see what they
are later)
 Exactly one special function named main must
be present. Program always starts from there
 Each function has statements (instructions) for
declaration, assignment, condition check,
looping etc.
 Statements are executed one by one
41
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
42
Contd.
 Variables stored in memory
 Remember that memory is a list of storage
locations, each having a unique address
 A variable is like a bin
 The contents of the bin is the value of the variable
 The variable name is used to refer to the value of
the variable
 A variable is mapped to a location of the memory,
called its address
43
Example
#include <stdio.h>
void main( )
{
int x;
int y;
x=1;
y=3;
printf("x = %d, y= %dn", x, y);
}
44
Variables in Memory
Instruction executed Memory location allocated
to a variable X
T
i
m
e
X = 10
10X = 20
X = X +1
X = X*5
45
Variables in Memory
Instruction executed Memory location allocated
to a variable X
T
i
m
e
X = 10
20X = 20
X = X +1
X = X*5
46
Variables in Memory
Instruction executed Memory location allocated
to a variable X
T
i
m
e
X = 10
21X = 20
X = X +1
X = X*5
47
Variables in Memory
Instruction executed
Memory location allocated
to a variable X
T
i
m
e
X = 10
105X = 20
X = X +1
X = X*5
48
Variables (contd.)
20
?
X
Y
X = 20
Y=15
X = Y+3
Y=X/6
49
Variables (contd.)
20
15
X
Y
X = 20
Y=15
X = Y+3
Y=X/6
50
Variables (contd.)
18
15
X
Y
X = 20
Y=15
X = Y+3
Y=X/6
51
Variables (contd.)
18
3
X
Y
X = 20
Y=15
X = Y+3
Y=X/6
52
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)
53
Contd.
 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 functions
 A value can also be assigned to a variable at the
time the variable is declared.
int speed = 30;
char flag = ‘y’;
54
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
More Valid and Invalid Identifiers
 Valid identifiers
X
abc
simple_interest
a123
LIST
stud_name
Empl_1
Empl_2
avg_empl_salary
 Invalid identifiers
10abc
my-name
“hello”
simple interest
(area)
%rate
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…
57
Example 1
#include <stdio.h>
void main()
{
int x, y, sum;
scanf(“%d%d”,&x,&y);
sum = x + y;
printf( “%d plus %d is %dn”, x, y, sum );
}
Three int type variables declared
Values assigned
58
Example - 2
#include <stdio.h>
void main()
{
float x, y;
int d1, d2 = 10;
scanf(“%f%f%d”,&x, &y, &d1);
printf( “%f plus %f is %fn”, x, y, x+y);
printf( “%d minus %d is %dn”, d1, d2, d1-d2);
}
Assigns an initial value to d2,
can be changed later
59
Read-only variables
 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
60
void main() {
const int LIMIT = 10;
int n;
scanf(“%d”, &n);
if (n > LIMIT)
printf(“Out of limit”);
}
void main() {
const int Limit = 10;
int n;
scanf(“%d”, &n);
Limit = Limit + n;
printf(“New limit is %d”, Limit);
}
Correct
Incorrect: Limit changed
61
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 between 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”
62
Contd.
 Character constants
 Contains a single character enclosed within a pair of
single quote marks.
Examples :: ‘2’, ‘+’, ‘Z’
 Some special backslash characters
‘n’ new line
‘t’ horizontal tab
‘’’ single quote
‘”’ double quote
‘’ backslash
‘0’ null
63
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
int a, b;
float c;
scanf(“%d %d %f”, &a, &b, &c);
Format string
Variable list (note the &
before a variable name)
64
 Commonly used conversion characters
c for char type variable
d for int type variable
f for float type variable
lf for double type variable
Examples
scanf ("%d", &size) ;
scanf ("%c", &nextchar) ;
scanf ("%f", &length) ;
scanf (“%d%d”, &a, &b);
65
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
66
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 %dn", 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 125
67
Contd.
 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
68
 Examples:
printf (“Average of %d and %d is %f”, a, b, avg);
printf (“Hello nGood nMorning n”);
printf (“%3d %3d %5d”, a, b, a*b+2);
printf (“%7.2f %5.1f”, x, y);
 Many more options are available for both
printf and scanf
Read from the book
Practice them in the lab

More Related Content

What's hot

Session02 c intro
Session02 c introSession02 c intro
Session02 c intro
HarithaRanasinghe
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
DhivyaSubramaniyam
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
Manzoor ALam
 
C language programming
C language programmingC language programming
C language programming
Vaibhav Salonia
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
MomenMostafa
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
Tareq Hasan
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Sreedhar Chowdam
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
Intro C# Book
 
C++ for beginners
C++ for beginnersC++ for beginners
C++ for beginners
Salahaddin University-Erbil
 
Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
Jussi Pohjolainen
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
Vivek chan
 
C tutorial
C tutorialC tutorial
C tutorial
Khan Rahimeen
 
C tutorial
C tutorialC tutorial
C tutorial
tuncay123
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
samt7
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
Syed Zaid Irshad
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
Sreedhar Chowdam
 
C programming
C programmingC programming
C programming
ASHISH KUMAR
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
Intro C# Book
 
C programming_MSBTE_Diploma_Pranoti Doke
C programming_MSBTE_Diploma_Pranoti DokeC programming_MSBTE_Diploma_Pranoti Doke
C programming_MSBTE_Diploma_Pranoti Doke
Pranoti Doke
 
10 -bits_and_bytes
10  -bits_and_bytes10  -bits_and_bytes
10 -bits_and_bytes
Hector Garzo
 

What's hot (20)

Session02 c intro
Session02 c introSession02 c intro
Session02 c intro
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
C language programming
C language programmingC language programming
C language programming
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
C++ for beginners
C++ for beginnersC++ for beginners
C++ for beginners
 
Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
C programming
C programmingC programming
C programming
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
C programming_MSBTE_Diploma_Pranoti Doke
C programming_MSBTE_Diploma_Pranoti DokeC programming_MSBTE_Diploma_Pranoti Doke
C programming_MSBTE_Diploma_Pranoti Doke
 
10 -bits_and_bytes
10  -bits_and_bytes10  -bits_and_bytes
10 -bits_and_bytes
 

Similar to Introductionof c

lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
Anonymous9etQKwW
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
KrishanPalSingh39
 
Presentation 2.ppt
Presentation 2.pptPresentation 2.ppt
Presentation 2.ppt
UdhayaKumar175069
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
dinoC_ppt.pptx
dinoC_ppt.pptxdinoC_ppt.pptx
dinoC_ppt.pptx
DinobandhuThokdarCST
 
C notes for exam preparation
C notes for exam preparationC notes for exam preparation
C notes for exam preparation
Lakshmi Sarvani Videla
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started Cpp
Long Cao
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
HNDE Labuduwa Galle
 
C++
C++C++
C tutorial
C tutorialC tutorial
C tutorial
Anuja Lad
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
Shankar Gangaju
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)
ExcellenceAcadmy
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)
ExcellenceAcadmy
 
Clanguage
ClanguageClanguage
Clanguage
Vidyacenter
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
Sudharsan S
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
ABHISHEK fulwadhwa
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptx
vijayapraba1
 

Similar to Introductionof c (20)

lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
 
Presentation 2.ppt
Presentation 2.pptPresentation 2.ppt
Presentation 2.ppt
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
dinoC_ppt.pptx
dinoC_ppt.pptxdinoC_ppt.pptx
dinoC_ppt.pptx
 
C notes for exam preparation
C notes for exam preparationC notes for exam preparation
C notes for exam preparation
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started Cpp
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
C++
C++C++
C++
 
C tutorial
C tutorialC tutorial
C tutorial
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)
 
Clanguage
ClanguageClanguage
Clanguage
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptx
 

Recently uploaded

Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
IJNSA Journal
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
zubairahmad848137
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMTIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
HODECEDSIET
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
rpskprasana
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
Aditya Rajan Patra
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
NazakatAliKhoso2
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
mamunhossenbd75
 

Recently uploaded (20)

Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMTIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
 

Introductionof c

  • 1. 1 COL 100: Introduction to Programming Smruti R. Sarangi Dept. of Computer Science & Engineering
  • 2. 2 Course Materials Books: 1. Programming with C (Second Edition) Byron Gottfried, Third Edition, Schaum’s Outlines Series, 2. The C Programming Language Brian W Kernighan, Dennis M Ritchie
  • 3. 3 Attendance REALLY matters  Important for understanding the course  Any student with low attendance may be deregistered from the course  Leave due to medical reasons must be certified by the IIT Hospital
  • 5. What is a Computer ? A computer is a general purpose device that can be programmed to process information, and yield meaningful results. 5
  • 7. How does it work ?  Program – List of instructions given to the computer  Information store – data, images, files, videos  Computer – Process the information store according to the instructions in the program Computer Program Information store results 7
  • 8. What does a computer look like ?  Let us take the lid off a desktop computer CPU Memory Hard disk 8
  • 9.  Memory – Stores programs and data. Gets destroyed when the computer is powered off  Hard disk – stores programs/data permanently Computer Memory Hard disk 9
  • 10. Let us make it a full system ... Computer Memory Hard disk Keyboard Mouse Monitor Printer 10
  • 11. Food for Thought...  What is the most intelligent computer ? 11
  • 12. Answer ...  Our brilliant brains 12
  • 13. How does an Electronic Computer Differ from our Brain ?  Computers are ultra-fast and ultra-dumb Feature Computer Our Brilliant Brain Intelligence Dumb Intelligent Speed of basic calculations Ultra-fast Slow Can get tired Never After sometime Can get bored Never Almost always 13
  • 14. How to Instruct a Computer ?  Write a program in a high level language – C, C++, Java  Compile it into a format that the computer understands  Execute the program Program Executable Output compile execute 14
  • 15. What Can a Computer Understand ?  Computer can clearly NOT understand instructions of the form  Multiply two matrices  Compute the determinant of a matrix  Find the shortest path between Mumbai and Delhi  They understand :  Add a + b to get c  Multiply a + b to get c 15
  • 16. The Language of Instructions  Humans can understand  Complicated sentences  English, French, Spanish  Computers can understand  Very simple instructions The semantics of all the instructions supported by a processor is known as its instruction set architecture (ISA). This includes the semantics of the instructions themselves, along with their operands, and interfaces with peripheral devices. 16
  • 17. Features of an ISA  Example of instructions in an ISA  Arithmetic instructions : add, sub, mul, div  Logical instructions : and, or, not  Data transfer/movement instructions  Also called low level instructions …  Most programmers avoid writing programs in low level instructions. Very complicated, and difficult. 17
  • 18. 18 Problems with programming using instruction sets directly  Instruction sets of different types of CPUs are different  Need to write different programs for computers with different types of CPUs even to do the same thing  Solution: High level languages (C, C++, Java,…)  CPU neutral, one program for many  Compiler to convert from high-level program to low level program that CPU understands  Easy to write programs
  • 19. 19
  • 21. Representing Positive Integers Ancient Roman System Issues :  There was no notion of 0  Very difficult to represent large numbers  Addition, and subtraction (very difficult) 21 Symbol I V X L C D M Value 1 5 10 50 100 500 1000
  • 22.  Uses the place value system Indian System Bakshali numerals, 7th century AD 5301 = 5 * 103 + 3 * 102 + 0 * 101 + 1*100 Example in base 10 22
  • 23. Number Systems in Other Bases  Why do we use base 10 ?  because ... 23
  • 24. What if we had a world in which ...  People had only two fingers. 24
  • 25. 25 Representing Numbers 102310 = 1 * 103 + 0 * 102 + 2 * 101 + 3 * 100 Decimal base 1710 = 1 * 24 + 0 * 23 + 0 * 22 + 0 * 21 + 1 * 20 = 100012 Binary Base = 2
  • 26. Binary Number System They would use a number system with base 2. Number in decimal Number in binary 5 101 100 1100100 500 111110100 1024 10000000000 26
  • 27. MSB and LSB  MSB (Most Significant Bit)  The leftmost bit of a binary number. E.g., MSB of 1110 is 1  LSB (Least Significant Bit)  The rightmost bit of a binary number. E.g., LSB of 1110 is 0 27
  • 28. Hexadecimal and Octal Numbers  Hexadecimal numbers  Base 16 numbers – 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F  Start with 0x  Octal Numbers  Base 8 numbers – 0,1,2,3,4,5,6,7  Start with 0 28
  • 29. Examples Convert 110010111 to the octal format : 110 010 111 = 0612 Convert 111000101111 to the hex format : 1110 0010 1111 = 0xC2F Decimal Binary Octal Hexadecimal 9 1001 0 11 0x 9 12 1100 0 14 0x C 17 10001 0 21 0x 11 28 11100 0 34 0x 1C
  • 30. 30 Bits and Bytes  Computers do not understand natural human languages, nor programming languages  They only understand the language of bits Bit 0 or 1Bit 0 or 1 Word 0 or 1 Byte 0 or 1 0 or 10 or 10 or 18 bits 0 or 10 or 10 or 14 bytes kiloByte 0 or 10 or 10 or 11024 bytes megaByte 0 or 10 or 1106 bytes 30
  • 32. 32 First C program – print on screen #include <stdio.h> void main() { printf ("Hello, World! n") ; }
  • 33. 33 More printing … (code and see) #include <stdio.h> void main() { printf ("Hello, World! ") ; printf ("Hello n World! n") ; }
  • 34. 34 Some more printing #include <stdio.h> void main() { printf ("Hello, World! n") ; printf ("Hello n World! n") ; printf ("Hellno t World! n") ; }
  • 35. 35 #include <stdio.h> void main() { int num ; scanf ("%d", &num) ; printf (“No. of students is %dn”, num) ; } Reading values from keyboard
  • 36. 36 Centigrade to Fahrenheit #include <stdio.h> void main() { float cent, fahr; scanf(“%f”,&cent); fahr = cent*(9.0/5.0) + 32; printf( “%f C equals %f Fn”, cent, fahr); }
  • 37. 37 Largest of two numbers #include <stdio.h> void main() { int x, y; scanf(“%d%d”,&x,&y); if (x>y) printf(“Largest is %dn”,x); else printf(“Largest is %dn”,y); } largest-1.c
  • 38. 38 What does this do? #include <stdio.h> void main() { int x, y; scanf(“%d%d”,&x,&y); if (x>y) printf(“Largest is %dn”,x); printf(“Largest is %dn”,y); } largest-2.c
  • 39. 39 The C Character Set  The C language alphabet  Uppercase letters ‘A’ to ‘Z’  Lowercase letters ‘a’ to ‘z’  Digits ‘0’ to ‘9’  Certain special characters: A C program should not contain anything else ! # % ^ & * ( ) - _ + = ~ [ ] | ; : ‘ “ { } , . < > / ? blank
  • 40. 40 Structure of a C program  A collection of functions (we will see what they are later)  Exactly one special function named main must be present. Program always starts from there  Each function has statements (instructions) for declaration, assignment, condition check, looping etc.  Statements are executed one by one
  • 41. 41 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
  • 42. 42 Contd.  Variables stored in memory  Remember that memory is a list of storage locations, each having a unique address  A variable is like a bin  The contents of the bin is the value of the variable  The variable name is used to refer to the value of the variable  A variable is mapped to a location of the memory, called its address
  • 43. 43 Example #include <stdio.h> void main( ) { int x; int y; x=1; y=3; printf("x = %d, y= %dn", x, y); }
  • 44. 44 Variables in Memory Instruction executed Memory location allocated to a variable X T i m e X = 10 10X = 20 X = X +1 X = X*5
  • 45. 45 Variables in Memory Instruction executed Memory location allocated to a variable X T i m e X = 10 20X = 20 X = X +1 X = X*5
  • 46. 46 Variables in Memory Instruction executed Memory location allocated to a variable X T i m e X = 10 21X = 20 X = X +1 X = X*5
  • 47. 47 Variables in Memory Instruction executed Memory location allocated to a variable X T i m e X = 10 105X = 20 X = X +1 X = X*5
  • 48. 48 Variables (contd.) 20 ? X Y X = 20 Y=15 X = Y+3 Y=X/6
  • 49. 49 Variables (contd.) 20 15 X Y X = 20 Y=15 X = Y+3 Y=X/6
  • 50. 50 Variables (contd.) 18 15 X Y X = 20 Y=15 X = Y+3 Y=X/6
  • 51. 51 Variables (contd.) 18 3 X Y X = 20 Y=15 X = Y+3 Y=X/6
  • 52. 52 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)
  • 53. 53 Contd.  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 functions  A value can also be assigned to a variable at the time the variable is declared. int speed = 30; char flag = ‘y’;
  • 54. 54 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
  • 55. More Valid and Invalid Identifiers  Valid identifiers X abc simple_interest a123 LIST stud_name Empl_1 Empl_2 avg_empl_salary  Invalid identifiers 10abc my-name “hello” simple interest (area) %rate
  • 56. 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…
  • 57. 57 Example 1 #include <stdio.h> void main() { int x, y, sum; scanf(“%d%d”,&x,&y); sum = x + y; printf( “%d plus %d is %dn”, x, y, sum ); } Three int type variables declared Values assigned
  • 58. 58 Example - 2 #include <stdio.h> void main() { float x, y; int d1, d2 = 10; scanf(“%f%f%d”,&x, &y, &d1); printf( “%f plus %f is %fn”, x, y, x+y); printf( “%d minus %d is %dn”, d1, d2, d1-d2); } Assigns an initial value to d2, can be changed later
  • 59. 59 Read-only variables  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
  • 60. 60 void main() { const int LIMIT = 10; int n; scanf(“%d”, &n); if (n > LIMIT) printf(“Out of limit”); } void main() { const int Limit = 10; int n; scanf(“%d”, &n); Limit = Limit + n; printf(“New limit is %d”, Limit); } Correct Incorrect: Limit changed
  • 61. 61 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 between 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”
  • 62. 62 Contd.  Character constants  Contains a single character enclosed within a pair of single quote marks. Examples :: ‘2’, ‘+’, ‘Z’  Some special backslash characters ‘n’ new line ‘t’ horizontal tab ‘’’ single quote ‘”’ double quote ‘’ backslash ‘0’ null
  • 63. 63 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 int a, b; float c; scanf(“%d %d %f”, &a, &b, &c); Format string Variable list (note the & before a variable name)
  • 64. 64  Commonly used conversion characters c for char type variable d for int type variable f for float type variable lf for double type variable Examples scanf ("%d", &size) ; scanf ("%c", &nextchar) ; scanf ("%f", &length) ; scanf (“%d%d”, &a, &b);
  • 65. 65 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
  • 66. 66 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 %dn", 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 125
  • 67. 67 Contd.  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
  • 68. 68  Examples: printf (“Average of %d and %d is %f”, a, b, avg); printf (“Hello nGood nMorning n”); printf (“%3d %3d %5d”, a, b, a*b+2); printf (“%7.2f %5.1f”, x, y);  Many more options are available for both printf and scanf Read from the book Practice them in the lab