You are on page 1of 253

CSE101

Computer Programming
Lecture #0

© LPU :: CSE101 C Programming


Course Details
• LTP
202

• Text Book
▪ “PROGRAMMING IN C”
by
ASHOK N. KAMTHANE
PEARSON, 2nd Edition

© LPU :: CSE101 C Programming


Reference Books
• “C HOW TO PROGRAM” by
PAUL DEITEL AND
HARVEY DEITEL
PHI(Prentice Hall India)

• “PROGRAMMING IN ANSI C”
By E. BALAGURUSAMY
McGraw Hill Education

© LPU :: CSE101 C Programming


Syllabus and Instruction Plan(IP)

© LPU :: CSE101 C Programming


Course Assessment Model
• Marks break up

▪ Attendance 5
▪ Academic Task 25
▪ MTE 20
▪ ETE 50
• Total 100

© LPU :: CSE101 C Programming


Academic Task
Component Week
1. Online Assignment 3 5th
2. Online Assignment 2 9th
3. Online Assignment 3 11th

Total Weeks: 14( 7 Before MTE and 7 After MTE)

© LPU :: CSE101 C Programming


Mode of Conduct
• BYOD(Bring your own device)

• Note: Laptops are mandatory for program


implementation.

© LPU :: CSE101 C Programming


Daily routine

Let us look around our daily routine…


• Let us see where all we do programming
everyday
• Simple things we do to start the day

This too has a set procedure. One


follows particular steps to accomplish
the task.

So there is ONE program you know which is there in you…


© LPU :: CSE101 C Programming
Daily routine

• There is a set procedure Start

Pick Brush

• Each step is defined Rinse


Brush
Apply
• The occurrence is ordered Paste

Brush

• Jump is NOT permitted Rinse


Mouth

Rinse
• A step cannot be skipped Brush

Stop

© LPU :: CSE101 C Programming


Daily routine

• Let us explore more as the day goes by…

Going for a morning 0900 AM Class Going for a movie at 0900 AM

It is all about WHICH program is loaded WHEN


© LPU :: CSE101 C Programming
Daily routine

• The flow changes


Start

Go!!!

Where
Class To Movie
Go?

Stop Stop
© LPU :: CSE101 C Programming
So what does this mean?

• Take ANY activity of the day…


• It will have a set procedure
• It has to be done in a designate way
• If not done the specified way will yield
wrong results
• Success in doing it depends on how
closer one is to the prescribed method

• This clearly shows that everything has a

© LPU :: CSE101 C Programming


What next?

• If there is logic in anything and


everything
• There has to be ways to represent logic
• There has to be modes to modify and
re-represent logic
• There should be methodology to
implement and re-design logic
• And for all this…
© LPU :: CSE101 C Programming
What next?

• There has to be logic machine


to assimilate, understand,
solve, store, retrieve and
represent logic

• There has to be a
LANGUAGE to communicate
with the logic machine
Otherwise….
© LPU :: CSE101 C Programming
Diving deeper…

© LPU :: CSE101 C Programming


WHY C???????????????

➢If we have number of powerful


programming languages available
with us then why c??????

© LPU :: CSE101 C Programming


The hitch...............
Some burning questions in mind......
• C is a very old language. Why are we still studying
this language??????
• Now, we have very powerful languages with us
then, why c??
• There is no scope of this language in industry

© LPU :: CSE101 C Programming


Lets take you close to the reality
• All of us use Computers or Laptops for different
purposes.
• Could you tell me which system software is most
required to get our system in working mode??????

© LPU :: CSE101 C Programming


Let’s Explore more
• Could you tell me which programming language is
used in writing all these operating system??????

• Latest version of Microsoft Windows i.e.


Windows10 is still being written in C Language

© LPU :: CSE101 C Programming


Contd.....
• Device drivers are also written in C language.
• All these modern programming languages are
influenced by C language

• Compilers for Python and PHP language are also


written in C language

© LPU :: CSE101 C Programming


Contd.....
• Embedded systems are also developed with the
help of C language

© LPU :: CSE101 C Programming


Contd.....
•Git

•Microsoft Excel

•Oracle Database

•MySql

•Linux

•Unix

•Android

•Google
© LPU :: CSE101 C Programming
MNCs
Top rated Companies which has a dearth of C programmers

© LPU :: CSE101 C Programming


Here are the Answers of Questions
• C is very a old language still, why do we study C
language??

• Now, we have very powerful languages


with us then why c??

• There is no scope of this language in industry

© LPU :: CSE101 C Programming


History of C
• Dennis Ritchie and Ken Thompson were working
on developing a new operating system i.e UNIX
• But the programming language they
were using was not providing them
the portability feature
• So Dennis Ritchie developed new
language i.e C

© LPU :: CSE101 C Programming


History continued...

© LPU :: CSE101 C Programming


Why “C” name was given???
• Many of C’s principles and ideas were derived from the
earlier language B. (Ken Thompson was the developer of
B Language.)
• BCPL and CPL are the earlier ancestors of B Language
• CPL is Combined Programming Language. In 1967, BCPL
Language ( Basic CPL ) was created as a scaled down
version of CPL
• As many of the features were derived from “B”
Language thats why it was named as “C”.
• After 7-8 years C++ came into existence which was first
example of object oriented programming .
© LPU :: CSE101 C Programming
Evolution of C...

© LPU :: CSE101 C Programming


Language Developers

© LPU :: CSE101 C Programming


Features of C Language
• Low Level Language Support
• Program Portability
• Powerful and Feature rich
• High Level Features
• Modular Programming

© LPU :: CSE101 C Programming


It can be defined in following ways:
It can be defined by the following ways:
• Mother language
• System programming language
• Procedure-oriented programming language
• Structured programming language
• Mid-level programming language

© LPU :: CSE101 C Programming


Course Contents
Before MTE
✓ Data Types & Operators
✓ Control Structures
✓ User Defined Functions
✓ Storage Classes

After MTE
✓ Arrays and Strings
✓ Pointers
✓ Dynamic Memory Allocation
✓ Derived Data Types- Structures
and Union
© LPU :: CSE101 C Programming
Tools
Offline Compiler Code Blocks:
• http://www.codeblocks.org/downloads

Online compiler CPP shell:


• http://cpp.sh/

© LPU :: CSE101 C Programming


© LPU :: CSE101 C Programming
© LPU :: CSE101 C Programming
© LPU :: CSE101 C Programming
© LPU :: CSE101 C Programming
© LPU :: CSE101 C Programming
© LPU :: CSE101 C Programming
MCQ
Q1 Who is the father of C language?
a) Bjarne Stroustrup
b) James A. Gosling
c) Dennis Ritchie
d) Dr. E.F Codd

© LPU :: CSE101 C Programming


MCQ
Q2 C was primarily developed as?
a) System Programming Language
b) General Purpose Language
c) Data Processing Language
d) None of the above

© LPU :: CSE101 C Programming


Basics and
Program
introduction
Development in
to
C C

© LPU :: CSE101 C Programming


©LPU CSE101 C Programming
C Program Development Environment
 A C program must go through various phases such as:
1. Creating a program with editor
2. Execution of preprocessor program
3. Compilation
4. Linking
5. Loading
6. Executing

©LPU CSE101 C Programming


Program is created in
Editor Disk the editor and stored
on disk.
Preprocessor program
Preprocessor Disk processes the code.
Compiler creates
Compiler Disk object code and stores
it on disk.
Linker links the object
Linker Disk code with the libraries,

Primary Memory

Loader
Loader puts program in memory.
Disk ..
..
..

Primary Memory

CPU CPU takes each


instruction and
executes it, possibly
.. storing new data
..
.. values as the program
executes.
©LPU CSE101 C Programming
C Program Development
Environment(cont.)
Phase 1: Create your Phase 2: A preprocessor Phase 3: Compiler
program with an editor find some preprocessor compiles the program
program directives (#include into machine languages
<stdio.h>) to include
other files.

Phase 6: CPU executes the Phase 5: A loader loads Phase 4: A linker links
program one instruction at the executable image the object code with the
a time. The load process in into memory (RAM). code in library or other
Windows OS is just input places to produce an
the name of the executable image.
executable file.

©LPU CSE101 C Programming


MCQ
C programs are converted into machine
language with the help of
a) An editor
b) A compiler
c) An operating system
d) An interpreter

©LPU CSE101 C Programming


Next Class: Program structure of C program.
Various programming tools like flow chart and
algorithms.

©LPU CSE101 C Programming


©LPU CSE101 C Programming
Algorithm
• Algorithm is defined as “ the finite set of
steps, which provide a chain of action for
solving a problem”
• It is step by step solution to given problem.
• Well organized, pre-arranged and defined
textual computational module

©LPU CSE101 C Programming


Characteristics of good Algorithm
1. Correctness - terminates on ALL inputs (even invalid inputs!) and
outputs the correct answer.
2. Simplicity - each step of the algorithm performs one logical step in
solving the problem.
3. Precision - each step of the algorithm is unambiguous in meaning.
4. Comprehensibility - the algorithm is easy to read and understand.
5. Abstraction - presents the solution steps precisely and concisely
without referring to low-level (program code) details.
6. Efficient - Gives results rapidly based on the problem size; does
not waste any space or time.
7. Easy to Implement - relatively easy to translate into a
programming language.

©LPU CSE101 C Programming


Steps to create an Algorithm
1. Identify the Inputs
• What data do I need?
• How will I get the data?
• In what format will the data be?

2. Identify the Outputs


• What outputs do I need to return to the user?
• What format should the outputs take?

©LPU CSE101 C Programming


Steps to create an Algorithm
3. Identify the Processes
• How can I manipulate data to produce
meaningful results?
• Data vs. Information

4. Break the Solution to steps


By breaking the solution to the steps we can
easily understand the logic of program

©LPU CSE101 C Programming


Example of Algorithm
To establish a telephone communication
• Step 1: Dial a phone number
• Step 2: Phone rings at the called party
• Step 3: Caller waits for the response
• Step 4: Called party picks up the phone
• Step 5: Conversation begins between them
• Step 6: After the conversation, both disconnect
the call

©LPU CSE101 C Programming


Algorithm: Add 2 Numbers
Problem: To add two numbers.

• Step1. Start.
• Step2. Take the two numbers.
• Step3. Add them.
• Step4. Print the result.
• Step5. Stop.

©LPU CSE101 C Programming


Flow Chart
• Flow Chart is pictorial representation of an
algorithm.
• Whatever we have done in algorithm we can
represent it in picture.
• It is easy to understand.
• Shows the flow of the instruction

©LPU CSE101 C Programming


Flow Chart Symbols

©LPU CSE101 C Programming


Flow Chart: Add 2 Numbers

START

TAKE TWO
NUMBERS A and B

FIND SUM=A+B

PRINT SUM

STOP
©LPU CSE101 C Programming
Flow Chart: Greater than two Numbers

©LPU CSE101 C Programming


Pseudocode
• pseudocode statements that appear to have
been written in a computer programming
language but do not necessarily follow any
syntax rules of any specific language.
• The purpose of using pseudocode is that it is
easier for people to understand than
conventional programming language code,
and that it is an efficient and environment-
independent description of the key principles
of an algorithm.
©LPU CSE101 C Programming
Example of Pseudocode
• start
input myNumber
set myAnswer = myNumber * 2
output myAnswer
Stop

©LPU CSE101 C Programming


MCQ
Q1 The symbol denotes _______

a) I/O
b) Flow
c) Terminal
d) Decision

©LPU CSE101 C Programming


MCQ
Q2 In computer science, algorithm refers to a
pictorial representation of a flowchart.
a) True
b) False

©LPU CSE101 C Programming


Explanation
• A simple C program consists of
– Comments (optional)
• //
• /*….*/
– Including header files
• #include<header file name>
– Functions
• main function as special function
• Other user defined functions (optional)
• Let’s discuss these in detail..
©LPU CSE101 C Programming
Comments

• Two forward slashes ‘ // ’ (double forward


slashes), are used to write single line comment
• The next combination ‘ /*……..*/ ’ (forward slash
with asterisk) is used for commenting multiple
lines
• These comments are not being executed by
compiler
• * comment can appear anywhere in a program
where a white space can appear

©LPU CSE101 C Programming


Header files
• The next two lines are command for including
header files

• These two lines must be included in every C


program
– stdio.h: standard input output header file for
functions printf(),scanf(),... and so on
– conio.h: console input output header file for
functions getch()…. and so on
• Here ‘ # ‘ is called preprocessor directive
©LPU CSE101 C Programming
Header files
C code example

Program //Sample program


#include<stdio.h> //header file for printf()
#include<conio.h> //header file for getch()
int main()
{
//stdio.h is providing printf() function
printf(“Car is under process”);
//conio.h is providing getch() function
getch();
}

Output:
Car is under process

©LPU CSE101 C Programming


Next Class: Components of C
Identifier and Keywords
Data Type
©LPU CSE101 C Programming
cse101@lpu.co.in
©LPU CSE101 C Programming
OUTLINE
• In this lecture we will cover
– Character set
– Identifiers
– Keyword
– Data types

©LPU CSE101 C Programming


Language: its influence in our life
• Let us look to what we are doing since our
childhood, how did we learnt ENGLISH- A recap

A B C D …… X Y Z Characters

RAT BAT CAT COW Words

COW EAT GRASS Statements

ESSAY ON COW Programs


©LPU CSE101 C Programming
Introduction to C
• Like every language C programming language
requires basic building blocks to communicate
with the computer. Characters
• So we require
– Character set Words
– Words(keywords and identifiers)
– Statement (instructions) Statements
– Program
Programs
©LPU CSE101 C Programming
Character Set
• The character set of C represents alphabet, digit or
any symbol used to represent information.
Types Character Set

Uppercase Alphabets A, B, C, … Y, Z

Lowercase Alphabets a, b, c, … y, z

Digits 0, 1, 2, 3, … 9
~‘!@#%^&*()_-+=|\{} []
Special Symbols
:;"'<>,.?/
White spaces Single space, tab, new line.
©LPU CSE101 C Programming
Token
• Every single element in a C Program is Token

©LPU CSE101 C Programming


Token
• Smallest unit in a program/statement.
• It makes the compiler understand what is written in the
program.
• Example: main, printf , name,), etc.
• Tokens are broadly classified as:
– Identifiers
– Keywords
– Constants
– Variables
– Strings
– Operators
– Special character

©LPU CSE101 C Programming


Identifiers
• So to identify things we have some name
given to them .
• Identifiers are the fundamental building blocks
of a program
• Used to give names to variables, functions,
constant, and user defined data.
• They are user-defined names and consist of a
sequence of letters and digits

©LPU CSE101 C Programming


Rules for naming an Identifier
1. An identifier name is any combination of 1 to 31
alphabets, digits or underscores.

2. The first character in the identifier name must be an


alphabet or underscore.

3. No blanks or special symbol other than an underscore


can be used in an identifier name.

4. Keywords are not allowed to be used as identifiers.

©LPU CSE101 C Programming


Some Identifiers
Tool_spanner;
both are different
tool_spanner;
FORMULA1;
engine_1;

Wrong identifiers name


1_engine;
break;
@car-roof;
©LPU CSE101 C Programming
C Keywords
• Keywords are the reserved words whose
meaning has already been explained to the C
compiler.
• We cannot use these keywords as variables.
• Each keyword is meant to perform a specific
function in a C program.
• There are 32 keywords in C language.
• All keywords are written in lowercase only

Eg: The name of person can never be home, eat,


sleep, run, etc because these words have some
predefined meaning to perform some task.

©LPU CSE101 C Programming


List of C Keywords
auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

©LPU CSE101 C Programming


Data Types
• Data type means the type of value a variable
will have.
• It also defines memory space for a particular
variable in computer.
• The type of value of variable can be alphabets
or numbers.
• The numbers can be further divided as the
integer or rational number.

©LPU CSE101 C Programming


• Lets see a mathematics problem:

©LPU CSE101 C Programming


My-Car
1. If the radius of car wheel is 15inch then what will the
distance traveled after one rotation of that wheel?
Sol: Given-
radius = 15 15 Integer( int in C )
dist_travelled = ?
So, Circumference of circle = 2 * pi * r
dist_travelled = 2 * 3.14 * radius 3.14 Real (float in C)

dist_travelled = 6.28 * 15
dist_travelled = 94.2 Ans. 94.2 Real (float in C)

©LPU CSE101 C Programming


Classification of Data Types
• In C data type is broadly classified as:
– Basic data types
– Derived data types
– User defined data types

©LPU CSE101 C Programming


Derived Data
Type
• Pointers
• Functions
• Array
Basic Data Type User Defined
• Integer Data Type
• Character • Structure
• Float • Union
• Double • Enumeration

Data
Type
©LPU CSE101 C Programming
List of Data Types
Type Size Minimal range
(bytes)
char 1 -128 to 127
unsigned char 1 0 to 255
int 4 -32768 to 32767
unsigned int 4 0 to 65535
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
float 4 3.4e-38 to 3.4e+38 with 6 digits of
precision
double 8 1.7e-308 to 1.7e+308 with 15 digits
of precision
long double 10 3.4e-4932 to 1.1e+4932 with 20
digits of precision

©LPU CSE101 C Programming


Integer
• It is used to store positive
and negative counting numbers, as well as
zero.
{...,-2,-1,0,1,2,...}

• The numbers written in green box of My-Car


problem are the integers.
15 84 34 97

©LPU CSE101 C Programming


• The type modifiers for the integer data type
are: signed, unsigned, short, long .
• Signed types represent positive and negative
numbers.
• Unsigned represent zero and positive numbers
only.
• Long and short represent the range of integer
number

©LPU CSE101 C Programming


Short Integer Long Integer
• Occupies 2 bytes in • Occupies 4 bytes in
memory. memory.
• Format specifier is %d or • Format specifier is %ld.
%i.
• Range is -32768 to • Range is -2147483648 to
32767.
2147483647
• By default int variable is
short signed int.
int cost=100; long radius=123456;
short int si; long int value;

©LPU CSE101 C Programming


Signed Integer Unsigned Integer
• Occupies 2 bytes in • Occupies 2 bytes in memory
memory • Format specifier is %u.
• Format specifier is %d or
%i • There are also long
• There are also long signed unsigned int with range 0 to
integers having range from 4294967295
-2147483648 to
2147483647
• Example: • Example:
int firstvalue=10; unsigned long count=567898;
long int WaterLevel; unsigned short int page;

©LPU CSE101 C Programming


Float
• Floating point numbers are real numbers that,
unlike integers, may contain fractional parts of
numbers, like 1.446, -112.972, 3.267e+27.
• It is used to store real numbers with single
precision i.e. a precision of 6 digits after
decimal point.

©LPU CSE101 C Programming


• Format specifier is %f.
• The type modifier for float are float, double
and long double.

• The rational number written in red box of My-


Car problem are the float numbers.
3.14 94.2

©LPU CSE101 C Programming


Type Float Double Long double

Storage Size 4 byte 8 byte 10 byte

Value range 3.4e-38 to 3.4e+38 1.7e-308 to 1.7e+308 3.4e-4932 to 1.1e+4932

Precision 6 decimal places 15 decimal places 20 decimal places

Example pi=3.141592 3.141592741012573 3.14159265358979323846

©LPU CSE101 C Programming


Character
• It stores a single character of data belonging
to the C character set.

• The alphabets written in blue box of My-


Grades problem are the character.
A D A B C

©LPU CSE101 C Programming


• It occupies 1 byte of memory.
• Format specifier is %c.
• The range is 0 to 255 for unsigned char.
• The range is -127 to 127 for signed char.
• Each char type has an equivalent integer
interpretation, ASCII value, so that a char is
really a special kind of short integer.
char choice=‘y’;

©LPU CSE101 C Programming


Format Specifier
• Specifies the format according to which the value
will be printed on screen in C.
Example:
• %d : signed integer
• %ld: long integer
• %u : unsigned integer
• %c : single character
• %f : float
• %s : string
• %i : int

©LPU CSE101 C Programming


• Remember car example?

15
%d
Program 90
%d
3.14
%d

15
%d
Program 94.2
%f
3.14
%f

©LPU CSE101 C Programming


MCQ
A program is made up of individual syntactic
elements called
• A)Classes
• B)Functions
• C)Tokens
• D)None of them

©LPU CSE101 C Programming


MCQ
Q What is the output of this C code?
int main()
{
float x = 'a';
printf("%f", x);
return 0;
}
A. a
B. run time error
C. a.0000000
D. 97.000000

©LPU CSE101 C Programming


MCQ
Q Which of the following is not a valid variable
name declaration?
a) int _v1;
b) int v_1;
c) int 1_v;
d) int _1v

©LPU CSE101 C Programming


MCQ
Q What will be the output?
• #include <stdio.h>
int main()
{
int main = 5;
printf(“%d”, main);
return 0;
}
a) compile-time error
b) run-time error
c) run without any error and prints 5
d) experience infinite looping

©LPU CSE101 C Programming


Next Lecture: Constants
Variables
Expressions
Operators
©LPU CSE101 C Programming
cse101@lpu.co.in
©LPU CSE101 C Programming
Tokens
• We have seen that Tokens are broadly classified as:
– Identifiers
– Keywords
– Constants
– Variables
– Strings
– Operators
– Special character

©LPU CSE101 C Programming


Constants
• The entity which do not change throughout
the execution are called constants.
• Types of constants:
– Integer constant
– Character constant
– Floating point constants
– String constants
Name of person remains same through out
the life, example: Amit, Shubnam, etc.

©LPU CSE101 C Programming


• Character constants
– Constants enclosed in single quotes(‘ ’).
– It can be any letter from character set.
Example : ‘\n’, ‘\t’ or ‘a’
• String Constants
– Set of zero or more characters enclosed in double
quotes (eg: “ ” )
– It is represented as sequence of characters within
double quotes.
Example : “This is C programming”

©LPU CSE101 C Programming


• Integer Constants
– When the constant contains only digits without
any decimal part
Example : 5;
-987;

• Floating Constant
– Constants that contains number with decimal
points
Example : 3.14;
309.89

©LPU CSE101 C Programming


My-Car
In My-Car problem the constant value is 3.14
which is the value of pi and always same.
• pi = 3.14
Therefore:
dist_travelled = 2 * pi * radius.

 pi is a floating point constant.

©LPU CSE101 C Programming


Variables
• Variable is an entity which may change.
• Variable is used to hold result and reserve
memory for the data.
datatype variable_name;
The naming of variable is done by following
the same rules of identifier naming.

Eg. What is your hobby?


The answer could be reading, dancing, drawing, etc.
So the answer to such questions may change during the life
time of the person

©LPU CSE101 C Programming


Rules for naming a Variable
1. An variable name is any combination of 1 to 31
alphabets, digits or underscores.

2. The first character in the variable name must be an


alphabet or underscore.

3. No blanks or special symbol other than an underscore


can be used in an variable name.

4. Keywords are not allowed to be used as variables.

©LPU CSE101 C Programming


Variables
In My-Car problem the variable was
• radius and dist_travelled
It can also be named as
• radius_wheel or r1 or
car_wheel_radius
• Distance or d1 or
dist_by_1rotation

©LPU CSE101 C Programming


Variables
Let us build some variables:
For speed of car we need to know
• Distance traveled
• Time taken to travel the distance

Variables to be declared as
• Speed, s1, speed_of_car
• Distance, d1, dist
• Time, t1, time_of_travel

©LPU CSE101 C Programming


Variable Initialization
• Assigning some value to the variable at
time of creation of variable is known as
variable initialization.
datatype variable_name = value;

Example: int radius= 15;


float pi = 3.14;
char grade = ‘A’;

©LPU CSE101 C Programming


Expressions
• Expressions are the statements or the instruction
given to computer to perform some operation.
• Every expression results in some value that can
be stored in a variable.
• Following are few example of expressions in
program:
– Expression to calculate speed of a car.
• Speed=distance/time
– Expression to find similarity of two things.
• c=value1>value2

©LPU CSE101 C Programming


• Expressions in C are basically operators acting on operands.
• An operand is an entity on which operation is to be performed.
Example: addition of two numbers, 5+8, these numbers will be
operands.

• An operator specifies the operation to be applied on operands.


Example: The addition, subtraction, etc will be operators

• Expressions are made of one or more operands.


• Statements like :
a = b + c,
300 > (8 * k)

©LPU CSE101 C Programming


Types of Expressions
• The type of expression depend upon the type of
operator used in the expression.
• It can be:
– Arithmetic operators.
3+6=9
4*2=8
– Relational or logical operators.
height_boy>=height_girl
– Increment and decrement operator.
count=count++

©LPU CSE101 C Programming


Find the output of the code
#include <stdio.h>
int main()
{
int i = 1, 2, 3;
printf("%d", i);
return 0;
}
a)1 c) prints 1,2,3
b)3 d) compile time error

©LPU CSE101 C Programming


• In this lecture we will study
– Operators
– Types of Operators

©LPU CSE101 C Programming


Operators
• Operator is the symbol which performs some
operations on the operands.

5+5=10 + and = are the operator and


5 and 10 are operands

©LPU CSE101 C Programming


Types of Operators
• Types of operators are:
1. Arithmetic operator
2. Unary operator
3. Relational operator
4. Logical operator
5. Assignment operator
6. Conditional operator
7. Bitwise operator
8. Special operator

©LPU CSE101 C Programming


Next Class: Operators
Types of operators…contd.

©LPU CSE101 C Programming


cse101@lpu.co.in
©LPU CSE101 C Programming
Operators
• Operator is the symbol which performs some
operations on the operands.

5+5=10 + and = are the operator and


5 and 10 are operands

©LPU CSE101 C Programming


Types of Operators
• Types of operators are:
1. Arithmetic operator
2. Unary operator
3. Relational operator
4. Logical operator
5. Assignment operator
6. Conditional operator
7. Bitwise operator
8. Special operator

©LPU CSE101 C Programming


Description of Operators

Arithmetic Operators
These are binary operators i.e. expression requires two operands
Operator Description Example (a=4 and b=2)
+ Addition of two operands a+b=6
- Subtraction of two operands a–b=2
* Multiplication of two operands a*b=8
/ Division of two operands a/b=2
% Modulus gives the remainder a%b=0
after division of two operands

©LPU CSE101 C Programming


MCQ
• Operator % in C Language is called.?
A) Percentage Operator
B) Quotient Operator
C) Modulus
D) Division

©LPU CSE101 C Programming


MCQ
• Choose a right statement.
int a = 10 + 4.867;
A) a = 10
B) a = 14.867
C) a = 14
D) compiler error.

©LPU CSE101 C Programming


Unary Operator
These operator requires only one operand.
Operator Description Example(count=1)
+ unary plus is used to show +count; value is 1
positive value
- unary minus negates the value of -count; value is -1
operand
++ Increment operator is used to ++count; value is 2
increase the operand value by 1 count++; value is 2
-- Decrement operator is used to --count; value is 1
decrease the operand value by 1 count--; value is 1

++count increments count by 1 and then uses its value as the value of the
expression. This is known a prefix operator.
count++ uses count as the value of the expression and then increments
count by 1. This is known as postfix operator.

©LPU CSE101 C Programming


MCQ
int main()
{
int c=--2;
printf(“c=%d”, c);
return 0;
}
a)1 b) -2 c) 2 d)error

©LPU CSE101 C Programming


MCQ
int main()
{
int x = 4, y, z;
y = --x;
z = x--;
printf("%d, %d, %d\n", x, y, z);
return 0;
}
a) 4,3,3 b)3,3,3 c)2,3,3 d)4,4,3

©LPU CSE101 C Programming


Unary Operators
Q: In an exam there was 10 question each carry 1 mark for right
answer and 0.50 marks were deducted for wrong answer. A
student attempted 6 questions and out of that 5 questions
were wrong. So what is the score of the student out of 10?
Sol: No. of questions attempted = 6
Marks deducted = 5 * 0.50 = 2.5
Unary Minus
Marks for right answer = 1 indicates that value is
Total marks = 1 – 2.5 = -1.5 negative.

©LPU CSE101 C Programming


Relational Operator
It compares two operands depending upon the their relation.
Expression generates zero(false) or nonzero(true) value.
Operator Description Example (a=10
and b=20)
< less than, checks if the value of left operand is less (a < b) value is 1(true)
than the value of right operand, if yes then condition
becomes true.
<= less than or equal to, checks if the value of left (a <= b) value is 1
operand is less than or equal to the value of right (true).
operand, if yes then condition becomes true.
> greater than, checks if the value of left operand is (a > b) value is 0 (not
greater than the value of right operand, if yes then true).
condition becomes true.
>= greater than or equal to, checks if the value of left (a >= b) value is 1
operand is greater than or equal to the value of right (true).
operand, if yes then condition becomes true.
== equality ,checks if the value of two operands is equal (a == b) value is 0
or not, if yes then condition becomes true. (not true).
!= inequality, checks if the value of two operands is equal (a != b) value is 1
or not, if values are not equal then condition becomes (true).
©LPU CSE101 C Programming
true.
Relational Operator
Q: Age of Sam is 20 and age of Tom is 19.
Verify the relationship between their age.
Sol: age of Sam = S1 = 20
age of Tom = T1 = 19
S1 < T1 = 0 (false)
S1 == T1 = 0 (false)
S1 > T1 = 1 (true)
So, Sam is elder than Tom.

©LPU CSE101 C Programming


Logical Operator
It checks the logical relationship between two expressions
and the result is zero( false) or nonzero(true).

Operator Description Example


&& Logical AND operator. If both the operands are (5>3 && 5<10) value is
true then condition becomes true. 1 (true).
|| Logical OR Operator. If any of the two (5>3 || 5<2) value is 1
operands is true then condition becomes true. (true).
! Logical NOT Operator. Use to reverses the !(8==8) value is 0
logical state of its operand. If a condition is (false).
true then Logical NOT operator will make
false.

©LPU CSE101 C Programming


Assignment Operator
They are used to assign the result of an expression on right side to a
variable on left side.
Operator Description Example(a=4 and b=2)
+= a=a+b a+=b; a=a+b = 6
-= a=a-b a-=b; a=a-b = 2
*= a=a*b a*=b; a=a*b = 8
/= a=a/b a/=b; a=a/b = 2
%= a=a%b a%=b; a=a%b = 0
<<= a=a<<b a=00000100 << 2 = 00010000
>>= a=a>>b A=00000100 >> 2 = 00000001
&= a=a&b (a=0100, b=0010) a&=b; a=a&b = 0000
|= a=a|b (a=0100, b=0010) a|=b; a=a|b =0110
^= a=a^b (a=0100, b=0010) a^=b; a=a^b = 0110

©LPU CSE101 C Programming


Assignment Operator
• To increase the cost of item soap by 50rs.
Cost_soap = Cost_soap + 50;
or Cost_soap += 50;
• To double the quantity of water in a bowl.
Water_inBowl *= 2;

 Therefore assignment operator are used to store the changed


value of the variable in the same variable.

©LPU CSE101 C Programming


Conditional Operator
Conditional operator contains condition followed by two
statements. If the condition is true the first statement is
executed otherwise the second statement.
It is also called as ternary operator because it requires three
operands.

Operator Description Example


?: conditional expression, (a>b)? “a is greater”: “b is
Condition? Expression1: Expression2 greater”

©LPU CSE101 C Programming


Conditional Operator
• Eligibility to cast vote
(age>=18)? “can cast vote”: “cannot cast vote”;
• In C
(age>=18)? printf(“can cast vote”) : printf(“cannot cast vote”);

©LPU CSE101 C Programming


MCQ
Choose a syntax for C Ternary Operator from
the list.
A) condition ? expression1 : expression2
B) condition : expression1 ? expression2
C) condition ? expression1 < expression2
D) condition < expression1 ? expression2

©LPU CSE101 C Programming


What is the output of the C statement.?
int main()
{
int a=0;
a = 5<2 ? 4 : 3;
printf("%d",a);
return 0;
}
A) 4 B) 3 C) 5 D) 2

©LPU CSE101 C Programming


Bitwise Operator
A bitwise operator works on each bit of data.
Logical Table Operator Description Example(a=1
a b a&b a|b a^b and b=0)
& bitwise AND a&b=0
0 0 0 0 0
0 1 0 1 1
| bitwise OR a| b = 1

1 1 1 1 0 ^ bitwise XOR a^b=1


1 0 0 1 1 ~ bitwise one’s ~a = 0, ~b=1
complement
<< bitwise left shift, 1101 << 1 = 1010
indicates the bits are
to be shifted to the
left.
>> bitwise right shift, 1101 >> 1 = 0110
indicates the bits are
to be shifted to the
right.
©LPU CSE101 C Programming
Some Special Operators

Operator Description Example


, comma operator, can be used to link int a, b, x;
the related expressions together
sizeof () sizeof operator to find the size of an int a; sizeof(a)=2
object.
type Cast operator, to change the data float x= 12.5;
type of the variable int a;
a = (int) x; value of a is 12.

©LPU CSE101 C Programming


MCQ
Choose a right statement.
int main()
{
float c = 3.5 + 4.5;
printf("%d", (int)c);
return 0;
}
A) 8.0 B) 8.000000 C) 7 D) 8

©LPU CSE101 C Programming


Precedence of Operators
• The precedence of operators determine a rank
for the operators. The higher an operator's
precedence or priority, the higher “binding”it
has on the operands.

Example: So how the expression a * b + c will be interpreted?


(a * b) + c or a * (b + c),
here the first interpretation is the one that is used because the multiplication
operator has higher precedence than addition.

©LPU CSE101 C Programming


Associativity of Operators
• Associativity tell us the order in which several operators with
equal precedence are computed or processed in two
directions, either from left to right or vice-versa.

Example: In the expression


a * b / c,
since multiplication and division have the same precedence we must use the
associativity to determine the grouping. These operators are left associative
which means they are grouped left to right as if the expression was
(a * b) / c.

©LPU CSE101 C Programming


Operator Associativity Type
() [] . -> ++(postfix) - - (postfix) left to right Highest
+ - ++ -- ! & * ~ sizeof (type) right to left Unary
* / % left to right multiplicative
+ - left to right additive
<< >> left to right shifting
< <= > >= left to right relational
== != left to right equality
& left to right bitwise AND
^ left to right bitwise OR
| left to right bitwise OR
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= &= |= ^= <<= >>= %= right to left assignment
, left to right comma
©LPU CSE101 C Programming
Next Class: Control Structures

©LPU CSE101 C Programming


cse101@lpu.co.in
©LPU CSE101 C Programming
Outline
• Control structure
Decision Statements
• If statement
• If-else statement
• Switch statement

©LPU CSE101 C Programming


Program
• Program is a set of instruction executed one by one.

• Depending upon the circumstances sometimes it is


desirable to alter the sequence of execution of
statements.

1. Wake up;
2. Get ready;
3. If you have enough time, then
eat breakfast;
4. Go to school.
©LPU CSE101 C Programming
Control Statements
• The C language programs until now follows a
sequential form of execution of statements.
• C language provides statements that can alter the
flow of a sequence of instructions. These statements
are called control statements.
• These statements help to jump from one part of the
program to another. The control transfer may be
conditional or unconditional.

©LPU CSE101 C Programming


Control Structure
• A control structure refers to the way in which the
programmer specifies the order of executing the
statements.
• Three control structures
– Sequence structure
• Programs are executed sequentially by default.
– Selection structures
• if, if…else, switch
– Repetition structures (iteration)
• while, do…while, for

©LPU CSE101 C Programming


Condition Statements
• The C condition statements or the decision
statements, checks the given condition
• Based upon the state of the condition, a sub-
block is executed.
• Decision statements are the:
– if statement
– if-else statement
– switch statement

©LPU CSE101 C Programming


Daily routine
Start

Go!!!

Where
Class To Movie
Go?

Stop Stop
©LPU CSE101 C Programming
if statement

Yes If you have No


time?

©LPU CSE101 C Programming


if Statement
• If statement
– It is decision making statement uses keyword if.
– It allows the computer to evaluate the expression
first
• and then, depending on whether the value is ‘true’
or ‘false’, i.e. non zero or zero it transfers the
control to a particular statement.
A decision can be made on any expression.
zero - false
nonzero - true
Example:
3 < 4 is true
©LPU CSE101 C Programming
if Statement
Syntax

if (expression)
statement;

or

if (expression)
{
block of statements;
}

©LPU CSE101 C Programming


if Statement
• The if statement has the following syntax:
The condition must be a
boolean expression. It must
if is a C Evaluate to either non-zero or zero.
reserved word

if ( condition )/* no semi-colon */


statement;

If the condition is non-zero, the statement is executed.


If it is zero, the statement is skipped.

©LPU CSE101 C Programming


Rain ???
Is it going to rain?

Look up sky for clouds

yes no
Clouds?

No rain
Raining

©LPU CSE101 C Programming


#include<stdio.h>
Program to
void main()
{ check
int v; whether
printf(“Enter the number :”);
number is
scanf(“%d”, &v);
if(v<10) less than 10.
printf(“number is less than 10”);
}

Enter the number: 6


Number is less than 10

©LPU CSE101 C Programming


What will be the output of the following C code?

#include <stdio.h>
void main()
{
int x = 5;
if (x < 1)
printf("hello");
if (x == 5)
printf("hi");
else
printf("no");
}
a) hi b)hello c) no d) error

©LPU CSE101 C Programming


What will be the output of the
following C code?
#include <stdio.h>
int x;
void main()
{
if (x)
printf("hi");
else
printf("how are u");
}
a) hi
b) how are you
c) compile time error
d) error
©LPU CSE101 C Programming
Control Flow

©LPU CSE101 C Programming


if..else statement

Yes If you have No


time?

Grab
something to
eat along

©LPU CSE101 C Programming


if..else statement
• The if statement executes only when the
condition following if is true.
• It does nothing when the condition is false.
• The if..else statement takes care of the
true and false conditions.

©LPU CSE101 C Programming


if..else statement
• if..else has two blocks.
• One block is for if and it is executed when
condition is non-zero(true).
• The other block is of else and its executed when
condition is zero (false).
Syntax
if (expression)
{
block of statements;
}
else
{
block of statements;
}
©LPU CSE101 C Programming
if..else statement
• The else statement cannot be used without
if.
• No multiple else statements are allowed
with one if.
• else statement has no expression.
• Number of else cannot be greater than
number of if.

©LPU CSE101 C Programming


Ternary conditional operator (?:)
• C code:
if ( marks>= 60 )
printf( "Pass\n");
else
printf( "Fail\n");
• Same code using ternary operator:
– Takes three arguments (condition, value if true, value if
false)
– Our code could be written:
printf("%s\n", grade >= 60 ? "Pass" : "Fail");
– Or it could have been written:
grade >= 60 ? printf(“Pass\n”) :
printf(“Fail\n”);

©LPU CSE101 C Programming


#include<stdio.h>
void main() Example :
{
int a;
Program to
printf(“Enter the number :”); check
scanf(“%d”, &v);
if(v<10) whether
printf(“number is less than 10”);
else number is
printf(“number is greater than 10”);
}
less than 10.

Enter the number: 7


Number is less than 10
or
Enter the number: 100
Number is greater than 10
©LPU CSE101 C Programming
Control Flow

MESSAG
E
DISPLAY

©LPU CSE101 C Programming


What will be the output of the following C code?
#include <stdio.h>
void main()
{
int x = 0;
if (x == 0)
printf("hi");
else
printf("how are u");
printf("hello");
}
a) hi b) how are you c) hello d) hihello

©LPU CSE101 C Programming


Nested if..else
• In if..else statement else block is executed by
default after failure of if condition.
• The nested if...else statement is used when
program requires more than one test expression.
• Test for multiple cases by placing if…else
selection statements inside if…else selection
statement.
• This kind of nesting will be unlimited.

©LPU CSE101 C Programming


Nested if..else
Syntax
if ( condition ) {
block of statements;
}
else if ( condition ) {
block of statements;
}
else {
block of statements;
}

©LPU CSE101 C Programming


#include<stdio.h>
void main()
Program to
{ check
int a;
whether
printf(“Enter the number :”);
scanf(“%d”, &v); number is
if(v<10){ less than 10.
printf(“number is less than 10”);
}
else if(v<100){
printf(“number is less than 100”);
}
}

Enter the number: 1


Number is less than 10
or
Enter the number: 56
Number
©LPU isC less
CSE101 than 100
Programming
MCQ
If you have to make decision based on multiple
choices, which of the following is best suited?

A.if
B.if-else
C.if-else-if
D.All of the above

©LPU CSE101 C Programming


What will be the output of the following C code?
#include <stdio.h>
int main()
{
int x = 0;
if (x == 1)
{
if (x == 0)
printf("inside if\n");
else
printf("inside else if\n");
}
else
printf("inside else\n");
}
a) inside if b) inside else if c) inside else d) compile time error
©LPU CSE101 C Programming
What will be output when you will execute
following c code?
#include<stdio.h>
void main(){
int a=100;
if(a>10)
printf("M.S. Dhoni");
else if(a>20)
printf("M.E.K Hussey");
else if(a>30)
printf("A.B. de villiers");
}

(A) M.S. Dhoni (B) A.B. de villiers


(C) M.S Dhoni D)none of the above
M.E.K Hussey
A.B. de Villiers

©LPU CSE101 C Programming


Forms of if
The if statement can take any of the following forms:
if ( condition ) {
if ( condition )
do this ;
do this ;
and this ;
or
}
if ( condition ) {
else {
do this ;
do this ;
and this ;
and this ;
}
}

if ( condition )
do this ;
if ( condition ) else if ( condition )
do this ; do this ;
else else {
do this ; do this ;
and this ;
©LPU CSE101 C Programming }
#include<stdio.h>
void main() Program to
{
float marks;
scanf(“%f”, &marks);
print grades
if (marks>90){
printf(“Grade A”);
of students
}
else if (marks>80) {
marks.
printf(“Grade B”);
}
else if(marks>70){
printf(“Grade C”);
}
else if (marks >60) {
printf(“Grade D”);
}
}

66.70
Grade D
or
78.00
Grade C C Programming
©LPU CSE101
Forms of if
Decision control Syntax Description
statements
if if (condition){ In these type of statements, if condition is
Statements;} true, then respective block of code is
executed.
if…else if (condition){ In these type of statements, group of
Statement1; statements are executed when condition is
Statement2;} true. If condition is false, then else part
else { statements are executed.
Statement3;
Statement4;}
Nested if if (condition1){ If condition 1 is false, then condition 2 is
Statement1;} checked and statements are executed if it
else is true. If condition 2 also gets failure, then
if(condition2){ else part is executed.
Statement2;}
else
©LPU CSE101 C ProgrammingStatement 3;
break statement
• break is a keyword.
• break allows the programmer to terminate
the loop.
• A break statement causes control to transfer
to the first statement after the loop or block.
• The break statement can be used in nested
loops. If we use break in the innermost loop
then the control of the program is terminated
only from the innermost loop.

©LPU CSE101 C Programming


switch Statement

Day= No Day=
Monday Sunday

Yes

©LPU CSE101 C Programming


switch Statement
• The control statement that allows to make a decision
from the number of choices is called switch.
• Also called switch-case-default.
• The switch statement provides another way to decide
which statement to execute next.
• The switch statement evaluates an expression, then
attempts to match the result to one of several possible
cases.
• Each case contains a value and a list of statements.
• The flow of control transfers to statement associated
with the first case value that matches.
©LPU CSE101 C Programming
switch Statement
Syntax
switch (expression)
{
case constant1:
statements;
break;
case constant2:
statements;
break;
case constant3:
statements;
break;
default:
statements;
}

©LPU CSE101 C Programming


Rules of using switch case
1. Case label must be unique
2. Case label must end with colon
3. Case label must have constant expression
4. Case label must be of integer, character type like case
2, case 1+1, case ‘a’
5. Case label should not be floating point
6. Default can be placed anywhere in switch
7. Multiple cases cannot use same expression
8. Relational operators are not allowed in switch
9. Nesting of switch is allowed.
10. Variables are not allowed in switch case label..

©LPU CSE101 C Programming


Syntax error in switch statement
Variable cannot be
switch(pt){
case count: used as label
printf(“%d”, count);
break;
case 1<8:
Relational operators
printf(“A point”); are not allowed
break;
case 2.5:
printf(“A line”); Floating point number
break; cannot be used
case 3 + 7.7:
printf(“A triangle”);
Floating point number
case 3 + 7.7:
printf(“A triangle”); cannot be used and
break; same expression cannot
case count+5: be used
printf(“A pentagon”);
break;
} constant expression
should be used
©LPU CSE101 C Programming
What is the output of this C code(When 1 is
entered)?
void main()
{
int ch;
printf("enter a value btw 1 to 2:");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("1\n");
default:
printf("2\n");
}
}
A. 1 B. 2 C. 1 2 D. Run time error

©LPU CSE101 C Programming


What is the output of this C code(When 1 is
entered)?
void main()
{
int ch;
printf("enter a value btw 1 to 2:");
scanf("%d", &ch);
switch (ch, ch + 1)
{
case 1:
printf("1\n");
break;
case 2:
printf("2");
break;
}
}
A. 1 B. 2 C. 3 D. Run time error

©LPU CSE101 C Programming


#include<stdio.h>
void main()
{
Program to
int pt;
printf(“Enter the number of nodes:”);
scanf(“%d”, &pt);
show switch
switch(pt){
case 0: statement in
printf(“\nNo Geometry”);
break;
case 1:
geometry
printf(“\nA point”);
break;
case 2:
printf(“\nA line”);
break;
case 3:
printf(“\nA triangle”);
break;
case 4:
printf(“\nA rectangle”);
break;
case 5:
printf(“\nA pentagon”);
break;
default:
printf(“Invalid input”);
}
}

Enter the number of nodes: 2


A line
©LPU CSE101 C Programming
#include<stdio.h>
void main() Program to
{
int key; move a car in
printf(“Press 1 to turn left.”);
printf(“Press 2 to turn right.”);
printf(“Press 3 to increase speed.”);
car game
printf(“Press 4 for break: ”);
scanf(“%d”, &key);
switch(key){
case 1:
printf(“\nTurn left”);
break;
case 2:
printf(“\nTurn right”);
break;
case 3:
printf(“\nIncrease speed”);
break;
case 4:
printf(“\nBreak”);
break;
default:
printf(“Invalid input”);
}
Press 1 to turn left.
}
Press 2 to turn right.
Press 3 to increase speed.
Press 4 for break: 4
Break
©LPU CSE101 C Programming
Next Class: Loop control and
Jump statements

©LPU CSE101 C Programming


cse101@lpu.co.in
©LPU CSE101 C Programming
Outline
• Repetition structure/Control Loop Statements
– for statement
– while statement
– do-while statement
• Jump Statements
– break
– continue
– goto
– return

©LPU CSE101 C Programming


Repetition(Going to School)
Day =
Monday to
Saturday

©LPU CSE101 C Programming


Repetition Statement
• A repetition statement allows you to specify
that an action is to be repeated while some
condition remains true.

©LPU CSE101 C Programming


Looping (repetition)
• What if we want to display hello 500 times?
– Should we write 500 printf statements or
equivalent ?
 Obviously not.
• It means that we need some programming
facility to repeat certain works.
• Such facility is available in form of looping
statements.

©LPU CSE101 C Programming


Loop
• The main idea of a loop is to repeat an action
or a series of actions.

The concept of a loop without condition

©LPU CSE101 C Programming


• But, when to stop looping?
• In the following flowchart, the action is executed
over and over again. It never stops – This is called
an infinite loop
• Solution – put a condition to tell the loop either
continue looping or stop.

©LPU CSE101 C Programming


Loop
• A loop has two parts –
body and condition
Condition
• Body – a statement or a
block of statements that True
will be repeated.
Repeated_Actions False

• Condition – is used to
control the iteration –
either to continue or stop
iterating.

©LPU CSE101 C Programming


Loop statements
• C provides three loop statements:

©LPU CSE101 C Programming


The “while” Statement in C
• The syntax of while statement in C:
Syntax

while (loop repetition condition){


statement; Condition
updating control;
}
True

Repeated_Actions False

While fatigue level is not


reached

©LPU CSE101 C Programming


while statement
while(loop repetition condition)
{
Statements;
}

Loop repetition condition is the condition which


controls the loop.
•The statement is repeated as long as the loop
repetition condition is true.
•A loop is called an infinite loop if the loop
repetition condition is always true.

©LPU CSE101 C Programming


What will be the output of the C
program?
#include<stdio.h>
int main()
{
int i = 4,j = 7;
while(++i < --j)
printf("Loop")
return 0;
}
a) Loop b) Loop Loop c) Loop Loop Loop d)infinite loop

©LPU CSE101 C Programming


What will be the output of the C program?

#include<stdio.h>
int main()
{
int i = 4;
while(i == 4--)
printf("Loop ");
return 0;
}
A. Loop Loop Loop Loop B. Loop Loop loop
C. Compilation Error D. Prints Nothing

©LPU CSE101 C Programming


while statement
Example: This while statement prints numbers 10 down to 1
#include<stdio.h>
int main()
n=10
{
int n=10;
while (n>0){
printf(“%d ”, n); is n>0?

n=n-1;
} True

} Print
n

False
10 9 8 7 6 5 4 3 2 1 n = n -1

Do TEN push ups imposes a


count condition
©LPU CSE101 C Programming
The for Statement in C
• The syntax of for statement in C:
Syntax

for (initialization-expression;
loop-repetition-condition;
update-expression){
statement;
}
• The initialization-expression set the initial value of the
loop control variable.
• The loop-repetition-condition test the value of the
loop control variable.
• The update-expression update the loop control
variable.
©LPU CSE101 C Programming
for statement

for (Initialization; Condition; Updating )


Initialization
{
Repeated_Actions;
}
Condition

True

Repeated_Actions

False

Updating

©LPU CSE101 C Programming


for statement
Example: This for statement prints numbers 10 down to 1
#include<stdio.h>
int main()
n=10
{
int n;
for (n=10; n>0; n=n-1){
is n>0?
printf(“%d ”, n);
} True

} Print
n

False

n = n -1
10 9 8 7 6 5 4 3 2 1
Do TEN push ups = for
count=1; count<=10;
count++
©LPU CSE101 C Programming
©LPU CSE101 C Programming
Nested Loops
• Nested loops consist of an outer loop with one
or more inner loops.
• Eg:
Outer loop
for (i=1;i<=100;i++){
for(j=1;j<=50;j++){ Inner loop


}
}
• The above loop will run for 100*50 iterations.

©LPU CSE101 C Programming


#include<stdio.h>
void main() Program to
{
int i,j,k ; print tables
printf(“Enter a number:”);
scanf(“%d”, &k);
up to a
printf(“the tables from 1 to %d: \n”,k);
for(i=1; i<k; i++){
given
for(j=1; j<=10; j++){ number.
printf(“%d ”,i*j);
} //end inner for loop
printf(“\n”);
} //end outer for loop
getch();
} //end main

Enter a number
4
The tables from 1 to 4
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12CSE101
©LPU 16 20 24 28 32 36 40
C Programming
#include<stdio.h>
#include<conio.h> Program to
void main() display a
{
int i,j; pattern.
printf(“Displaying right angled triangle for 5
rows”);
for(i=1 ; i<=5 ; i++) {
for(j=1 ; j<=i ; j++)
printf(“* ”);
printf(“\n”);
}
}

Displaying right angled triangle for 5 rows


*
**
***
****
*****
©LPU CSE101 C Programming
While vs. for statements

Comparing for and while loops


©LPU CSE101 C Programming
The do-while Statement in C
• The syntax of do-while statement in C:
Syntax
do
{
statement;
} while (condition);

• The statement executed at least one time.


• For second time, If the condition is true, then the
statement is repeated else the loop is exited.

5-23
©LPU CSE101 C Programming
do…while statement

do
{
Repeated_Actions; True Repeated_Actions
} while (Condition);

Condition

False

©LPU CSE101 C Programming


do…while statement
Example: this do…while statement prints numbers 10 down to 1
#include<stdio.h>
int main() n=10
{
int n=10;
do{ Print
printf(“%d ”, n); True
n

n=n-1;
}while (n>0); n = n -1

is n>0?

10 9 8 7 6 5 4 3 2 1
False

©LPU CSE101 C Programming


Difference between while and do..while
while loop do..while loop
1. Condition is specified at the top 1. Condition is mentioned at the bottom
2. Body statements are executed when 2. Body statements are executed at least
the condition is satisfied once even if the expression value
evaluates to false
3. It is an entry controlled loop 3. It is an exit controlled loop
4.Syntax: 4.Syntax:
while (condition) do
statement; {
statements;
}
while (condition);

©LPU CSE101 C Programming


Jump statements
• You have learn that, the repetition of a loop is controlled by
the loop condition.
• C provides another way to control the loop, by using jump
statements.
• There are four jump statements:

©LPU CSE101 C Programming


break statement
• break is a keyword.
• break allows the programmer to terminate
the loop.
• A break statement causes control to transfer
to the first statement after the loop or block.
• The break statement can be used in nested
loops. If we use break in the innermost loop
then the control of the program is terminated
only from the innermost loop.

©LPU CSE101 C Programming


break statement
##include<stdio.h>
Program to
int main()
{ show use of
int n; break
for (n=10; n>0; n=n-1){
statement.
if (n<8)
break;
printf(“%d ”, n);
} //end for
}

10 9 8

©LPU CSE101 C Programming


continue statement
• continue statement is exactly opposite to
break.
• continue statement is used for continuing
the next iteration of the loop statements
• When it occurs in the loop, it does not
terminate, but skips the statements after this
statement

©LPU CSE101 C Programming


continue statement
• In while and do…while loops, the continue
statement transfers the control to the loop condition.
• In for loop, the continue statement transfers the
control to the updating part.

©LPU CSE101 C Programming


continue statement
#include<stdio.h>
Program to
int main()
{
show the use
int n; of continue
for (n=10; n>0; n=n-1){ statement in
if (n%2==1) for loop
continue;
printf(“%d ”, n);
}
}

10 8 6 4 2

©LPU CSE101 C Programming


continue statement
#include<stdio.h> Program to
int main()
show the use
{
int n = 10;
of continue
while(n>0){ statement in
printf(“%d”, n); for loop
For n=9, loop goes to infinite
if (n%2==1) execution
continue;
n = n –1;
}
}
The loop then prints
10 9 9 9 9 9 ………… number 9 over and over
again. It never stops.
©LPU CSE101 C Programming
goto
• Unconditionally transfer control.
• goto may be used for transferring control from one
place to another.
• The syntax is:
goto identifier;
Control is unconditionally transferred to the location of a
local label specified by identifier. For example,
Again:
...
goto Again;

©LPU CSE101 C Programming


goto statement

n=10;

A:
n=10 printf(“%d “, n);
n = n -1;
A

Print if (n>0)
n
goto A;
n = n -1

Output:
is n>0? True A

10 9 8 7 6 5 4 3 2 1
False

©LPU CSE101 C Programming


#include<stdio.h>
void main() Program to
{
int x; show goto
printf(“enter a number: ”);
scanf(“%d”,&x); statement.
if(x%2==0)
goto even;
else
goto odd;
even:
printf(“ %d is even”, x);
return;
odd:
printf(“%d is odd”, x);
}

enter a number: 18
18 is even

©LPU CSE101 C Programming


return statement
• Exits the function.
• return exits immediately from the currently
executing function to the calling routine,
optionally returning a value. The syntax is:
• return [expression];
• For example,
int sqr (int x){
return (x*x);
}

©LPU CSE101 C Programming


©LPU CSE101 C Programming
Introduction
• Presentation of output is very important.
• Formatted functions scanf and printf :
– these functions input data from standard input
stream and
– output data to standard output stream.
• Include the header #include<stdio.h>

©LPU CSE101 C Programming


Standard I/O Functions
• There are many library functions available for
standard I/O.
• These functions are divided into two
categories:
–Unformatted functions
–Formatted functions

©LPU CSE101 C Programming


Formatted Functions
• With Formatted functions, input and output is
formatted as per our requirement
– For example, if different values are to be displayed,
how much field width i.e., how many columns on
screen, is to be used, and how much space between
two values is to be given. If a value to be displayed is
of real type, then how many decimal places to output
• Formatted functions are:
– printf()
– scanf()

©LPU CSE101 C Programming


Formatted output with printf function
• The printf() function: (Formatted output)
printf() is an output function that takes text and values from within
the program and sends it out onto the screen.
In general terms, the printf function is written as:
Syntax
printf(“format-control-string”, arg1,arg2,……….,argN);

• The format-control-string can contain:


– Characters that are simply printed as they are
– Conversion specifications that begin with a % sign
– Escape sequences that begin with a \ sign
 The arguments can be written as constants, single variable or array
names, or more complex expressions.

©LPU CSE101 C Programming


Example
printf(“Area of circle is %f units
\n”, area);
In this :-
“Area of circle is %f units \n”- is a
control string.
area - is a variable whose value will be printed.
%f- is the conversion specifier indicating the type of
corresponding value to be printed.

©LPU CSE101 C Programming


Formatted Functions
The scanf() function: (Formatted input)
scanf() is a function that reads data from the keyboard. It
interprets character input to the computer and stores the
interpretation in specified variable(s).
In general terms, the scanf function is written as:
Syntax
scanf (format-control-string, arg1, arg2,………., argN);

• The format-control-string can contain:


– Describes the format of the input.
– Conversion specifications that begin with a % sign.
• The arguments are the pointers to variables in which the input
will be stored.

©LPU CSE101 C Programming


Example:
scanf(“%s %d %f”, name, &age,
&salary);
In this :-
“%s %d %f”- is a control string.
name – is a string argument and it’s a array name
and implicit memory address reference.
age - is a decimal integer variable preceded by &.
salary - is floating-point value preceded by &.

©LPU CSE101 C Programming


Reading data
Conversion Specifier Description
d Read signed decimal integer
i Read a signed decimal integer
u Read an unsigned decimal integer
h or l Used before any integer conversion specifier to
indicate that a short or long integer is to be input,
respectively
e, E, f, g, G Read a floating-point value
c Read a character
s Read a string
p Read an address
% Skip the percent sign(%) in the input

©LPU CSE101 C Programming


#include <stdio.h>
int main( void )
{ int a, c;
float f;
char day[10];
printf( "Enter integers: " );
scanf( "%d %u", &a, &c);

printf( "Enter floating-point numbers:" );


scanf( "%f", &f);

printf( "%s", "Enter a string: " );


scanf( "%8s", day );
}

Enter integers: -89 23


Enter floating-point numbers:
1.34256
Enter a string:
monday

©LPU CSE101 C Programming


Unformatted functions
• The unformatted functions work only with character data
type.
• They do not require format conversion symbol for formatting
of data types because they work only with character data type
• Unformatted functions are:
– getchar() and putchar()
– getch() and putch()
– gets() and puts()

©LPU CSE101 C Programming


Unformatted Functions
• C has three types of I/O functions:
i. Character I/O
ii. String I/O
iii. File I/O

©LPU CSE101 C Programming


getchar()
• This function reads a character-type data from
standard input.
• It reads one character at a time till the user
presses the enter key.
Syntax
Variable-name = getchar();

Example:
char c;
c = getchar();
©LPU CSE101 C Programming
#include<stdio.h>
void main()
{
char c;
printf(“enter a character”);
c=getchar();
printf(“c = %c ”,c);
}

Enter a character k
c = k

©LPU CSE101 C Programming


putchar()
• This function prints one character on the
screen at a time which is read by standard
input.
Syntax

putchar( variable name);

Example: char c= ‘c’;


putchar (c);

©LPU CSE101 C Programming


#include<stdio.h>
void main()
{
char ch;
printf(“enter a character: ”);
scanf(“%c”, ch);
putchar(ch);
}

enter a character: r
r

©LPU CSE101 C Programming


getch() & getche()
• These functions read any alphanumeric character
from the standard input device
• The character entered is not displayed by the getch()
function until enter is pressed
• The getche() accepts and displays the character.
• The getch() accepts but does not display the
character.
Syntax

getche();

©LPU CSE101 C Programming


#include<stdio.h>
void main()
{
printf(“Enter two alphabets:”);
getche();
getch();
}
Enter two alphabets a

©LPU CSE101 C Programming


putch()
This function prints any alphanumeric character
taken by the standard input device
#include<stdio.h>
Example:
void main()
{
char ch;
printf(“Press any key to continue”);
ch = getch();
printf(“ you pressed:”);
putch(ch);
}

Press any key to continue


You pressed : e

©LPU CSE101 C Programming


gets()
String I/O
• This function is used for accepting any string
until enter key is pressed (string will be
covered later)
Syntax
char str[length of string in number];
gets(str);

©LPU CSE101 C Programming


#include<stdio.h>
void main()
{
char ch[30];
printf(“Enter the string:”);
gets(ch);
printf(“Entered string: %s”, ch);
}

Enter the string: Use of data!


Entered string: Use of data!

©LPU CSE101 C Programming


puts()
• This function prints the string or character
array. It is opposite to gets()

Syntax
char str[length of string in number];
gets(str);
puts(str);

©LPU CSE101 C Programming


#include<stdio.h>
void main()
{
char ch[30];
printf(“Enter the string:”);
gets(ch);
puts(“Entered string:”);
puts(ch);
}

Enter the string: puts is in use


Entered string: puts is in use

©LPU CSE101 C Programming


Mcq
Choose a C unformatted input output function
below.
A) gets(), puts()
B) getchar(), putchar()
C) A & B
D) None of the above

©LPU CSE101 C Programming


MCQ
What is the output of C program.?
int main()
{
char ch='A';
ch=getchar();
putchar(ch);
return 0; }//input= S
A) A
B) B
C) S
D) Compiler error

©LPU CSE101 C Programming

You might also like