You are on page 1of 650

CSE101-Lec#1

Program Development in C(Development Environment/Compilation phases)

CSE101-Computer Programming
C Program Development Environment

C program goes through various phases such as:


⮚ Creating a program with editor
⮚ Execution of preprocessor program
⮚ Compilation
⮚ Assembly
⮚ Linking
⮚ Loading
⮚ Executing

CSE101-Computer Programming
Overview of phases

1. Source code is written in the text editor to generate .c


extension file(also known as source code file)
2. Pre-processor works and generates Expanded Source Code
file with extension (.I)
3. After this phase, compiler converts this expanded source
code into assembly code and syntax errors are identified. The
extension of the assembly code would be (.s)
4. This assembly code is then sent to the assembler, which
converts the assembly code into object code.(.o/.obj)
5. After this phase, linker works and it combines the object file
with library routines to generate the final executable file(.exe
extension)
6. After this phase, loader loads the .exe file into RAM and
CPU starts execution

CSE101-Computer Programming
Program is created in
Editor Disk the editor and stored
on disk.
Preprocessor program
Preprocessor Disk processes the code.

Compiler Compiler compiles the code and creates


Assembler Disk assembly code and further assembler
creates object code and stores
it on disk.
Linker Linker links the object
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.
CSE101-Computer Programming
CSE101-Computer Programming
Key points

▪ Preprocessing:
➢Generates expanded source code
➢Removal of comments
➢Expansion of included files(e.g. Header files)

▪ Compilation:
➢Detects syntax errors
➢Preprocessed code is translated to assembly instructions specific to the target
processor architecture.
➢The existence of this step allows for C code to contain inline assembly
instructions and for different assemblers to be used.

CSE101-Computer Programming
Key points

▪ Assembly:
➢This stage is used to translate the assembly instructions to object code
➢The output consists of actual instructions to be run by the target processor.

▪ Linking:
➢The result of this stage is the final executable program.
➢Mainly, all the programs written in C use library functions. These library functions are
pre-compiled, and the object code of these library files is stored with '.lib' (or '.a')
extension. The main working of the linker is to combine the object code of library files
with the object code of our program.
➢Sometimes the situation arises when our program refers to the functions defined in
other files; then linker plays a very important role in this. It links the object code of
these files to our program.
➢So, it links the object code of our program with the object code of the library files and
other files.

CSE101-Computer Programming
Polling Questions
Which of the following component will point out the syntax errors in the
code?
A. Linker
B. Compiler
C. Loader
D. Preprocessor

CSE101-Computer Programming
Extension of expanded source code file is
A. (.obj)
B. (.i)
C. (.s)
D. (.exe)

CSE101-Computer Programming
Which of the following component generates the final .exe file?
A. Linker
B. Loader
C. Assembler
D. Compiler

CSE101-Computer Programming
Role of preprocessor is to:
A. Detect syntax errors
B. Generate object code
C. Combine various object files and library files together
D. Include the code of header files at the point, where they are included to generate
expanded source code

CSE101-Computer Programming
Which of the following extension is valid for a file containing assembly code?
A. (.obj)
B. (.i)
C. (.s)
D. (.exe)

CSE101-Computer Programming
CSE101-Lec#2
Structured Programming Using Algorithm and Flowchart(or
Program development tools)
Outline
• Structured programming using
• Algorithm and
• Flowchart

©LPU CSE101 C Programming


Program Development Tools
• Algorithm
• Flowchart

©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


General 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[Example 1]

Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to
sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

©LPU CSE101 C Programming


Algorithm: Calculate area of circle[Example 2]

Step 1: Start
Step 2: Declare variables radius and area.
Step 3: Read value of radius.
Step 4: Apply the expression as specified below
and assign the result in area
area←3.14*radius*radius
Step 5: Display area
Step 6: Stop

©LPU CSE101 C Programming


Algorithm: Swap the values of two variables[Example 3]

Step 1: Start
Step 2: Declare three variables: num1,num2 and temp
Step 3: Read values of num1 and num2
Step 4: Assign the value of num1 in temp
temp ←num1
Step 5: Assign the value of num2 in num1
num1 ←num2
Step 6: Assign the value of temp in num2
num2 ←temp
Step 7: Display swapped values of num1 and num2
Step 8:Stop

©LPU CSE101 C Programming


Practice questions for Algorithms
• Write an algorithm to calculate and display simple interest
and final amount
• Write an algorithm to swap the values of 2 numbers without
using temporary variable
• Write an algorithm to convert temperature from degree
Celsius to degree Fahrenheit and vice versa
• Write an algorithm to multiply, divide and subtract two
numbers and display their individual results
• Write an algorithm to read the prices and quantities of 5
items and display the final amount after applying a discount
of 10 percent
• Write an algorithm to convert distance from km to m and vice
versa
• Write an algorithm to display the areas of triangle, square and
rectangle and display their individual results.

©LPU CSE101 C Programming


Q1
Which of the following characteristic is not
desired in good algorithm?
A. Ambiguity
B. Correctness
C. Simplicity
D. Abstraction

©LPU CSE101 C Programming


Q1
Which of the following characteristic is not
desired in good algorithm?
A. Ambiguity
B. Correctness
C. Simplicity
D. Abstraction

©LPU CSE101 C Programming


Q2
Q2:Algorithm is:
A. Infinite set of steps
B. Pictorial representation
C. Textual Computational solution
D. Actual Code for the solution

©LPU CSE101 C Programming


Q2
Q2:Algorithm is:
A. Infinite set of steps
B. Pictorial representation
C. Textual Computational solution
D. Actual Code for the solution

©LPU CSE101 C Programming


Q3
Q3.Efficient algorithm is one which takes
A. Less time
B. Less space
C. More time and space
D. Both A and B options

©LPU CSE101 C Programming


Q3
Q3.Efficient algorithm is one which takes
A. Less time
B. Less space
C. More time and space
D. Both A and B options

©LPU CSE101 C Programming


CSE 101 COMPUTER PROGRAMMING
OUTLINE
• In this lecture we will cover
• Character set
• Identifiers
• Keyword
• Data types

CSE 101 COMPUTER 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


CSE 101 COMPUTER PROGRAMMING
Introduction to C
• Like every language C programming language requires basic building
blocks to communicate with the computer.
• So we require Characters
• Character set
• Words(keywords and identifiers)
• Statement (instructions) Words
• Program
Statements

Programs
CSE 101 COMPUTER 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.
CSE 101 COMPUTER PROGRAMMING
Meaningfulness
• Let us look to some words
• saslc, enp, keib, rac, llab

• Rearrange
• Class, pen, bike, car, ball

• This is the influence of adding meaning by logical and


sensible grouping in mode of communication through
language

CSE 101 COMPUTER PROGRAMMING


Token
• Every single element in a C Program is Token

CSE 101 COMPUTER 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

CSE 101 COMPUTER PROGRAMMING


Lets Identify the following:
square circle

ellipse square

circle ellipse

CSE 101 COMPUTER 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

CSE 101 COMPUTER 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.

CSE 101 COMPUTER PROGRAMMING


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

Wrong identifiers name


1_engine;
break;
@car-roof;
CSE 101 COMPUTER PROGRAMMING
Q Which of the following is not a valid C variable name?

A) int number;
B) float rate;
C) int variable_count;
D) int $main;

CSE 101 COMPUTER 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.
CSE 101 COMPUTER 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

CSE 101 COMPUTER PROGRAMMING


Q All keywords in C language are in___

A) UpperCase letters
B) LowerCase letters
C) Digits
D) CamelCase letters

CSE 101 COMPUTER 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


Flowchart Example 1-Adding 2 numbers

©LPU CSE101 C Programming


Flowchart Example 2-Displaying greatest of 2 numbers

©LPU CSE101 C Programming


Flowchart Example 3-Checking whether a person is
eligible to vote or not

©LPU CSE101 C Programming


Flowchart Example 3-Greatest of 3 numbers

©LPU CSE101 C Programming


Practice questions for flowcharts
Write solutions using RAPTOR and without RAPTOR(Basic conventions)

1) Draw a flowchart to check whether a given


number is even or odd
2) Draw a flowchart to calculate simple interest and
final amount
3) Draw a flowchart to calculate the area of a circle
4) Draw a flowchart to display the roots of a
quadratic equation
5) Draw a flowchart to check whether the given
number is a multiple of 5 or not
6) Draw a flowchart to swap the values of two
variables without the help of temporary variable

©LPU CSE101 C Programming


Q1
Which of the following symbol is used to denote
decision or condition in a flowchart?
A. Oval
B. Rectangle
C. Diamond
D. Small Circle

©LPU CSE101 C Programming


Q1
Which of the following symbol is used to denote
decision or condition in a flowchart?
A. Oval
B. Rectangle
C. Diamond
D. Small Circle

©LPU CSE101 C Programming


Q2
Oval symbol in a flowchart is used to represent
A. Input/Output
B. Decision
C. Connector
D. Start and Stop

©LPU CSE101 C Programming


Q2
Oval symbol in a flowchart is used to represent
A. Input/Output
B. Decision
C. Connector
D. Start and Stop

©LPU CSE101 C Programming


Q3
Which of the following symbol is used to denote
processing part in a flowchart?
A. Oval
B. Rectangle
C. Diamond
D. Parallelogram

©LPU CSE101 C Programming


Q3
Which of the following symbol is used to denote
processing part in a flowchart?
A. Oval
B. Rectangle
C. Diamond
D. Parallelogram

©LPU CSE101 C Programming


More practice questions on Flowchart
Write solutions using RAPTOR and without RAPTOR(Basic conventions)

1) Draw a flowchart to calculate circumference


of circle
2) Draw a flowchart to display the equivalent
grade student has achieved after calculating the
percentage of marks in 5 subjects[A+,A,Fail]
3) Draw a flowchart to calculate the area of
triangle, cylinder and rhombus
4) Draw a flowchart to calculate the compound
interest
©LPU CSE101 C Programming
CSE 101 COMPUTER 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.

CSE 101 COMPUTER PROGRAMMING


• Lets see a mathematics problem:

CSE 101 COMPUTER 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
dist_travelled = ?
So, Circumference of circle = 2 * pi * r
15 Integer( int in C )
dist_travelled = 2 * 3.14 * radius
dist_travelled = 6.28 * 15
dist_travelled = 94.2 Ans.
3.14 Real (float in C)

94.2 Real (float in C)

CSE 101 COMPUTER PROGRAMMING


My-Grades
2. Five students have appeared for Mathematics exam and their
respective marks are
84,34,97,58,64
consider the rank bands and their respective grades as
80 to 100 –A
60 to 79 –B
40 to 59 –C
less than 40 – D
So find the grade for each students?

CSE 101 COMPUTER PROGRAMMING


Marks as integer Grades as character
Sol: Given-
84 char in C
M1=84, G1=? A

M2=34, G2=? 34 D
char in C

M3=97, G3=? 97 A char in C

M4=58, G4=? C char in C


58
M5=64, G5=?
64 B char in C

CSE 101 COMPUTER PROGRAMMING


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

CSE 101 COMPUTER PROGRAMMING


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

Data
Type
CSE 101 COMPUTER PROGRAMMING
List of Data Types
Type Size Minimal range
(bytes)
char 1 -128 to 127
unsigned char 1 0 to 255
int 2 or 4 -32768 to 32767
unsigned int 2 or 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
CSE 101 COMPUTER 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

CSE 101 COMPUTER 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

CSE 101 COMPUTER 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. long radius=123456;
int cost=100;
long int value;
short int si;

CSE 101 COMPUTER 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 signed
• There are also long unsigned
integers having range from -
int with range 0 to
2147483648 to 2147483647
4294967295
• Example:
int firstvalue=10;
long int WaterLevel; • Example:
unsigned long count=567898;
unsigned short int page;

CSE 101 COMPUTER 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.

CSE 101 COMPUTER 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

CSE 101 COMPUTER 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

CSE 101 COMPUTER 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

CSE 101 COMPUTER 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’;

CSE 101 COMPUTER 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
CSE 101 COMPUTER PROGRAMMING
• Remember car example?

15
%d
Program 90
%d
3.14
%d

15
%d
Program 94.2
3.14 %f
%f

CSE 101 COMPUTER PROGRAMMING


• Grade example:

84 %d %c A

34 %c D
%d
97 %d Program %c A
58 %d %c C

64 %d %c B

CSE 101 COMPUTER PROGRAMMING


Size of float, double and long double in Bytes are.?
A) 4, 8, 16
B) 4, 8, 10
C) 2, 4, 6
D) 4, 6, 8

CSE 101 COMPUTER PROGRAMMING


Ans B

CSE 101 COMPUTER PROGRAMMING


Types of Real numbers in C are.?
A) float
B) double
C) long double
D) All the above

CSE 101 COMPUTER PROGRAMMING


Ans D

CSE 101 COMPUTER PROGRAMMING


Q: Which is correct with respect to size of the datatypes?
A. char > int > float
B. int > char > float
C. char < int < double
D. double > char > int

CSE 101 COMPUTER PROGRAMMING


Ans C

CSE 101 COMPUTER PROGRAMMING


Next Lecture: Constants
Variables
Expressions
Operators
cse101@lpu.co.in
CSE101-Lec#5-First Part
Operators

©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.

c=a+b + and = are the operator and


a, b and c 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
Operato Description Example (a=4 and b=2)
r
+ 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


Arithmetic Operators
If the radius of car wheel is 15inch then what will the
diameter and calculate distance traveled after one rotation
of that wheel? Arithmetic
Operators
Sol:
r = 15
diameter = r + r = 2 * r = 2 * 15 = 30
dist_travelled = pi * d
dist_travelled = pi * diameter
= 3.14 * 30 = 94.2

©LPU CSE101 C Programming


Arithmetic Operators
To get the remainder of the integer value.
Eg:
3)14(4
14 mod 3 = 2
12
17 mod 2 = 1 2
190 mod 3 = 1

Q:Suppose we have to distribute 10 chocolates among 3 students


equally then after equal distribution how many chocolates will be
left?
Sol: 10 mod 3 = 1
So 1 chocolate will be left as all 3 students will have 3
chocolates each.

©LPU CSE101 C Programming


Q1
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i = -3;
int k = i % 2;
printf("%d\n", k);
return 0;
}
A. Compile time error
B. -1
C. 1
D. None of these

©LPU CSE101 C Programming


Q2
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i = 3;
int l = i / -2;
int k = i % -2;
printf("%d %d\n", l, k);
return 0;
}
A. Compile time error
B. -1 1
C. 1 -1
D. None of these

©LPU CSE101 C Programming


Q4
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int x = 5.3 % 2;
printf("Value of x is %d", x);
return 0;
}
A. Value of x is 2.3
B. Value of x is 1
C. Value of x is 0.3
D. Compile time error

©LPU CSE101 C Programming


Q5
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int a = 10;
double b = 5.6;
int c;
c = a + b;
printf("%d", c);
return 0;
}
A. 15
B. 16
C. 15.6
D. 10

©LPU CSE101 C Programming


⮚Unary Operator
These operator requires only one operand.
Operato Description Example(count=1)
r
+ 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


Difference between Prefix and Postfix
• Unary Prefix increment/ decrement performs the operation first, and then the
value is assigned/ or used
Example:
Consider x=2, then
y = ++x; is equivalent to writing
//x = x + 1;
//y = x;
So eventually x will be incremented by 1, i.e x will become 3, and then the value 3 will
be assigned to y
• Unary Postfix increment/ decrement will assign/ or use the value first and then the
operation is performed
Example:
Consider x=2, then
y = x++; is equivalent to writing
//y = x;
//x=x+1;
Here y will take value 2, and then the value of x will be increment by 1, and x becomes
©LPU3.
CSE101 C Programming
Difference between Prefix and Postfix
Explanation:
• Example:
• Initialize x to 3
#include<stdio.h>
• Assign y the value we get
int main() { by evaluating the expression
int x = 3, y, z; x++, i.e, the value of x
y = x++; before increment then
z = ++x; increment x.
printf(“\n%d,%d,%d”,x,y,z); • Increment x then assign z
return 0; the value we get by
evaluating the expression
}
++x, i.e, value of x after the
Output: increment.
5, 3, 5 • Print these values

©LPU CSE101 C Programming


Q1
What will be the output of following code?
#include <stdio.h>
int main()
{
int a=1,b=1,c;
c = a++ + b;
printf("%d,%d,%d", a,b,c);
return 0;
}
A. 2,1,1
B. 1,2,1
C. 2,1,2
D. 1,1,2

©LPU CSE101 C Programming


Q2
What will be the output of following code?
#include <stdio.h>
int main()
{
int d, a = 1, b = 2;
d = a++ + ++b;
printf("%d %d %d", d, a, b);
return 0;
}
A. 4 2 2
B. 3 1 2
C. 4 2 3
D. 3 2 3

©LPU CSE101 C Programming


Q3
What will be the output of following code?
#include <stdio.h>
int main()
{
int i = 0;
int x = i++;
int y = ++i;
printf("%d % d\n", x, y);
return 0;
}
A. 0, 2
B. 0, 1
C. 1, 2
D. 1, 1

©LPU CSE101 C Programming


Q4
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int x = 4, y, z;
y = --x;
z = x--;
printf("%d%d%d", x, y, z);
return 0;
}
A. 3 2 3
B. 2 3 3
C. 3 2 2
D. 2 3 4

©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 than the (a < b) value is 1(true)
value of right operand, if yes then condition becomes true.
<= less than or equal to, checks if the value of left operand is less (a <= b) value is 1 (true).
than or equal to the value of right operand, if yes then
condition becomes true.

> greater than, checks if the value of left operand is greater than (a > b) value is 0 (false).
the value of right operand, if yes then condition becomes true.

>= greater than or equal to, checks if the value of left operand is (a >= b) value is 0 (false).
greater than or equal to the value of right operand, if yes then
condition becomes true.

== equality ,checks if the value of two operands is equal or not, if (a == b) value is 0


yes then condition becomes true. (false).

!= inequality, checks if the value of two operands is equal or not, (a != b) value is 1 (true).
if values are not equal then condition becomes true.
©LPU CSE101 C Programming
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 = 1 (true)
So, Sam is elder than Tom.
S1 == T1 = 0 (false)

©LPU CSE101 C Programming


Q1
What will be the output of following code?
#include <stdio.h>
int main()
{
int a=1,b=2,c;
c=a>b;
printf("\n%d",c);
return 0;
}
A. 0
B. 1
C. 2
D. None of these

©LPU CSE101 C Programming


Q2
What will be the output of following code?
#include <stdio.h>
int main()
{
int a=1,b=2;
printf("\n%d",a!=b);
return 0;
}
A. 0
B. 1
C. 2
D. None of these

©LPU CSE101 C Programming


Q3
What will be the final value of d in the following C code?
#include <stdio.h>
int main()
{
int a = 10, b = 5, c = 5;
int d;
d = b + c == a;
printf("%d", d);
return 0;
}
A. Syntax error
B. 1
C. 5
D. 10

©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 (5>3 && 5<10) value is
are 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


Logical Operator
Grade system :
If (Marks >=90 || marks == 100)
students performance is excellent.
If (Marks <= 40 && attendance < 75)
student is detained.

©LPU CSE101 C Programming


Q1
//What will be the output of following code?
#include <stdio.h>
int main()
{
int a = 10, b = 0,c;
c=a&&b;
printf("%d",c);
}
A. 0
B. 1
C. -1
D. None of these

©LPU CSE101 C Programming


Q2
What will be the output of following code?
#include <stdio.h>
int main()
{
int a = 10, b = 0,c=2,d;
d=a&&b||c-2;
printf("%d",d);
}
A. 0
B. 1
C. -1
D. None of these

©LPU CSE101 C Programming


Q3
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int x = 1, y = 0, z = 5;
int a = x && y || z++;
printf("%d", z);
return 0;
}
A. 6
B. 5
C. 0
D. None of these

©LPU CSE101 C Programming


Q4
What will be the output of following code?
#include <stdio.h>
int main()
{
int x = 1, y = 0, z = 5;
int a = ++ && x && yz ;
printf("%d", z);
return 0;
}
A. 6
B. 5
C. 0
D. None of these

©LPU CSE101 C Programming


CSE101-Lec#5-Second Part
Operators

©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


⮚Assignment Operator
They are used to assign the result of an expression on right side to a
variable on left side.
Operato Description Example(a=4 and b=2)
r
+= 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


⮚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
Explanation
• The & (bitwise AND) in C takes two numbers as operands and does
AND on every bit of two numbers. The result of AND is 1 only if
both bits are 1.
• The | (bitwise OR) in C takes two numbers as operands and does
OR on every bit of two numbers. The result of OR is 1 if any of the
two bits is 1.
• The ^ (bitwise XOR) in C takes two numbers as operands and does
XOR on every bit of two numbers. The result of XOR is 1 if the two
bits are different.
• The << (left shift) in C takes two numbers, left shifts the bits of the
first operand, the second operand decides the number of places to
shift.
• The >> (right shift) in C takes two numbers, right shifts the bits of
the first operand, the second operand decides the number of
places to shift.
• The ~ (bitwise NOT) in C takes one number and inverts all bits of it

©LPU CSE101 C Programming


Program Example
#include <stdio.h> • Output:
int main() a = 2, b = 4
{ a&b = 0
int a = 2, b = 4; a|b = 6
printf("a = %d, b = %d\n", a, b); a^b = 6
printf("a&b = %d\n", a & b); ~a = -3
printf("a|b = %d\n", a | b); b<<1 = 8
printf("a^b = %d\n", a ^ b); b>>1 = 2
printf("~a = %d\n", a = ~a);
printf("b<<1 = %d\n", b << 1);
printf("b>>1 = %d\n", b >> 1);
return 0;
}

©LPU CSE101 C Programming


Explanation

©LPU CSE101 C Programming


©LPU CSE101 C Programming
Q1
What will be the output of following code?
#include<stdio.h>
int main()
{
int a=10,b=5;
printf("%d",a&b);
return 0;
}
A. 10
B. 5
C. 0
D. 1

©LPU CSE101 C Programming


Q2
What will be the output of following code?
#include<stdio.h>
int main()
{
int a=7,b=5;
printf("%d",a|b);
return 0;
}
A. 7
B. 5
C. 12
D. 0

©LPU CSE101 C Programming


Q3
What will be the output of following code?
#include<stdio.h>
int main()
{
int a=8,b=3;
printf("%d",a^b);
return 0;
}
A. 8
B. 3
C. 1
D. 11

©LPU CSE101 C Programming


Q4
What will be the output of following code?
#include<stdio.h>
int main()
{
int a=10;
printf("%d",~a);
return 0;
}
A. 11
B. -11
C. 9
D. -9

©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


Explanation
COMMA OPERATOR
• The comma operator in C takes two operands. It works by evaluating the first and
discarding its value, and then evaluates the second and returns the value as the
result of the expression.
• Comma separated operands when chained together are evaluated in left-to-right
sequence with the right-most value yielding the result of the expression.
• Among all the operators, the comma operator has the lowest precedence. For
example,
int a=2, b=3, x=0;
x = (++a, b+=a);
Now, the value of x = 6.
sizeof operator
sizeof is a unary operator used to calculate the sizes of data types.
It can be applied to all data types.
The operator returns the size of the variable, data type or expression in bytes.
'sizeof' operator is used to determine the amount of memory space that the
variable/expression/data type will take. For example,
sizeof(char) returns 1, that is the size of a character data type
©LPU CSE101 C Programming
• Comma operator can be used like:
for(i=0 , j=1 ; i>10 ; i++ , j++)
• To know space occupied by variable in computer memory we use
sizeof() operator.
char choice;
int char_sz = sizeof(choice); // 1 because char is 1byte
• If we are adding float number and integer number and we require
output in float then integer number is converted to float using type
cast operator.
int num1;
float num2, sum;
sum= (float) num1 + num2;

©LPU CSE101 C Programming


Lecture-5(Part-2)Operators
Precedence and Associativity of
Operators
Precedence of Operators
• The precedence of operators determine a rank for the
operators. The higher an operator's precedence or
priority,

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


Precedence-Example

©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


Associativity-Example

©LPU CSE101 C Programming


©LPU CSE101 C Programming
©LPU CSE101 C Programming
Lecture-5(Part-2)Operators
Precedence and Associativity of
Operators
Precedence of Operators
• The precedence of operators determine a rank for the
operators. The higher an operator's precedence or
priority,

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


Precedence-Example

©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


Associativity-Example

©LPU CSE101 C Programming


©LPU CSE101 C Programming
©LPU CSE101 C Programming
Consider
int a=0,b=1,c=-1
float x=2.5,y=0.0

©LPU CSE101 C Programming


Practice questions(Q1)
#include <stdio.h>
int main()
{
double b = 5 % 3 & 4 + 5 * 6;
printf("%lf", b);
return 0;
}
A. 2
B. 30
C. 2.000000
D. 5

©LPU CSE101 C Programming


(Q2)
#include <stdio.h>
int main()
{
double b = 3 && 5 & 4 % 3;
printf("%lf", b);
return 0;
}
A. 3.000000
B. 4.000000
C. 5.000000
D. 1.000000

©LPU CSE101 C Programming


(Q3)
What will be the output of the following C code?
#include <stdio.h>
int main()
{
double b = 5 & 3 && 4 || 5 | 6;
printf("%lf", b);
return 0;
}
A. 1.000000
B. 0.000000
C. 7.000000
D. 2.000000

©LPU CSE101 C Programming


(Q4)
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int b = 5 + 7 * 4 - 9 * (3, 2);
printf("%d", b);
}
A. 6
B. 15
C. 13
D. 21

©LPU CSE101 C Programming


(Q5)
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int b = 4 * 6 + 3 * 4 < 3 ? 4 : 3;
printf("%d\n", b);
}
A. 3
B. 33
C. 34
D. 4

©LPU CSE101 C Programming


(Q6)
Which of the following option is the correct representation of
the following C statement[As per precedence rule only]?
e = a * b + c / d * f;
A. e = (a * (b +(c /(d * f))));
B. e = ((a * b) + (c / (d * f)));
C. e = ((a * b) + ((c / d)* f));
D. Both e = ((a * b) + (c / (d * f))); and e = ((a * b) + ((c / d)* f));

©LPU CSE101 C Programming


(Q7)
Which of the following operators has an associativity from Right
to Left?
A. <=
B. <<
C. ==
D. +=

©LPU CSE101 C Programming


(Q8)

What will be the output of the following C code?


#include <stdio.h>
int main()
{
int a = -1, b = 4, c = 1, d;
d = ++a && ++b || ++c;
printf("%d, %d, %d, %d\n", a, b, c, d);
return 0;
}
A. 0, 4, 2, 1
B. 0, 5, 2, 1
C. -1, 4, 1, 1
D. 0, 5, 1, 0

©LPU CSE101 C Programming


CSE101-Lec#6-Part-1
• Control structures(Decision control
statements/ or Condition Statements)

©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;
©LPU CSE101 C Programming
4. Go to school.
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(Condition)
• if, if…else, if-else-if, Nested-if ,switch
– Repetition structures (iteration)
• while, do…while, for

©LPU CSE101 C Programming


Condition Statements(or Decision control
statements or Branching 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
– If-else-if statement
– Nested if statement
– switch statement

©LPU CSE101 C Programming


©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
int 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”);
return 0;
}

Enter the number: 6


Number is less than 10

©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


#include<stdio.h>
int 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”);
return 0;
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


Q1
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int x = 5;
if (x < 1)
printf("hello");
if (x == 5)
printf("hi");
else
printf("no");
return 0;
}
A. hi
B. hello
C. no
D. error

©LPU CSE101 C Programming


Q2
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int x = 0;
if (x == 0)
printf("hi");
else
printf("how are u");
printf("hello");
return 0;
}
A. hi
B. how are you
C. hello
D. hihello

©LPU CSE101 C Programming


Q3
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int x = 5;
if (x < 1);
printf("Hello");

}
A. Nothing will be printed
B. Compile time error
C. Hello
D. Logical error

©LPU CSE101 C Programming


Q4
#include<stdio.h>
A. Hi
int main()
{ B. Hello
float x=2.3;
if(x==2.3)
C. Compile time error
{ D. None of these
printf("Hi");
}
else
{
printf("Hello");
}
return 0;
}

©LPU CSE101 C Programming


Q5
#include<stdio.h> A. Hi
int main()
{ B. Hello
int x=-1; C. Compile time error
if(x)
D. None of these
{
printf("Hi");
}
else
{
printf("Hello");
}
return 0;
}

©LPU CSE101 C Programming


Q6
What is the output of this C
code?
A. True
#include <stdio.h> B. False
int main() C. Compile time error
{ D. None of these
float f = 0.1;
if (f == 0.1)
printf("True");
else
printf("False");
return 0;
}
©LPU CSE101 C Programming
If-else-if
• if-else-if statement is used when program requires
more than one test expression.
• We can check multiple conditions, and what so ever condition
is true, that part will work
• Here, a user can decide among multiple options. The C if
statements are executed from the top down. As soon as one
of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the C else-if
ladder is bypassed. If none of the conditions are true, then
the final else statement will be executed.

©LPU CSE101 C Programming


If-else-if ladder
Syntax
if ( condition ) {
block of statements;
}
else if ( condition ) {
block of statements;
}
else {
block of statements;
}

©LPU CSE101 C Programming


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

Enter the number: 1


Number is less than 10
or
Enter the number: 56
Number
©LPU isC less
CSE101 than 100
Programming
#include<stdio.h>
int main()
{
Program to
float marks;
scanf(“%f”, &marks); print grades
if (marks>90){
printf(“Grade A”); of students
}
else if (marks>80) {
printf(“Grade B”);
marks.
}
else if(marks>70){
printf(“Grade C”);
}
else if (marks >60) {
printf(“Grade D”);
}
return 0;
}

66.70
Grade D
or
78.00
Grade C C Programming
©LPU CSE101
Q1
#include <stdio.h>
int main() A. inside if
{ B. inside elseif
int x = 1; C. inside if
if (x > 0) inside elseif
printf("inside if\n");
D. Compile time error
else if (x > 0)
printf("inside elseif\n");
}

©LPU CSE101 C Programming


Q2
What will be the output of the
following C code? A. true
#include <stdio.h>
B. false
int main()
{
C. Compile time error
int x = 0; D. undefined behaviour
if (x++)
printf("true\n");
else if (x == 1)
printf("false\n");
}

©LPU CSE101 C Programming


Q3
What will be the output of the following
C code?
#include <stdio.h> A. false, 0
int main() B. true, 0
{
C. true, 10
int x = 0;
if (x == 0) D. compile time error
printf("true, ");
else if (x = 10)
printf("false, ");
printf("%d\n", x);
return 0;
}

©LPU CSE101 C Programming


Nested if
• A nested if in C is an if statement that is the
target of another if statement. Nested if
statements means an if statement inside
another if statement. C allows us to nested if
statements within if statements, i.e, we can
place an if statement inside another if
statement.

©LPU CSE101 C Programming


Syntax
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
©LPU CSE101 C Programming
Program example
// C program to illustrate nested-if statement
#include <stdio.h>
Output
int main() • i is smaller than 15
{
int i = 10; • i is smaller than 12
if (i == 10)
{
too
// First if statement
if (i < 15)
printf("i is smaller than 15\n");

// Nested - if statement
// Will only be executed if statement above is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
return 0;
}

©LPU CSE101 C Programming


What will be the output of following code?
#include <stdio.h> A. true
int main() B. false
{
C. Depends on the
int x = 0;
compiler
if (x == 1)
D. Nothing will be printed
if (x >= 0)
printf("true\n");
else
printf("false\n");
}

©LPU CSE101 C Programming


What will be the output of the
following C code?
#include <stdio.h> A.inside if
int main() B.inside else if
{
int x = 0; C.inside else
if (x == 1) D.Compile time error
if (x == 0)
printf("inside if\n");
else
printf("inside else if\n");
else
printf("inside else\n");
return 0;
}
©LPU CSE101 C Programming
CSE101-Lec#6-Part-2
• Control structures(Decision control
statements/ or Condition 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


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. Nesting of switch is allowed.
9. Variables are not allowed in switch case label..

©LPU CSE101 C Programming


Syntax error in switch statement
Variable cannot be
switch(pt){
used as label
case count:
printf(“%d”, count);
break;

case 2.5:
printf(“A line”); Floating point number
break; cannot be used
case 3 + 7.7:
printf(“A triangle”);
case 3 + 7.7: Floating point number
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
#include<stdio.h>
int main()
{
int pt;
printf("Enter the number of nodes:");
Program to
scanf("%d", &pt);
switch(pt){ show switch
case 0:
printf("\nNo Geometry");
break;
statement in
case 1:
printf("\nA point");
break;
geometry
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");
break;
}
return 0;
}

Enter the number of nodes: 2


A line
©LPU CSE101 C Programming
Q1
#include <stdio.h>
int main() A. Compile time error
{ B. 1
double ch; C. 2
printf("enter a value between 1 to 2:"); D. Nothing will be displayed
scanf("%lf", &ch);
switch (ch)
{
case 1:
printf("1");
break;
case 2:
printf("2");
break;
}
return 0;
}

©LPU CSE101 C Programming


Q2
What will be the output of the following C
code? (Assuming that we have entered the A. 1
value 1 in the standard input)
#include <stdio.h> B. 2
int main()
{
C. 1 2
int ch; D. Compile time error
printf("enter a value between 1 to 2:");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("1 ");
default:
printf("2");
}
return 0;
}

©LPU CSE101 C Programming


Q3
What will be the output of the following C A. 1 hi
code? (Assuming that we have entered the
value 1 in the standard input) B. 2
#include <stdio.h> C. hi
int main() D. 1
{
int ch;
printf("enter a value between 1 to 2:");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("1 ");
printf("hi");
break;
default:
printf("2\n");
}
}

©LPU CSE101 C Programming


Q4
What will be the output of the A. yes
following C code?
B. yes no
#include <stdio.h>
int main() C. Duplicate case value error
{ D. Nothing will be displayed
int x = 97;
switch (x)
{
case 'a':
printf("yes ");
break;
case 97:
printf("no");
break;
}
}
©LPU CSE101 C Programming
Q5
What will be the output of the A. Output: Case A
following C code?
#include <stdio.h> B. Output: Default
int main() C. Output: Case A Default
{
int a = 1;
D. Compile time error
switch (a)
{
case a:
printf("Case A ");
default:
printf("Default");
}
return 0;
}

©LPU CSE101 C Programming


CSE101-Lec#6-Part-2
• Control Structures[Repetition structures/ or
Looping statements/ or Iterative statements]

©LPU CSE101 C Programming


Outline
• Repetition structure/Control Loop Statements
– for statement
– while statement
– do-while statement

©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

• Body – a statement or a
block of statements that
will be repeated.

• 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;
updating control;
}

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.
• while loop is known as entry controlled loop, as
condition is checked at the beginning/ or entry
point
©LPU CSE101 C Programming
while statement
Example: This while statement prints numbers 10 down to 1
#include<stdio.h>
int main()
{
int n=10;
while (n>0){
printf(“%d ”, n);
n=n-1;
}
return 0;
}
10 9 8 7 6 5 4 3 2 1

Do TEN push ups imposes a


count condition
©LPU CSE101 C Programming
Q1
How many times i value is checked in the following C code?
#include <stdio.h>
int main()
{
int i = 0;
while (i < 3)
i++;
printf("In while loop\n");
}
A. 2
B. 3
C. 4
D. 1

©LPU CSE101 C Programming


Q2
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i = 0;
while (++i)
{
printf("H");
}
return 0;
}
A. H
B. H is printed infinite times
C. Compile time error
D. Nothing will be printed

©LPU CSE101 C Programming


Q3
What will be the output of the following C code?

#include <stdio.h>
int main()
{
int i = 0;
while (i = 0)
printf("True\n");
printf("False\n");
return 0;
}
A. True (infinite time)
B. True (1 time) False
C. False
D. Compiler dependent

©LPU CSE101 C Programming


Q4
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i = 0, j = 0;
while (i < 5, j < 10)
{
i++;
j++;
}
printf("%d, %d\n", i, j);
return 0;
}
A. 5, 5
B. 5, 10
C. 10, 10
D. Compiler error

©LPU CSE101 C Programming


Q5
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i=0;
while(++i<=5);
printf("%d ",i);
return 0;
}

A. 1 2 3 4 5
B. 6
C. 5
D. Compiler error

©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.
• It is also known as entry controlled loop as condition is
checked first and then loop body executes

©LPU CSE101 C Programming


for statement

for (Initialization; Condition; Updating )


{
Repeated_Actions;
}

©LPU CSE101 C Programming


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

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
Q1
#include <stdio.h>
int main()
{
int i;
for (i = 1; i != 10; i += 2)
printf("Hello");
return 0;
}
A. Hello will be displayed 5 times
B. Hello will be displayed 4 times
C. Hello will be displayed infinite no. of times
D. Hello will be displayed 6 times

©LPU CSE101 C Programming


Q2
What will be the output of following code
#include<stdio.h>
int main()
{
int i;
for(i=1;i<10;i++);
printf("%d",i);
return 0;
}
A. Numbers from 1 to 9 will be printed
B. 10
C. 9
D. Infinite loop

©LPU CSE101 C Programming


Q3
What will be the output of following code?
#include<stdio.h>
int main()
{
int i;
for(i=2;i<=10;)
{
printf("%d ",++i);
}
return 0;
}
A. 2 3 4 5 6 7 8 9 10
B. 3 4 5 6 7 8 9 10 11
C. infinite loop
D. Compile time error

©LPU CSE101 C Programming


Q4
What will be the output of following code?
#include<stdio.h>
int main()
{
int i=1;
for(;0;)
{
printf("%d",i);
i++;
}
return 0;
}

A. 1
B. 0
C. infinite loop
D. Nothing will be displayed

©LPU CSE101 C Programming


Q5
What will be the output of following code?
#include<stdio.h>
int main()
{
int i,j;
for(i=1,j=1;j<=5;j++)
{
}
printf("\n%d %d",i,j);
return 0;
}

A. 1 6
B. 1 1
C. 6 1
D. 1 5

©LPU CSE101 C Programming


for vs while loop

©LPU CSE101 C Programming


Nested Loops
• Nested loops consist of an outer loop with one
or more inner loops.
• Eg:
for (i=1;i<=100;i++){ Outer loop

for(j=1;j<=50;j++){ Inner loop


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

©LPU CSE101 C Programming


#include<stdio.h>
int 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
return 0;
} //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>
int main() Program to
{
int i,j;
display a
printf(“Displaying right angled triangle for 5 pattern.
rows”);
for(i=1 ; i<=5 ; i++) {
for(j=1 ; j<=i ; j++)
printf(“* ”);
printf(“\n”);
}
return 0;
}

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(even if the
condition is false)
• For second time, If the condition is true, then the
statement is repeated else the loop is exited.
• Also known as exit-controlled loop, as loop body
executes first and then the condition is checked

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

do
{
Repeated_Actions;
} while (Condition);

©LPU CSE101 C Programming


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

10 9 8 7 6 5 4 3 2 1

©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


Q1
What will be the output of the following C code?
#include <stdio.h>
int main()
{
do
printf("In while loop ");
while (0);
printf("After loop\n");
return 0;
}
A. In while loop
B. In while loop
After loop
C. After loop
D. Infinite loop

©LPU CSE101 C Programming


Q2
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i = 0;
do {
i++;
printf("In while loop\n");
} while (i < 3);
return 0;
}
A. In while loop
In while loop
In while loop

B. In while loop
In while loop

C. Nothing will be displayed


D. Compile time error

©LPU CSE101 C Programming


Q3
How many times i value is checked in the following C code?
#include <stdio.h>
int main()
{
int i = 0;
do {
i++;
printf("in while loop\n");
} while (i < 3);
return 0;
}
A. 2
B. 3
C. 4
D. 1

©LPU CSE101 C Programming


Q4
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i = 0;
do
{
printf("Hello");
} while (i != 0);
return 0;
}
A. Nothing
B. H is printed infinite times
C. Hello
D. Run time error

©LPU CSE101 C Programming


CSE101-Lec 7
Jump statements
break , continue, goto, return
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){
if (n<8)
statement.
break;
printf(“%d ”, n);
} //end for
}

10 9 8

©LPU CSE101 C Programming


Q1
What will be the output of the following C code?
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==2||i==3)
continue;
printf("\nHello");
}
return 0;
}
A. Hello will be printed 3 times
B. Hello will be printed 5 times
C. Hello will be printed for one time
D. Nothing will be displayed

©LPU CSE101 C Programming


Q2
What will be the output of the following C code?
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=5;i++)
{
printf("\nHello");
break;
}
return 0;
}

A. Hello will be printed 4 times


B. Hello will be printed 5 times
C. Hello will be printed for one time
D. Nothing will be displayed

©LPU CSE101 C Programming


Q3
//What will be the output of following
code? A. 1 3 4
#include<stdio.h> B. 2 5
int main() C. 1 3
{ D. Nothing will be displayed
int i=0;
while(1)
{
i++;
if(i==2)
continue;
else if(i==5)
break;
printf("%d ",i);
}
return 0;
}
©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
if (n%2==1) For n=9, loop goes to infinite
execution
continue;
n = n –1;
}
return 0;
}
The loop then prints
10 9 9 9 9 9 ………… number 9 over and over
again. It never stops.
©LPU CSE101 C Programming
Q1
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i = 0;
do
{
i++;
if (i == 2)
continue;
printf("In while loop ");
} while (i < 2);
printf("%d\n", i);
return 0;
}
A. In while loop 2
B. In while loop In while loop 3
C. In while loop 3
D. Infinite loop

©LPU CSE101 C Programming


Q2
#include<stdio.h>
int main()
{
int i=1;
while(i<=5)
{
i++;
continue;
printf("\nC");
}
return 0;
}
A. C will be printed 5 times
B. C will be printed 0 times
C. C will be printed 1 time
D. None of these

©LPU CSE101 C Programming


Q3
What will be the output of following code?
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=5;i++)
{
printf("%d ",i);
continue;
}
return 0;
}
A. 1 2 3 4 5
B. 1
C. 1 2
D. Nothing will be displayed

©LPU CSE101 C Programming


Q4
//What will be the output of following A. 1 2
code?
#include<stdio.h> B. 1 2 3 4 5
int main() C. 1 2 4
{ D. Nothing will be displayed
int i=0;
for(;;)
{
i++;
if(i%3==0)
continue;
else if(i%5==0)
break;
printf("%d ",i);

}
return 0;
}

©LPU CSE101 C Programming


break vs continue
BASIS FOR
BREAK CONTINUE
COMPARISON
Task It terminates the execution It terminates only the
of remaining iteration of the current iteration of the
loop. loop(or it is used to skip the
current iteration and the
statements following the
continue statement)
Control after 'break' resumes the control 'continue' resumes the
break/continue of the program to the end control of the program to
of loop enclosing that the next iteration of that
'break'. loop enclosing 'continue'.

Causes It causes early termination It causes early execution of


of loop. the next iteration.

Continuation 'break' stops the 'continue' do not stops the


continuation of loop. continuation of loop, it only
stops the current iteration.

Other uses 'break' can be used with 'continue' can not be


'switch', 'label'. executed with 'switch' and
©LPU CSE101 C Programming 'labels'.
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:
printf(“%d “, n);
n = n -1;

if (n>0)
goto A;

Output:

10 9 8 7 6 5 4 3 2 1

©LPU CSE101 C Programming


#include<stdio.h>
int 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);
return 0;
}

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


Question 1
The continue statement cannot be used with
A. for
B. while
C. do while
D. switch

©LPU CSE101 C Programming


Answer 1
The continue statement cannot be used with
A. for
B. while
C. do while
D. switch

©LPU CSE101 C Programming


Question 2
Which keyword can be used for coming out of
recursion?
A. return
B. break
C. exit
D. both A and B

©LPU CSE101 C Programming


Answer 2
Which keyword can be used for coming out of
recursion?
A. return
B. break
C. exit
D. both A and B

©LPU CSE101 C Programming


Question 3
Switch statement accepts.

A. int
B. char
C. long
D. All of the above

©LPU CSE101 C Programming


Answer 3
Switch statement accepts.

A. int
B. char
C. long
D. All of the above

©LPU CSE101 C Programming


Question 4
Which loop is guaranteed to execute at least
one time.
A. for
B. while
C. do while
D. None of the above

©LPU CSE101 C Programming


Answer 4
Which loop is guaranteed to execute at least
one time.
A. for
B. while
C. do while
D. None of the above

©LPU CSE101 C Programming


Question 5
A labeled statement consist of an identifier
followed by
A. ;
B. :
C. ,
D. =

©LPU CSE101 C Programming


Question 5
A labeled statement consist of an identifier
followed by
A. ;
B. :
C. ,
D. =

©LPU CSE101 C Programming


©LPU CSE101 C Programming
Type Conversion
• C evaluates arithmetic expressions only in
which the data types of the operands are
identical.
• To ensure that operands are of same type the
compiler performs type conversion.
• Converting between types can be :
– Implicitly (automatically)
– Explicitly (forced)

©LPU CSE101 C Programming


Implicit Conversion
• If two operands are of different data types the compiler
performs an operation called implicit conversion on
selected operands.
• Example: in an expression containing the data types int and
float, int operand is converted to float.
float average, total;
int counter;
average = total/counter;
• The copy of counter is made and converted to float, the
calculation is performed and the result of floating-point
division is assigned to average.

©LPU CSE101 C Programming


Explicit Conversion
• Type is converted using unary type cast operator.
• Which temporary converts the operands.
• Example: in an expression containing the data types int and
float, int operand is converted to float.
float average, total;
int counter;
average = total/(float)counter;
• The temporary floating-point copy of counter is created. The
value stored in counter is still integer.
• calculation is performed and the result of floating-point
division is assigned to average.

©LPU CSE101 C Programming


• Cast operator is unary operator i.e. it takes
only one operand.
• It is formed by placing parentheses around the
type name with operand.
Syntax

(type) operand;

©LPU CSE101 C Programming


Implicit type conversion(or automatic type conversion)

• Done by the compiler on its own, without any external


trigger from the user.
• Generally takes place when in an expression more than one
data type is present. In such condition type conversion (type
promotion) takes place to avoid lose of data.
• All the data types of the variables are upgraded to the data
type of the variable with largest data type.
• char -> short int -> int -> unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
• It is possible for implicit conversions to lose information,
signs can be lost (when signed is implicitly converted to
unsigned), and overflow can occur (when long long is
implicitly converted to float).

©LPU CSE101 C Programming


Type Modifiers

long double

double

float

unsigned long int

long int

signed int

int

char

©LPU CSE101 C Programming


©LPU CSE101 C Programming
#include<stdio.h>
int main()
{ int x = 10;
char y = 'a';
x = x + y;
float z = x + 1.0;
printf("x = %d, z = %f", x, z); return 0;
}

A. x = 107, z = 108.00
B. x = 107, z = 108.0000
C. x = 107, z = 108.000000
D. x = 108, z = 108.000000

©LPU CSE101 C Programming


#include<stdio.h>
int main()
{
double x = 1.2;
int sum = (int)x + 1;
printf("sum = %d", sum);
return 0;
}

A. sum = 2
B. sum = 1
C. sum = 0
D. sum = 3

©LPU CSE101 C Programming


• What will be the data type of the result of the following operation?

(float)a * (int)b / (long)c * (double)d

a) int
b) long
c) float
d) double

©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


Output?
int main()
{
int a=6543;
printf("*%5d,*%-5d*",a,a);
return 0;
}

A) *56543,*56543*
B) * 6543,*6543 *
C) *6543 ,* 6543*
D) *6543,*6543*

©LPU CSE101 C Programming


Output?
int main()
{
int a=123;
printf("*%06d*",a);
return 0;
}
A) *123*
B) *6123*
C) *000123*
D) *006123*

©LPU CSE101 C Programming


Output?
int main()
{
float a=654.123456f;
printf("%3.3f,%3.2f",a,a);
return 0;
}

A) 654,654
B) 654.123456,654.123456
C) 654.123,654.12
D) 654.000,654.00

©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


Output?
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


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


CSE101-lec 11
Introduction to Functions
©LPU CSE101 C Programming
Divide and Conquer
• Best way to solve a problem is by dividing the
problem and solving it.
• Divide and conquer
– Construct a program from smaller pieces or
components
• These smaller pieces are called modules
– Each module more manageable than the original
program

©LPU CSE101 C Programming


Program Modules in C
• Functions
– Modules in C are called functions.
– Programs combine user-defined functions with library
functions
• C standard library has a wide variety of functions for
performing common mathematical calculations, string
manipulations, character manipulations, input/output and
many more.
• C standard library makes your job easier.
• Functions like printf(), scanf(), pow() are standard library
functions.
• We can also write functions to define some specific task in a
program and these functions are called user-defined
functions.

©LPU CSE101 C Programming


Functions
• Functions
– Modularize a program
– All variables defined inside functions are local
variables
• Known only in function defined.
– Parameters
• Functions have list of parameters.
• Communicate information between functions.
• Are also Local variables to that function.

©LPU CSE101 C Programming


Benefits of functions
– Divide and conquer
• Manageable program development
– Software reusability
• Use existing functions as building blocks for new
programs
• Abstraction - hide internal details (library functions)
– Avoid code repetition

©LPU CSE101 C Programming


Function Call
• Function calls
– Invoking functions
• Provide function name and arguments (data)
• Function performs operations or manipulations
• Function returns results
– Function call analogy:
• Boss asks worker to complete task
– Worker gets information, does task, returns result
– Information hiding: boss does not know details

©LPU CSE101 C Programming


Program Modules in C
Hierarchical boss function/worker function relationship.

©LPU CSE101 C Programming


Function Definitions
• Function definition format
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Function-name: any valid identifier
– Return-value-type: data type of the result (default int)
• void – indicates that the function returns nothing
– Parameter-list: comma separated list, declares
parameters
• A type must be listed explicitly for each parameter unless,
the parameter is of type int

©LPU CSE101 C Programming


Function Definitions
• Function definition format (continued)
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Definitions and statements: function body (block)
• Variables can be defined inside blocks (can be nested)
• Functions can not be defined inside other functions
– Returning control
• If nothing returned
– return;
– or, until reaches right brace at the end of function.
• If something returned
– return expression;

©LPU CSE101 C Programming


1 4 9 16 25 36 49 64 81 100

©LPU CSE101 C Programming


Function Prototypes
• Function prototype
– Function name
– Parameters – what the function takes in
– Return type – data type function returns (default int)
– Used to validate functions
– Prototype only needed if function definition comes after use in
program
– The function with the prototype
int square( int y);
• Takes in 1 int data.
• Returns an int
• Promotion rules and conversions
– Converting to lower types can lead to errors

©LPU CSE101 C Programming


Function Prototypes
• The argument values that do not correspond to the parameter types in the
function prototype are converted to the proper type before function is called.
• This is done according to promotion hierarchy of data types in type conversion.
• The types lower in the table is converted to types higher in the table.

©LPU CSE101 C Programming


1. Default return type of function is:
A. void
B. int
C. char
D. float
1. Output of following code
#include <stdio.h>
int main()
{
int i=7;
printf(“%d%d%d%d",i++,i,++i,i+1);}
A. 8 9 9 8
B. 9 9 9 8
C. 8 9 10 11
D. 7 8 9 10
#include <stdio.h>
int main()
{
void show()
{
printf("hello");
}
show();
}

A. hello
B. No output
C. compiler error
#include <stdio.h>
void show();
int main()
{
show();
printf("hello");
}
void show()
{
printf(" World");
}
1. Hello World
2. World Hello
3. WorldHello
4. HelloWorld
#include <stdio.h>
void show();
int main()
{
show();
printf("hello");
}
void show()
{
printf("World");
main();
}
1. HelloWorld
2. WorldHello
3. World will be printed infinite times
4. Worldhello will be printed infinite time
CSE101-Lec#11
Function Call

Created By:
Amanpreet Kaur &
Sanjeev Kumar
©LPU CSE101 C Programming SME (CSE) LPU
Outline
• Function call
– Passing arguments by value
– Passing arguments by reference

©LPU CSE101 C Programming


Formal Arguments and
Actual Arguments
• Argument: An argument is an expression which is
passed to a function by its caller in order for the
function to perform its task.
• Actual arguments: The arguments that are passed
in a function call are called actual arguments. These
arguments are defined in the calling function.
• Formal arguments: The formal arguments are the
parameters/arguments in a function declaration.
Formal arguments are a copy of the actual
arguments.

©LPU CSE101 C Programming


#include <stdio.h>
void sum(int i, int j, int k); /*function prototype*/
int main()
{
int a = 5;
sum(3, 2 * a, a); // actual arguments
return 0;
}
void sum(int i, int j, int k)//formal arguments
{
int s;
s = i + j + k;
printf("sum is %d", s);
}

©LPU CSE101 C Programming


Methods of passing arguments
• There are two ways to call a function/to pass
arguments to a function:
1. Call by value
2. Call by reference

©LPU CSE101 C Programming


Call by Value
• Call by value
– In this method the values of actual arguments are
copied to the formal arguments of the function.
– Changes in function do not effect original
– Use when function does not need to modify
argument
• Avoids accidental changes
– The method of passing arguments by value is know
as call by value

©LPU CSE101 C Programming


#include <stdio.h>
int cubeByValue(int n); // prototype
int main( void )
{
int number = 5; // initialize number
printf("The original value of number is %d", number);
cubeByValue(number); // pass number by value
printf( "\nThe new value of number is %d\n", number );
} // end main

int cubeByValue( int n )


{
return n*n*n; //cube local variable n and return value
}

The original value of number is 5


The new value of number is 5

©LPU CSE101 C Programming


Call by reference
• The address of actual argument are copied to
the formal arguments.
• The called function uses the address to refer to
the actual location.
• Changes made by the function are effective
when the control returns to the calling
function.
– If we want to make changes even in the actual
arguments, then we use call by address

©LPU CSE101 C Programming


Address of variable
int i=3;

If we want to print the address of variable:


#include< stdio.h>
void main()
{
int i=3;
printf(“address of i=%d”, &i);
printf(“value of i =%d”, i);
}

©LPU CSE101 C Programming


Pointers
• A variable which stores address of another
variable
• Example:
int *p;
int i;
p= &i;
➢*p gives value at address stored in p.
➢ int *p means p is containing an address of
variable on which an integer is stored
©LPU CSE101 C Programming
Calling Functions by Reference
• Call by reference with pointer arguments
– Pass address of argument using & operator
– Allows you to change actual location in memory
• * operator
– Used as alias/nickname for variable inside of function
void double( int *number )
{
*number = 2 * ( *number );
}

– *number used as nickname for the variable passed

©LPU CSE101 C Programming


#include <stdio.h>
void cubeByReference(int *nPtr); //function prototype
int main( void )
{
int number = 5;
printf("The original value of number is %d", number);
cubeByReference( &number ); //pass address of number
printf("\nThe new value of number is %d\n", number);
} // end main

//calculate cube of *nPtr; actually modifies number in main


void cubeByReference( int *nPtr )
{
*nPtr = *nPtr * *nPtr * *nPtr; //cube *nPtr
}z

The original value of number is 5


The new value of number is 125

©LPU CSE101 C Programming


#include <stdio.h>
void fn1(int a){
printf("%d",a);
return a*a;
}
int main()
{
int a=5;
fn1(a);
printf("%d",a);
}
1. 5 25
2. 25 25
3. 25 5
4. 5 5

©LPU CSE101 C Programming


#include <stdio.h>
int show();

void main()
{
int a;
a=show();
printf("%d", a);
}

int show()
{
return 15.5;
return 35;
}
1. 15.5
2. 15
3. 35
4. error

©LPU CSE101 C Programming


#include <stdio.h> 1. -5
void f1 (int a, int b) 2. 5
{ 3.-3
int c; 4. Compilation error
c=a; a=b; b=c;
}
void f2 (int *a, int *b)
{
int c;
c=*a; *a=*b;*b=c;
}
int main()
{
int a=4, b=5, c=6;
f1(a, b);
f2(&b, &c);
printf ("%d", c-a-b);
return 0;
}

©LPU CSE101 C Programming


#include <stdio.h>
void show(int x,int y)
{
x=x+1;
y=y+1;
printf(“%d,%d ",x,y);
}
int main()
{
int a=6,b=9;
show(a,b);
a=a+1;
b=b+1;
printf(“%d,%d ",a,b);
}
A. 7,10 8,11
B. 7,10 7,10
C.8,11 7,10
D. Compiler error

©LPU CSE101 C Programming


#include <stdio.h>
void show(int *x,int *y)
{
*x=*x+1;
*y=*y+1;
printf(“%d,%d ",*x,*y);
}
int main()
{
int a=6,b=9;
show(&a,&b);
a=a+1;
b=b+1;
printf(“%d,%d ",a,b);
}
A. 7,10 8,11
B. 7,10 7,10
C.8,11 7,10
D. Compiler error

©LPU CSE101 C Programming


©LPU CSE101 C Programming
Header Files
• Header files
– Contain function prototypes for library functions
– <stdlib.h> , <math.h> , etc
– Load with #include <filename>
#include <math.h>
• Custom header files
– Create file with functions
– Save as filename.h
– Load in other files with #include "filename.h"
– Reuse functions
• Example #include<square.h>

©LPU CSE101 C Programming


Header Files

©LPU CSE101 C Programming


Next Class: Recursive Functions and
Scope Rules

©LPU CSE101 C Programming


cse101@lpu.co.in
CSE101-Lec#13
• Math Library functions

©LPU CSE101 C Programming


Functions in Mathematics
“A relationship between two variables, typically x and y, is
called a function, if there is a rule that assigns to each
value of x one and only one value of y.”
So, for example, if we have a function
f(x) = x + 1
then we know that
f(-2.5) = -2.5 + 1 = -1.5
f(-2) = -2 + 1 = -1
f(-1) = -1 + 1 = 0
f(0) = 0 + 1 = +1
f(+1) = +1 + 1 = +2
f(+2) = +2 + 1 = +3
f(+2.5) = +2.5 + 1 = +3.5

©LPU CSE101 C Programming


Functions in Mathematics
Likewise, if we have a function
a(y) = | y |
then we know that …
a(-2.5) = | -2.5 | = +2.5
a(-2) = | -2 | = +2
a(-1) = | -1 | = +1
a(0) = | 0 | = 0
a(+1) = | +1 | = +1
a(+2) = | +2 | = +2
a(+2.5) = | +2.5 | = +2.5

©LPU CSE101 C Programming


Function Argument
f(x) = x + 1
a(y) = | y |
We refer to the thing inside the parentheses
immediately after the name of the function as
the argument (also known as the parameter)
of the function.
In the examples above:
• the argument of the function named f is x;
• the argument of the function named a is y.

©LPU CSE101 C Programming


Absolute Value Function in C
• The abs function calculates the absolute
value of its argument. It’s the C analogue of
the mathematical function
a(y) = | y |
(the absolute value function)
a= abs(y);

©LPU CSE101 C Programming


Absolute Value Function in C

fabs(-2.5) returns 2.5


abs(-2) returns 2
abs(-1) returns 1
abs(0) returns 0
abs(1) returns 1
abs(2) returns 2
fabs(2.5) returns 2.5

©LPU CSE101 C Programming


Absolute Value Function in C #3
We say “abs of -2 evaluates to 2” or “abs of -2
returns 2.”

Note that the function named abs calculates the


absolute value of an int argument, and fabs
calculates the absolute value of a float argument.

©LPU CSE101 C Programming


Function Call in Programming
In programming, the use of a function in an
expression is referred to as a call.
We say that the statement
printf("%d\n", abs(-2));
invokes or calls the function abs;
the statement passes an argument of -2 to
the function; the function abs returns a
value of 2.

©LPU CSE101 C Programming


Math Function vs Programming
Function
An important distinction between a function in
mathematics and a function in programming:
a function in mathematics is simply a
definition (“this name means that
expression”), while a function in
programming is an action (“this name means
execute that sequence of statements”).

©LPU CSE101 C Programming


C Standard Library
• Every implementation of C comes with a
standard library of predefined functions.
• Note that, in programming, a library is a
collection of functions.
• The functions that are common to all
versions of C are known as the C
Standard Library.

©LPU CSE101 C Programming


Math Library Functions
• Math library functions
– perform common mathematical calculations
– #include <math.h>
• Format for calling maths functions
– functionName( argument );
• If multiple arguments, use comma-separated list
• Example:
printf( "%.2f", sqrt( 900.0 ) );
• Calls function sqrt, which returns the square root of its argument
• All math functions return data type double
– Arguments may be constants, variables, or expressions

©LPU CSE101 C Programming


Math Library Functions
Function Description Example
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0

exp( x ) exponential function ex exp( 1.0 ) is 2.718282


exp( 2.0 ) is 7.389056
log( x ) natural logarithm of x log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
(base e)
log10( x ) logarithm of x (base 10) log10( 1.0 ) is 0.0
log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
fabs( x ) absolute value of x fabs( 5.0 ) is 5.0
fabs( 0.0 ) is 0.0
fabs( -5.0 ) is 5.0
ceil( x ) rounds x to the smallest ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
integer not less than x
floor( x ) rounds x to the largest floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
integer not greater than x
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128.0
pow( 9, .5 ) is 3.0
fmod( x, y ) remainder of x/y as a fmod( 13.657, 2.333 ) is
1.992
floating point number
sin( x ) trigonometric sine of x sin( 0.0 ) is 0.0
(x in radians)
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0.0
(x in radians)
©LPU CSE101 C Programming
Math Library Functions: pow()
• The power function, pow(x,y), calculates xy; that is, the
value of
pow(x,y) = xy.
• pow(2,3)= 2³ = 8.0 and pow(2.5,3) = 15.625.
• The function pow is of the type double or that the function
pow returns a value of the type double.
• x and y are called the parameters (or arguments) of the
function pow.
• Function pow has two parameters.

©LPU CSE101 C Programming


sqrt()
• The square root function, sqrt(x),
calculates the non-negative square root of x for x >= 0.0
sqrt(2.25) is 1.5
sqrt(25) is 5.0
• The function sqrt is of the type double and has only one
parameter.

©LPU CSE101 C Programming


fabs()
• fabs calculates the absolute value of a float
argument.
fabs(2.25) is 2.25
fabs(-25.0) is 25.0
•The function fabs is of the type double
and has only one parameter.

©LPU CSE101 C Programming


floor()
• The floor function, floor, calculates the largest
whole number that is not greater than x.
floor(48.79) is 48.0
floor(48.03) is 48.0
floor(47.79) is 47.0
• The function floor is of the type double and has
only one parameter.

©LPU CSE101 C Programming


ceil()
• The ceil function, ceil, calculates the smallest
whole number that is not less than x.
ceil(48.79) is 49
ceil(48.03) is 49
ceil(47.79) is 48
• The function ceil is of the type double and has
only one parameter.

©LPU CSE101 C Programming


©LPU CSE101 C Programming
Programming: Argument Type
• Programming has concepts that are analogous to the
mathematical domain and range: argument type and
return type.
• For a given function in C, the argument type – which
corresponds to the domain in mathematics – is the
data type that C expects for an argument of that
function.
• For example:
• the argument type of abs is int;
• the argument type of fabs is float.

©LPU CSE101 C Programming


Argument Type Mismatch
• An argument type mismatch is when you pass an
argument of a particular data type to a function that
expects a different data type.
• Some implementations of C WON’T check for you
whether the data type of the argument you pass is
correct. If you pass the wrong data type, you can get a
bogus answer.
• This problem is more likely to come up when you pass a
float where the function expects an int. In the
reverse case, typically C simply promotes the int to a
float.

©LPU CSE101 C Programming


#include <stdio.h>
#include <math.h>

int main ()
{ /* main */
const float pi = 3.1415926;
printf("2.0 = %f\n", 2.0);
printf("pi = %f\n", pi);
printf("cos(pi) = %f\n", cos(pi));
printf("sin(pi) = %f\n", sin(pi));
printf("sqrt(2.0) = %f\n", sqrt(2.0));
printf("sqrt(2.0) / 2 = %f\n", sqrt(2.0) / 2);
} /* main */

©LPU CSE101 C Programming


Function Use Example
2.0 = 2.000000
pi = 3.141593
cos(pi) = -1.000000
sin(pi) = 0.000000
sqrt(2.0) = 1.414214
sqrt(2.0) / 2 = 0.707107

©LPU CSE101 C Programming


Q1
Which of the following header declares
mathematical functions and macros?
a) math.h
b) assert.h
c) stdmat. h
d) stdio. h

©LPU CSE101 C Programming


Q1
Which of the following header declares
mathematical functions and macros?
a) math.h
b) assert.h
c) stdmat. h
d) stdio. h

©LPU CSE101 C Programming


Q2
What is the value of x
x=floor(-2.3)
a) 2
b) -2
c) 3
d) -3

©LPU CSE101 C Programming


Q2
What is the value of x
x=floor(-2.3)
a) 2
b) -2
c) 3
d) -3

©LPU CSE101 C Programming


Q3
Which of the given function is a library function
under the header math.h?
a) log10()
b) log20()
c) log30()
d) log50()

©LPU CSE101 C Programming


Q3
Which of the given function is a library function
under the header math.h?
a) log10()
b) log20()
c) log30()
d) log50()

©LPU CSE101 C Programming


Q4
Which is used to calculates xy
a) pow()
b) exp()
c) power()
d) log10()

©LPU CSE101 C Programming


Q4
Which is used to calculates xy
a) pow()
b) exp()
c) power()
d) log10()

©LPU CSE101 C Programming


Next Class: Function Call

©LPU CSE101 C Programming


cse101@lpu.co.in
• Recursive function

©LPU CSE101 C Programming


Outline
• Recursion
• Examples of recursion
– Finding factorial of a number
– Finding Fibonacci series up to nth term
• Recursion Vs Iteration

©LPU CSE101 C Programming


Recursion
• Recursive functions
– Functions that call themselves
– Can only solve a base case
– Divide a problem up into
• What it can do
• What it cannot do
– What it cannot do resembles original
problem
– The function launches a new copy of itself
(recursion step) to solve what it cannot do
– Eventually base case gets solved
• Gets plugged in, works its way up and
solves whole problem

©LPU CSE101 C Programming


Recursion example (factorial)
• Factorial of a number in mathematics
– 5! = 5 * 4 * 3 * 2 * 1
• Another method we have studied is

Values returned
– For 5!, we write 5! = 5 * 4! 120
– Then for 4!, 4! = 4 * 3!
24
– Then for 3!, 3! = 3 * 2!
– Then for 2!, 2! = 2 * 1! 6
2
– Then for 1!, 1! = 1 * 0!
1
– And if its comes to 0,
– 0!=1
– Solve base case (1! = 0! = 1)

©LPU CSE101 C Programming


Recursion example (factorial)
Fin a l va lue = 120
5! 5!
5! = 5 * 24 = 120 is re turn ed
5 * 4! 5 * 4!
4! = 4 * 6 = 24 is re turne d
4 * 3! 4 * 3!
3! = 3 * 2 = 6 is re tu rn e d
3 * 2! 3 * 2!
2! = 2 * 1 = 2 is re turne d
2 * 1! 2 * 1!
1 re turne d
1 1

( a ) Se q u en c e o f re c ursive c a lls. ( b ) Va lue s re turne d fro m e a c h re cu rsive c a ll.

©LPU CSE101 C Programming


Recursion example (factorial code)
This function
calculates
factorial of
numbers

©LPU CSE101 C Programming


Recursion example (fibonacci)
• What is Fibonacci series: …??
• 0, 1, 1, 2, 3, 5, 8...
– Each number is the sum of the previous two
– Can be solved recursively:
• fib( n ) = fib( n - 1 ) + fib( n – 2 )
– Code for the fibonacci function
long fibonacci( long n )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci( n - 1)+fibonacci( n – 2 );
}

©LPU CSE101 C Programming


Recursion example (fibonacci)
• Set of recursive calls to fibonacci() function

f( 3 )

return f( 2 ) + f( 1 )

return f( 1 ) + f( 0 ) return 1

return 1 return 0

©LPU CSE101 C Programming


Recursion example (fibonacci code)
This function
calculates
fibonacci
number of
any given
position

©LPU CSE101 C Programming


Recursion example (fibonacci code)
This function
print first n
term of series

©LPU CSE101 C Programming


Recursion vs. Iteration
• Repetition
– Iteration: explicit loop(for,while)
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case reached
• Both can have infinite loops
• Balance
– Choice between performance (iteration) and good
software engineering (recursion)

©LPU CSE101 C Programming


Rules for recursive function
1. In recursion, it is essential to call a function itself
2. Only the user defined function can be involved in the
recursion. Library function cannot be involved in
recursion because their source code cannot be
viewed
3. A recursive function can be invoked by itself or by
other function.
4. To stop recursive function, it is necessary to base
recursion on some condition, and proper termination
statement such as exit() or return
5. The user defined function main() can be invoked
recursively.

©LPU CSE101 C Programming


Q1
What will be the output of the following C code?

#include<stdio.h>
int f(int n); a) 10
int main()
{
b) 80
int n=10; c) 30
printf("%d",f(n)); d) Error
}
int f(int n)
{
if(n>0)
return(n+f(n-2));
}

©LPU CSE101 C Programming


Q1
What will be the output of the following C code?

#include<stdio.h>
int f(int n); a) 10
int main()
{
b) 80
int n=10; c) 30
printf("%d",f(n)); d) Error
}
int f(int n)
{
if(n>0)
return(n+f(n-2));
}

©LPU CSE101 C Programming


Q2
What will be the output of the following C code?

#include<stdio.h>
int main()
{
printf("Hello");
main();
return 0;
}
a) Hello is printed once
b) Hello infinite number of times
c) Hello is not printed at all
d) 0 is returned

©LPU CSE101 C Programming


Q2
What will be the output of the following C code?

#include<stdio.h>
int main()
{
printf("Hello");
main();
return 0;
}
a) Hello is printed once
b) Hello infinite number of times
c) Hello is not printed at all
d) 0 is returned

©LPU CSE101 C Programming


Q3
A recursive function is
a) Math function
b) Call itself
c) Library function
d) Call main function

©LPU CSE101 C Programming


Q3
A recursive function is
a) Math function
b) Call itself
c) Library function
d) Call main function

©LPU CSE101 C Programming


Q4
Function
0 if n==0
f(n) = {n+ f(n-1) if n>0
will print
a) Sum of n numbers
b) Factorial of number
c) Value of n
d) Nothing

©LPU CSE101 C Programming


Q4
Function
0 if n==0
f(n) = {n+ f(n-1) if n>0
will print
a) Sum of n numbers
b) Factorial of number
c) Value of n
d) Nothing

©LPU CSE101 C Programming


• Next Lecture

Life and existence of a


variable …??
storage classes

©LPU CSE101 C Programming


cse101@lpu.co.in
//sum and average of array elements
main()
{
    int i,n,sum=0;
    float avg;
    printf("Enter no of elements\n");
    scanf("%d",&n);
    int a[n];
    printf("Enter array elements\n");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("Entered Array is-->\n");
    for(i=0;i<n;i++)
        printf("%d\n",a[i]);
    for(i=0;i<n;i++)
        sum=sum+a[i];
    printf("\nsum= %d\n",sum);

    avg=sum/n;
    printf("\nAverage=%f\n",avg);
}
-------------------------------
//Smallest element in an array
main()
{
    int i,n,min;
    printf("Enter no of elements\n");
    scanf("%d",&n);
    int a[n];
    printf("Enter array elements\n");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("Entered Array is-->\n");
    for(i=0;i<n;i++)
        printf("%d\n",a[i]);
    min=a[0];
    for(i=1;i<n;i++)
    {
        if(min>a[i])
            min=a[i];
    }
    printf("\nSmallest element = %d\n",min);

}
------------------------------
//Largest element in an array
main()
{
    int i,n,max;
    printf("Enter no of elements\n");
    scanf("%d",&n);
    int a[n];
    printf("Enter array elements\n");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("Entered Array is-->\n");
    for(i=0;i<n;i++)
        printf("%d\n",a[i]);
    max=a[0];
    for(i=1;i<n;i++)
    {
        if(max<a[i])
            max=a[i];
    }
    printf("\nLargest element = %d\n",max);

}
CSE101-Lec#15,16, 17
• What are Arrays?
• To declare an array
• To initialize an array
• To display address of the array
• Basic program examples of 1D array
• To pass an array to a function(By reference
and By value)
• Applications and Operations on 1D Array

©LPU CSE101 C Programming


Outline
• To declare an array
• To initialize an array
• To display address of the array
• Basic program examples of 1D array
• To pass an array to a function(By reference
and By value)
• Applications and Operations on 1D Array

©LPU CSE101 C Programming


Introduction
• Arrays
– Collection of related data items of same data
type.
– Static entity – i.e. they remain the same size
throughout program execution

©LPU CSE101 C Programming


Types
• One Dimensional (e.g. int a[100])
• Multidimensional(2D,3D….)(e.g. int a[5][5], int a[5][5][5])

©LPU CSE101 C Programming


1-D array
• A single- dimensional or 1-D array consists of a
fixed number of elements of the same data
type organized as a single linear sequence.
• The elements of a single dimensional array
can be accessed by using a single subscript
• The arrays we have studied till now were 1D
array or linear array.
• Example: int a[n];

©LPU CSE101 C Programming


Arrays(1D) Name of array (Note
that all elements of
this array have the
• Array same name, c)

– Group of consecutive memory locations c[0] -45


– Same name and data type c[1] 6
c[2] 0
• To refer to an element, specify: c[3] 72
– Array name c[4] 3
c[5] -89
– Position number in square brackets([]) c[6] 0
• Format: c[7] 62
c[8] -3
arrayname[position_number]
c[9] 1
– First element is always at position 0 c[10] 6453
– Eg. n element array named c: c[11] 78
• c[0], c[1]...c[n – 1]
Position number of
the element within
©LPU CSE101 C Programming array c
Arrays
• An array is an ordered list of values
The entire array Each value has a numeric index
has a single name

c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9]

c 79 87 94 82 67 98 87 81 74 91

An array of size N is indexed from zero to N-1

This array holds 10 values that are indexed from 0 to 9

©LPU CSE101 C Programming


Arrays
• Array elements are like normal variables
c[0] = 3;/*stores 3 to c[0] element*/
scanf (“%d”, &c[1]);/*reads c[1] element*/
printf (“%d, %d”, c[0], c[1]); /*displays
c[0] & c[1] element*/
• The position number inside square brackets is called
subscript/index.
• Subscript must be integer or an integer expression
c[5 - 2] = 7; (i.e. c[3] = 7)

©LPU CSE101 C Programming


Defining Arrays
• When defining arrays, specify:
– Name
– Data Type of array
– Number of elements
datatype arrayName[numberOfElements];
– Examples:
int students[10];
float myArray[3284];
• Defining multiple arrays of same data type
– Format is similar to regular variables
– Example:
int b[100], x[27];

©LPU CSE101 C Programming


Initializing Arrays
Different ways of initializing ID Arrays
1) Initializing array at the point of declaration
• int a[5]={1,2,3,4,5};
• int a[]={1,2,3,4,5};//Here compiler will automatically depict the size:5
• int a[5]={1,2,3};//Partial initialization[Remaining elements will be initialized to
default values for integer, i.e. 0]
• int a[5]={};//All elements will be initialized to zero
• int a[5]={1};//First element is one and the remaining elements are default
values for integer, i.e. 0

©LPU CSE101 C Programming


Initializing Arrays
2) Initializing array after taking input from the user
• Array is same as the variable can prompt for value from the user at
run time.
• Array is a group of elements so we use for loop to get the values of
every element instead of getting single value at a time.
• Example: int array[5], i; // array of size 5
for(i=0;i<5;i++){// loop begins from 0 to 4
scanf(“%d”, &array[i]);
}

©LPU CSE101 C Programming


Printing base address of the array and address of any array
element
#include<stdio.h>
int main()
{
int a[5]={1,2,3,4,5};
int i;
printf("\n Printing base address of the array:");
printf("\n%u %u %u",&a[0],a,&a);
printf("\n Printing addresses of all array elements:");
for(i=0;i<5;i++)
{
printf("\n%u",&a[i]);
}
return 0;
}

©LPU CSE101 C Programming


Program example 1-WAP to read and display elements of 1D Array
#include<stdio.h>
int main()
{
int a[100],n,i;
printf("\n Enter number of elements:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Entered array elements are:");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
return 0;
}
©LPU CSE101 C Programming
Program example-2 WAP to find the sum of all 1D array elements
#include<stdio.h>
int main()
{
int a[100],n,i,sum=0;
printf("\n Enter number of elements:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
printf("\n Sum of array elements is:%d",sum);
return 0;

©LPU CSE101 C Programming


Program example 3-WAP to display the largest and smallest
element from 1D array elements
#include<stdio.h> max=a[0];
int main() for(i=1;i<n;i++)
{
int n,a[10],i,max,min; {
printf("\n Enter number of elements:"); if(a[i]>max)
scanf("%d",&n); {
for(i=0;i<n;i++) max=a[i];
{
scanf("%d",&a[i]); }
} }
min=a[0]; printf("\nMaximum element
for(i=1;i<n;i++) is: %d",max);
{ printf("\nMinimum element
if(a[i]<min) is: %d",min);
{
min=a[i]; return 0;
} }
}

©LPU CSE101 C Programming


Passing Arrays to Function
• Arrays can be passed to functions in two ways:
1. Pass entire array
2. Pass array element by element

©LPU CSE101 C Programming


Pass entire array
• Here entire array can be passed as an argument
to the function
• Function gets complete access to the original
array
• While passing entire array Address of first
element is passed to function, any changes made
inside function, directly affects the Original
value.
void modifyArray(int b[], int arraySize);
• Function passing method: “ Pass by Address”

©LPU CSE101 C Programming


Passing array element by element
• Here individual elements are passed to the
function as argument
• Duplicate carbon copy of Original variable is
passed to function
• So any changes made inside function does not
affects the original value
• Function doesn’t get complete access to the
original array element.
void modifyElement(int e);
• Function passing method: “ Pass by Value”

©LPU CSE101 C Programming


Passing Arrays to Functions
• Function prototype
void modifyArray(int b[], int arraySize);
– Parameter names optional in prototype
• int b[] could be written int []
• int arraySize could be simply int
void modifyArray(int [], int);
• Function call
int a[SIZE];
modifyArray(a, SIZE);

©LPU CSE101 C Programming


Program example-1 Passing Array to a function using
by reference(or Passing entire array at once)
#include<stdio.h> void reference(int x[],int size)
void reference(int[],int); {
int main() int i;
{ for(i=0;i<size;i++)
int arr[100],n; {
int i; printf("%d ",x[i]);
}
printf("\n Enter n:");
}
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\n Elements by reference:");
reference(arr,n);//Passing array by call by reference
return 0;
}

©LPU CSE101 C Programming


Program example-2 Passing Array to a function using by
value(or Passing element by element)
#include<stdio.h>
void value(int); void value(int u)
int main() {
{ printf("%d ",u);
int arr[100],n; }
int i;
printf("\n Enter n:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\n Passing elements by value:");
for(i=0;i<5;i++)
{
value(arr[i]);//Passing array value by Call by value
}
return 0;
}

©LPU CSE101 C Programming


Application Of Array :
Stores Elements of Same Data Type
• Array is used to store the number of elements that are of same data
type.
• Eg: int students[30];
• array of marks of five subjects for single student.
float marks[5];
• array of marks of five subjects for 30 students.
float marks[30][5]
• Similarly if we declare the character array then it can hold only
character.
• So in short character array can store character variables while
floating array stores only floating numbers.

©LPU CSE101 C Programming


Array Used for Maintaining multiple variable names using single
name
Suppose we need to store 5 roll numbers of students then without
declaration of array we need to declare following -
int roll1,roll2,roll3,roll4,roll5;
1. Now in order to get roll number of first student we need to access
roll1.
2. Guess if we need to store roll numbers of 100 students then what
will be the procedure.
3. Maintaining all the variables and remembering all these things is
very difficult.
➢ So we are using array which can store multiple values and we have
to remember just single variable name.

©LPU CSE101 C Programming


Array Can be Used for Sorting Elements
• We can store elements to be sorted in an array and then by
using different sorting technique we can sort the elements.
Different Sorting Techniques are :
1. Bubble Sort
2. Insertion Sort
3. Selection Sort

©LPU CSE101 C Programming


Array Can Perform Matrix Operation
Matrix operations can be performed using the array. We can use
2-D array
• To store the matrix.
• To perform all mathematical manipulations on matrix.
• Matrix can be multi-dimensional.

©LPU CSE101 C Programming


Searching in Arrays
• The process of finding a particular element of
an array is called searching.
• Search an array for a key value.
• Two searching techniques:
– Linear search
– Binary search

©LPU CSE101 C Programming


Linear search
• Linear search
– Simple
– Compare each element of array with key value
– Useful for small and unsorted arrays
• It simply examines each element sequentially,
starting with the first element, until it finds the
key element or it reaches the end of the array.
Example: If you were looking for someone on a
moving passenger train, you would use a
sequential search.

©LPU CSE101 C Programming


Program example-WAP to implement linear search in 1D array
element
#include <stdio.h> if(loc!= -1)
int main() {
{ printf("Element found at %d",loc+1);
int a[50];
}
int i, loc = -1, key,n;
printf("\n Enter value of n:"); else
scanf("%d",&n); {
printf("\n Enter the elements:"); printf("Element not found");
}
for(i=0;i<n;i++) } // end main
{ •

scanf("%d",&a[i]);
}
printf("Enter integer value to search in array:");
scanf( "%d", &key );
// attempt to locate searchKey in array a
for ( i = 0; i < n; i++ )
{
if ( a[i] == key )
{
loc = i; // location of key is stored
break;
} // end if
} // end for

©LPU CSE101 C Programming


Binary search
• Binary search
– Applicable for sorted arrays
• The algorithm locates the middle element of
the array and compares it to the key value.
– Compares middle element with the key
• If equal, match found
• If key < middle, looks in left half of middle
• If key > middle, looks in right half of middle
• Repeat (the algorithm is repeated on one-quarter of
the original array.)

©LPU CSE101 C Programming


Binary search
– It repeatedly divides the sequence in two, each
time restricting the search to the half that would
contain the element.
– This is a tremendous increase in performance over
the linear search that required comparing the
search key to an average of half of the array
elements.
– You might use the binary search to look up a word
in a dictionary

©LPU CSE101 C Programming


Program example-WAP to implement Binary Search in 1D array elements
#include<stdio.h> else if(a[mid]>key) //Middle element is greater than key
int main() {
{ last=mid-1;//If middle element is greater than key, we
need to search left subarray
int a[50],n,loc=-1, key, beg,last,mid,i; }
printf("\n Enter number of array elements:"); else if(a[mid]<key) //Middle element is less than key
scanf("%d",&n); {
printf("\n Enter array elements:"); beg=mid+1;//If middle element is less than key, we
for(i=0;i<n;i++) need to search right subarray
{ } //end of if else
scanf("%d",&a[i]); } //end of while
} if(loc!=-1)
beg=0; {
last=n-1; printf("element found at %d", loc+1);//Location is exact
position, not index
printf("Enter integer value to search in sorted array:"); }
scanf( "%d", &key ); else
while(beg<=last)//Loop will run until unless only one element is not {
remaining
{ printf("element not found");
mid = (beg + last) / 2; // determine index of middle element }
if(a[mid]==key) return 0;
{ }
loc=mid; //save the location of element.
break;
}

©LPU CSE101 C Programming


Dry running

©LPU CSE101 C Programming


Sorting
• Sorting data
– Important computing application
– Virtually every organization must sort some data

©LPU CSE101 C Programming


Bubble sort
Bubble sort (sinking sort)
• A simple but inefficient sorting technique.
– Several passes through the array
– Successive pairs of elements are compared
• If increasing order (or identical ), no change
• If decreasing order, elements exchanged
– Repeat

©LPU CSE101 C Programming


Bubble sort Comparing
successive elements

77 56 4 10 34 2 Original array

56 4 10 34 2 77 After pass 1

4 10 34 2 56 77 After pass 2

4 10 2 34 56 77 After pass 3

4 2 10 34 56 77 After pass 4
2 4 10 34 56 77 After pass 5

Total number of pass required for sorting: n-1


©LPU CSE101 C Programming
Bubble sort
• It’s called bubble sort or sinking sort because smaller
values gradually “bubble” their way to the top of the
array (i.e., toward the first element) like air bubbles
rising in water, while the larger values sink to the
bottom (end) of the array.
• The technique uses nested loops to make several
passes through the array.
– Each pass compares successive pairs of elements.
– If a pair is in increasing order (or the values are equal), the
bubble sort leaves the values as they are.
– If a pair is in decreasing order, the bubble sort swaps their
values in the array.

©LPU CSE101 C Programming


Bubble sort
• The first pass compares the first two elements of the
array and swaps their values if necessary. It then
compares the second and third elements in the array.
The end of this pass compares the last two elements
in the array and swaps them if necessary.
• After one pass, the largest element will be in the last
index. After two passes, the largest two elements will
be in the last two indices.

©LPU CSE101 C Programming


Program example-WAP to sort elements of 1D array in ascending order using Bubble
sort
#include <stdio.h> // loop to control number of passes(no. of passes are
always n-1)
int main() for (i=0;i<n-1;i++)
{ {
int a[100]; // loop to control number of comparisons per
pass(There is one comparison less)
int hold,i,j,n;
printf("\n Enter value of n:"); for (j=0;j<n-i-1;j++)
scanf("%d",&n); {
// compare adjacent elements and swap them if
printf("\n Enter elements:"); first
for(i=0;i<n;i++) // element is greater than second element
{ if (a[j]>a[j+1])
{
scanf("%d",&a[i]); hold=a[j];
} a[j]=a[j+1];
printf( "Data items in original order" ); a[j+1]=hold;
} // end if
for (i=0;i<n;i++ ) } // end inner for
{ } // end outer for
printf("%d ",a[i]);//Elements will printf( "\nData items in ascending order" );
come with space for (i=0;i<n;i++)
} // end for {
printf("%d ",a[i]);
// bubble sort } // end for
} // end main

©LPU CSE101 C Programming


Dry running

©LPU CSE101 C Programming


Operations on arrays
• Insertion of element into an array
• Deletion of element from an array

©LPU CSE101 C Programming


Write a program to insert an element at a given position in 1D array

#include <stdio.h> printf("Resultant array is:\n");


int main()
for (c = 0; c <= n; c++)
{
int array[100], position, c, n, value; {
printf("Enter number of elements in array:\n"); printf("%d\n", array[c]);
scanf("%d", &n); }
printf("Enter %d elements:\n", n);
for (c = 0; c < n; c++) return 0;
{ }
scanf("%d", &array[c]);
} •
printf("Enter the location where you wish to insert
an element:\n");
scanf("%d", &position);
printf("Enter the value to insert:\n");
scanf("%d", &value);

for (c = n - 1; c >= position - 1; c--)


{
array[c+1] = array[c];
}
array[position-1] = value;

©LPU CSE101 C Programming


Dry running

©LPU CSE101 C Programming


Write a program delete an element from a given position in 1D array
#include <stdio.h>
int main()
printf("Resultant array
{ is\n");
int array[100], position, c, n;
printf("Enter number of elements in array\n");
for (c = 0; c < n-1; c++)
scanf("%d", &n); {
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++) printf("%d\n",
{
scanf("%d", &array[c]);
array[c]);
} }
printf("Enter the location where you wish to delete
from an array\n"); }
scanf("%d", &position);
for (c = position-1; c < n-1; c++)

{
array[c] = array[c+1];
}

©LPU CSE101 C Programming


Dry running

©LPU CSE101 C Programming


Q1
If the size of the array is 100, then last index will be:
A. 100
B. 99
C. 98
D. 0

©LPU CSE101 C Programming


Q2
For the given array, int a={22,3,44,8,9}; what value will be coming for
a[3]??
A. 22
B. 44
C. 9
D. 8

©LPU CSE101 C Programming


Q3
For the given array, int a[5]={}; what value will be coming for a[1]??
A.1
B. Garbage value
C.0
D.-1

©LPU CSE101 C Programming


Q4
What will be the output of A. 0
following code?
#include<stdio.h> B. 2
int main() C. 1
{ D. Garbage value
int a[5],i;
for(i=0;i<5;i++)
{
a[i]=i;
}
printf("%d",a[2]);
return 0;
}

©LPU CSE101 C Programming


Q5
What will be the output of A. 22
following code? B. 33
#include<stdio.h> C. 44
int main() D. 55
{
int a[5]={11,22,33,44,55};
a[2]=a[1];
a[3]=a[2];
a[4]=a[3];
printf("%d",a[4]);
return 0;
}

©LPU CSE101 C Programming


Q6
#include<stdio.h>
int main()
{
int a[5]={1,2,3,4,5};
int b[5];
int i;
for(i=0;i<5;i++)
{
b[i]=++a[i];
}
printf("%d",b[0]+b[3]);
return 0;
}

A. 5
B. 7
C. 4
D. 3

©LPU CSE101 C Programming


Q7
What will be the output of the following program?
#include<stdio.h>
int main()
{
int a[5] = {5, 1, 15, 20, 25};
int i=2;
printf("%d",a[++i]);
return 0;
}

A. 15
B. 20
C. 25
D. 5

©LPU CSE101 C Programming


Q8
What will be the output of the following program?
#include<stdio.h>
int main()
{
int a[5] = {5, 1, 15, 20, 25};
int i, j, m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d %d %d",i,j,m);
return 0;
}
A. 3, 2, 15
B. 2, 3, 20
C. 2, 1, 15
D. 1, 2, 5

©LPU CSE101 C Programming


Q9
What is the output of C program.?
int main()
{
float marks[3] = {90.5, 92.5, 96.5};
int a=0;
while(a<3)
{
printf("%.2f,", marks[a]);
a++;
}
return 0;
}
A) 90.5 92.5 96.5
B) 90.50 92.50 96.50
C) 0.00 0.00 0.00
D) Compiler error

©LPU CSE101 C Programming


Q10
If the number of elements in array are:20, then number of
passes as per bubble sort will be
A. 20
B. 19
C. 18
D. 21

©LPU CSE101 C Programming


Q11
If array elements are already arranged in ascending order, and if
the key element is 23, and middle indexed element is 35, then
what expression will be used as per the condition in binary
search?
A. beg=mid+1
B. last=mid-1
C. mid=mid-1
D. beg=beg+1

Here, beg: starting index, last: ending index, mid:middle index

©LPU CSE101 C Programming


Q12
If array elements are already arranged in ascending order, and if
the key element is 98, and middle indexed element is 50, then
what expression will be used as per the condition in binary
search?
A. beg=mid+1
B. last=mid-1
C. mid=mid-1
D. beg=beg+1

Here, beg: starting index, last: ending index, mid:middle index

©LPU CSE101 C Programming


Q13
//What will be the output of the A. 18
following program?
#include<stdio.h> B. 2
void process(int[],int); C. -2
int main() D. 3
{
int a[5] = {15, 3, 10, 4, 6};
process(a,5);
printf("%d",a[0]+a[1]);
return 0;
}
void process(int x[],int z)
{
int i;
for(i=0;i<z;i++)
{
if(x[i]%5==0)
{
x[i]=-1;
}
}
}
©LPU CSE101 C Programming
CSE101-Lec#17(Part-2)
• Multidimensional Arrays(2D Array)

©LPU CSE101 C Programming


2D-Array
• The basic form of declaring a two-dimensional array of size
x, y:
• Syntax:
• data_type array_name[x][y];
• data_type: Type of data to be stored. Valid C/C++ data type.
• We can declare a two dimensional integer array say ‘x’ of
size 10,20 as:
• int x[10][20];
• Elements in two-dimensional arrays are commonly referred
by x[i][j] where i is the row number and ‘j’ is the column
number

©LPU CSE101 C Programming


2D-Array
• A two – dimensional array can be seen as a table with ‘x’ rows
and ‘y’ columns where the row number ranges from 0 to (x-1)
and column number ranges from 0 to (y-1). A two –
dimensional array ‘x’ with 3 rows and 3 columns is shown
below:

©LPU CSE101 C Programming


Also known as Multiple-Subscripted Arrays

• Multiple subscripted arrays


– Tables with rows and columns (m by n array)
– Like matrices: specify row, then column
int a[rows][column];

Column 0 Column 1 Column 2 Column 3


0 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
a[
Row 0
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript
Array name
Row subscript
4
©LPU CSE101 C Programming
Memory representation of 2D-Array
• A 2D array’s elements are stored in continuous memory locations. It can
be represented in memory using any of the following two ways:

1. Column-Major Order
2. Row-Major Order

1. Column-Major Order:
In this method the elements are stored column wise, i.e. m elements of
first column are stored in first m locations, m elements of second column
are stored in next m locations and so on. E.g.
A 3 x 4 array will stored as below:

©LPU CSE101 C Programming


Memory representation of 2D-Array
• 2. Row-Major Order:
In this method the elements are stored row wise, i.e. n
elements of first row are stored in first n locations, n elements
of second row are stored in next n locations and so on. E.g.
A 3 x 4 array will stored as below:

©LPU CSE101 C Programming


Initialization
1) Initializing at the point of declaration:
1 2
3 4
• int a[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
Initializers grouped by row in braces
• If not enough, unspecified elements set to zero
1 0
3 4
• Int a[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
• int a3[2][2]={1,2};//Remaining elements are zero
• int a4[2][2]={0};//All elements are zero

©LPU CSE101 C Programming


Initialization
• int a5[][2]={1,2,3};//It is possible to skip row size, if
elements are initialized at the point of declaration
• int a[2][]={1,2,3};//Not possible to skip column
size[Error will come]
• int a[][]={1,2,3};//Not possible to skip both row and
column size[Error will come]

©LPU CSE101 C Programming


Initialization
2) Taking input from user
int a[3][3], i, j;
for(i=0; i<3; i++)
{ // for loop for rows
for(j=0; j<3;j++)
{ // for loop for columns
printf(“enter the value ofa[%d][%d]: ”, i, j);
scanf(“%d”, &a[i][j]);
} //end for columns

} //end for rows

©LPU CSE101 C Programming


#include<stdio.h>
void main() Program to
{
int a[3][3], i, j; display 2D
for(i=0; i<3; i++)
{ // for loop for rows array
for(j=0; j<3;j++)
{ // for loop for columns
printf(“enter the value of a[%d][%d]: ”, i, j);
scanf(“%d”, &a[i][j]);
} //end for columns
} //end for rows
printf(“elements of 2D matrix are”);
for(i=0; i<3; i++)
{
for(j=0;j<3;j++)
{
print(“%d\t”, a[i][j]);
} //end for
printf(“\n”);
} //end for
} //end main

©LPU CSE101 C Programming


enter the value of a[0][1] :1
enter the value of a[0][1] :2
enter the value of a[0][1] :3
enter the value of a[0][1] :4
enter the value of a[0][1] :5
enter the value of a[0][1] :6
enter the value of a[0][1] :7
enter the value of a[0][1] :8
enter the value of a[0][1] :9
Element of 2D matrix are:
1 2 3
4 5 6
7 8 9
Matrix operations using 2D arrays
• WAP to find the sum of two matrices
• WAP to display the transpose of a matrix
• WAP to find the sum of diagonal elements of a
matrix
• WAP to perform multiplication of 2 matrices
and display the result

©LPU CSE101 C Programming


WAP to find the sum of two matrices
#include <stdio.h> for(i=0; i<3; i++)
int main() {
{ for(j=0; j<3; j++)
float a[3][3], b[3][3], c[3][3]; {
int i, j; c[i][j] = a[i][j] + b[i][j];
printf("Enter elements of 1st matrix\n"); }
for(i=0; i<3; i++) }
{ // Displaying the sum
for(j=0; j<3 ;j++) printf("\nSum Of Matrix:\n");
{
printf("Enter a%d%d: ", i, j); for(i=0; i<3; i++)
scanf("%f", &a[i][j]); {
} for(j=0; j<3; j++)
} {
// Taking input using nested for loop printf("%.1f\t", c[i][j]);
printf("Enter elements of 2nd matrix\n"); }
for(i=0; i<3; i++) printf("\n");
{ }
for(j=0; j<3; j++) return 0;
{ }
printf("Enter b%d%d: ", i, j);
scanf("%f", &b[i][j]);
}
}
// adding corresponding elements of two arrays

©LPU CSE101 C Programming


WAP to display the transpose of a matrix
#include <stdio.h> // Finding the transpose of matrix a
int main() for(i=0; i<r; i++)
{ {
int a[10][10], transpose[10][10], r, c, i, j; for(j=0; j<c; j++)
printf("Enter rows and columns of matrix: "); {
transpose[i][j] = a[j][i];
scanf("%d %d", &r, &c);
}
}
// Storing elements of the matrix
printf("\nEnter elements of matrix:\n"); // Displaying the transpose of matrix a
for(i=0; i<r; i++) printf("\nTranspose of Matrix:\n");
{ for(i=0; i<r; i++)
for(j=0; j<c; j++) {
{ for(j=0; j<c; j++)
printf("Enter element a%d%d: ",i, j); {
scanf("%d", &a[i][j]); printf("%d ",transpose[i][j]);
} }
}
// Displaying the matrix a[][] */ printf("\n\n");
}
printf("\nEntered Matrix: \n");
for(i=0; i<r; i++)
return 0;
{ }
for(j=0; j<c; j++)
{
printf("%d ", a[i][j]);
}
printf("\n\n");
}

©LPU CSE101 C Programming


WAP to find the sum of diagonal elements of a matrix
#include<stdio.h> for(i=0;i<m;i++)
int main() {
{ for(j=0;j<n;j++)
int a[10][10],sum=0; {
int i,j,m,n; if(i==j)
printf("Enter number of rows and {
column:");
scanf("%d%d",&m,&n); sum=sum+a[i][j];
printf("Enter Elements : "); }
for(i=0;i<m;i++) }
{ }
for(j=0;j<n;j++) printf("Sum of Diagonal
{ Elements = %d ",sum);
scanf("%d",&a[i][j]);
} }
}

©LPU CSE101 C Programming


WAP to perform multiplication of 2 matrices and display the result
#include <stdio.h>
int main()
{ // Initializing all elements of result matrix to 0
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k; for(i=0; i<r1; i++)
printf("Enter rows and column for first matrix: "); {
scanf("%d %d", &r1, &c1); for(j=0; j<c2; j++)
{
printf("Enter rows and column for second matrix: "); result[i][j] = 0;
scanf("%d %d",&r2, &c2); }
// Column of first matrix should be equal to column of second }
matrix and
// Multiplying matrices a and b and
while (c1 != r2)
// storing result in result matrix
{
printf("Error! No. of columns of first matrix not equal to no.of
row of second.\n\n");
printf("Enter rows and column for first matrix: "); for(i=0; i<r1; i++)
scanf("%d %d", &r1, &c1); {
printf("Enter rows and column for second matrix: "); for(j=0; j<c2; j++)
scanf("%d %d",&r2, &c2); {
} for(k=0; k<c1; k++)
// Storing elements of first matrix. {
printf("\nEnter elements of matrix 1:\n"); result[i][j]+=a[i][k]*b[k][j];
for(i=0; i<r1; i++) }
{ }
for(j=0; j<c1; j++) }
{ // Displaying the result
printf("Enter elements a%d%d: ",i,j); printf("\nOutput Matrix:\n");
scanf("%d", &a[i][j]); for(i=0; i<r1; i++)
} {
} for(j=0; j<c2; j++)
// Storing elements of second matrix. {
printf("\nEnter elements of matrix 2:\n"); printf("%d ", result[i][j]);
for(i=0; i<r2; i++) }
{ printf("\n\n");
for(j=0; j<c2; j++) }
{ return 0;
• }
printf("Enter elements b%d%d: ",i, j);
scanf("%d",&b[i][j]);
©LPU CSE101 C Programming
}
}
Dry running

©LPU CSE101 C Programming


Q1
What will be the output of following code?
#include<stdio.h>
int main()
{
int a[][3]={1,2,3,4,5,6};
printf("%d",a[0][2]);
return 0;
}
A. 2
B. 3
C. 4
D. Compile time error

©LPU CSE101 C Programming


Q2
Which of the following is invalid initialization of 2D Array?
A. int a[][2]={1,2,3,4};
B. int a[2][2]={1,2,3,4};
C. int a[2][]={1,2,3,4};
D. int a[2][2]={};

©LPU CSE101 C Programming


Q3
What will be the output of following code?
#include<stdio.h>
int main()
{
int a[3][2]={{1,2},{3,4},{5,6}};
printf("%d",a[1][1]*a[2][1]);
return 0;
}
A. 24
B. 12
C. 8
D. 20

©LPU CSE101 C Programming


CSE101-Lec# 18,19

Pointers in C

©LPU CSE101 C Programming


Introduction-Pointer declaration and Initialization
• A pointer is a variable that holds the address of another variable of same data type.
• The general syntax of declaring pointer variable is
data_type *ptr_name;
Here, data_type is the data type of the value that the pointer will point to. For example:
int *p;
int x= 10;
p=&x; //Pointer initialization[ When some variable’s address is assigned to pointer, it is said to
be initialized]
The '*' informs the compiler that ptr is a pointer variable and the int specifies that it will store the
address of an integer variable. [ ‘*’ is also known as indirection/ or deferencing/ or value at
address operator]
The & operator retrieves the address of x, and copies that to the contents of the pointer ptr. [ ‘&’ is
also known as address of operator]

©LPU CSE101 C Programming


Understanding pointers

©LPU CSE101 C Programming


Pointer Operators
• & (address operator)
– Returns address of operand
int y = 5;
int *yPtr;
yPtr = &y; /* yPtr gets address of y */
yPtr “points to” y

y yptr y
5 500000 600000 600000 5
yPtr

Value of yptr
is the address
©LPU CSE101 C Programming
of y
Example Code
#include<stdio.h> This program
demonstrates
int main()
the use of the
{ pointer
int x=10,*p; operators: &
p=&x; and *
printf(“%u”,p);
printf(“\n%d”,*p);
}

©LPU CSE101 C Programming


Key points related to pointers
➢ Data type of the pointer variable and variable whose address it will store must be of
same type
Example:
int x=10;
float y=2.0;
int *px;
px=&y;//Invalid, as px is of integer type and y is of float type
int *ptr;
ptr=&x;//Valid as both ptr and x are of same types
➢ Any number of pointers can point to the same address
Example:
int x=12;
int *p1=&x,*p2=&x,*p3=&x;// All the three pointers are pointing towards x
➢ Memory taken by any kind of pointer(i.e int, float, char, double…) as always
equivalent to the memory taken by unsigned integer, as pointer will always store
address of a variable( which is always unsigned integer), so the type of pointer will
not make any difference

©LPU CSE101 C Programming


Example-size taken by different type of pointers
#include<stdio.h>
int main()
{
int *pnum;
char *pch;
float *pfnum;
double *pdnum;
long *plnum;
printf("\n Size of integer pointer=%d",sizeof(pnum));
printf("\n Size of character pointer=%d",sizeof(pch));
printf("\n Size of float pointer=%d",sizeof(pfnum));
printf("\n Size of double pointer=%d",sizeof(pdnum));
printf("\n Size of long pointer=%d",sizeof(plnum));
return 0;
}
//All will give the same answer(equivalent to size taken by unsigned integer for a particular
compiler)

©LPU CSE101 C Programming


Program example-Finding area of circle using pointers
#include<stdio.h>
int main()
{
double radius,area=0.0;
double *pradius=&radius,*parea=&area;
printf("\n Enter the radius of the circle:");
scanf("%lf",pradius);
*parea=3.14*(*pradius)*(*pradius);
printf("\n The area of the circle with radius %.2lf = %.2lf",*pradius,*parea);
return 0;
}

©LPU CSE101 C Programming


Types of pointers
• Null pointer
• Wild pointer
• Generic pointer(or void) pointer
• Constant pointer
• Dangling pointer

©LPU CSE101 C Programming


Null pointer
• A Null Pointer is a pointer that does not point to any memory
location
• It is used to initialize a pointer variable when the pointer does not
point to a valid memory address.
• So, if we don’t know in the initial phases, where the pointer will
point? , it is better to initialize pointer with NULL address
To declare a null pointer you may use the predefined constant NULL,
int *ptr = NULL;
or
int *ptr=0;
We can overwrite the NULL address hold by NULL pointer with some
valid address also, in the later stages of program
Note: It is invalid to dereference a null pointer.

©LPU CSE101 C Programming


Example
#include<stdio.h>
int main()
{
int *ptr=NULL;
int a=10;
printf("%u",ptr);// 0 will be displayed
printf(“%d”,*ptr);//Invalid(Dereferencing), as ptr is NULL at this point.
ptr=&a;
printf("\n%d",*ptr);//Now it is allowed, as NULL pointer has starting pointing somewhere
return 0;
}

©LPU CSE101 C Programming


Wild pointer
• Pointer which are not initialized during its definition
holding some junk value( or Garbage address) are
Wild pointer.
• Example of wild pointer:
int *ptr;
• Every pointer when it is not initialized is defined as a
wild pointer.
• As pointer get initialized, start pointing to some
variable its defined as pointer, not a wild one.

©LPU CSE101 C Programming


Example
#include<stdio.h>
int main()
{
int *ptr;//Wild pointer
int a=10;
//printf("%u",ptr);//Gives garbage address value
//printf("\n%d",*ptr);//Gives garbage value stored in the garbage address
ptr=&a;//Now ptr is not a wild pointer
printf("\n%d",*ptr);//
return 0;
}

©LPU CSE101 C Programming


Void pointer
• Is a pointer that can hold the address of variables of
different data types at different times also called
generic pointer.
• The syntax for declaring a void pointer is
void *pointer_name;
• Here, the keyword void represents that the pointer
can point to value of any data type.
• But before accessing the value through generic pointer
by dereferencing it, it must be properly typecasted.
• To Print value stored in pointer variable:
*(data_type*) pointer_name;

©LPU CSE101 C Programming


Limitations of void pointers:
• void pointers cannot be directly dereferenced.
They need to be appropriately typecasted.
• Pointer arithmetic cannot be performed on
void pointers.

©LPU CSE101 C Programming


Example
#include<stdio.h>
int main()
{
int x=10;
char ch='A';
void *gp;
gp=&x;
printf("\n Generic pointer points to the integer value=%d",*(int*)gp);
gp=&ch;
printf("\n Generic pointer now points to the character %c",*(char*)gp);
return 0;
}

©LPU CSE101 C Programming


Constant Pointers
• A constant pointer, ptr, is a pointer that is initialized with an
address, and cannot point to anything else.
• But we can use ptr to change the contents of variable
pointing to
• Example
int value = 22;
int * const ptr = &value;

©LPU CSE101 C Programming


Constant Pointer
• Example:
int * const ptr2

indicates that ptr2 is a pointer which is


constant. This means that ptr2 cannot be
made to point to another integer.
• However the integer pointed by ptr2 can be
changed.

©LPU CSE101 C Programming


Example
#include<stdio.h>
int main()
{
int var1 = 60, var2 = 70;
int *const ptr = &var1;
printf("\n%d",*ptr);
//ptr = &var2; //Invalid-Error will arise
//printf("%d\n", *ptr);
return 0;
}

©LPU CSE101 C Programming


Dangling pointer

• It is a type of pointer which point towards such a


memory location which is already deleted/ or
deallocated.
• It is a problem associated with pointers, where in a
pointer is unnecessarily pointing towards deleted
memory location
• It can be resolved through assigning NULL address
once, the memory has been deallocated

©LPU CSE101 C Programming


Dangling pointer-Example 1[Compile time case]
When local variable goes out of scope
#include<stdio.h>
int main()
{
int *ptr;
{
int val=23;
ptr=&val;
printf("\n%d",*ptr);// 23 is printed
printf("\n%u",ptr);// Address of val is printed
}
printf("\n%u",ptr);// Same address is printed, even val is destroyed, hence ptr
is dangling pointer
ptr=NULL;//Solution
printf("\n%u",ptr);// Now ptr is not a dangling pointer[0 address value is
printed]
return 0;
}

©LPU CSE101 C Programming


Dangling pointer-Example 2[Runtime/or Dynamic memory allocation case]
When free() function is called
// Deallocating a memory pointed by ptr causes
// dangling pointer
#include <stdlib.h>
#include <stdio.h>
int main()
{

int n=1;
int *ptr = (int *)malloc(n*sizeof(int));
*ptr=6;
printf("%d",*ptr);//6 is printed
printf("\n%d",ptr);//Printing address hold by pointer before deallocation
free(ptr);
printf("\n%d",ptr);//Same address will be printed(Dangling pointer)
//SOLUTION
ptr = NULL;//Pointer is now changed to NULL pointer
printf("\n%d",ptr);//0 will be printed
return 0;
}
©LPU CSE101 C Programming
Example-1-Passing pointer to a function(or call by reference)

//Passing arguments to function using pointers


#include<stdio.h>
void sum(int *a,int *b,int *t);
int main()
{
int num1,num2,total;
printf("\n Enter the first number:");
scanf("%d",&num1);
printf("\n Enter the second number:");
scanf("%d",&num2);
sum(&num1,&num2,&total);
printf("\n Total=%d",total);
return 0;
}
void sum(int *a,int *b,int *t)
{
*t=*a+*b;
}

©LPU CSE101 C Programming


Example-2-Passing pointer to a function(or call by reference)
#include<stdio.h>
void read(float *b,float *h);
void calculate_area(float *b,float *h,float *a);
int main()
{
float base,height,area;
read(&base,&height);
calculate_area(&base,&height,&area);
printf("\n Area is :%f",area);
return 0;
}
void read(float *b,float *h)
{
printf("\n Enter the base of the triangle:");
scanf("%f",b);
printf("\n Enter the height of the triangle:");
scanf("%f",h);
}
void calculate_area(float *b,float *h,float *a)
{
*a=0.5*(*b)*(*h);
}

©LPU CSE101 C Programming


Q1
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int *ptr, a = 10;
ptr = &a;
*ptr += 1;
printf("%d,%d", *ptr, a);
}
A. 10,10
B. 10,11
C. 11,10
D. 11,11

©LPU CSE101 C Programming


Q2
Comment on the following pointer declaration.
int *ptr, p;
A. ptr is a pointer to integer, p is not
B. ptr and p, both are pointers to integer
C. ptr is a pointer to integer, p may or may not be
D. ptr and p both are not pointers to integer

©LPU CSE101 C Programming


Q3
What will be the output of the following C code?
#include <stdio.h>
int x = 0;
int main()
{
int *ptr = &x;
printf("%p\n", ptr);
x++;
printf("%p\n ", ptr);
}
A. Same address
B. Different address
C. Compile time error
D. None of these

©LPU CSE101 C Programming


Q4
#include <stdio.h>
int main()
{
int x=10;
int *p1=&x,*p2;
*p1=x+3;
p2=p1;
*p2=*p1+2;
printf("%d",x);
return 0;
}
A. 13
B. 12
C. 10
D. 15

©LPU CSE101 C Programming


Q5
What will be the output of the following C code?
#include <stdio.h>
int main()
{
char *p = NULL;
char *q = 0;
if (p)
printf(" p ");
else
printf("nullp");
if (q)
printf("q\n");
else
printf(" nullq\n");
}
a) nullp nullq
b) Nothing will be printed
c) Compile time error
d) p q
©LPU CSE101 C Programming
Q6
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i = 10;
void *p = &i;
printf("%d\n", (int)*p);
return 0;
}
A. Compile time error
B. Program will crash
C. 10
D. Address of i

©LPU CSE101 C Programming


Q7
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i = 10;
void *p = &i;
printf("%f\n", *(float*)p);
return 0;
}
A. Compile time error
B. 10.000000
C. 10
D. 0.000000

©LPU CSE101 C Programming


Q8
What will be the output of the following C code?
#include <stdio.h>
int x = 0;
void main()
{
int *const ptr = &x;
printf("%p\n", ptr);
ptr++;
printf("%p\n ", ptr);
}
A. 0 1
B. Compile time error
C. 0xbfd605e8 0xbfd605ec
D. 0xbfd605e8 0xbfd605e8

©LPU CSE101 C Programming


Q9
What will be the output of the following C code?
#include <stdio.h>
void foo(int *p)
{
int j = 2;
p = &j;
printf("%d ", *p);
}
int main()
{
int i = 97, *p = &i;
foo(&i);
printf("%d ", *p);
}

A. 2 97
B. 2 2
C. Compile time error
D. Program will crash
©LPU CSE101 C Programming
Q10
What will be the output of the following C code?
#include <stdio.h>
void m(int *p, int *q)
{
p=q;
*p=8;
*q=7;
}
int main()
{
int a = 6, b = 5;
m(&a, &b);
printf("%d %d\n", a, b);
}
a) 8 7
b) 6 7
c) 6 5
d) 8 8

©LPU CSE101 C Programming


CSE101-Lec 20
Pointer arithmetic and expressions
Pointer and One dimensional array(or Pointer to 1D array)
Pointer arithmetic
• A limited set of arithmetic operations can be performed on pointers. A
pointer may be:
➢incremented ( ++ ), e.g. ptr++, ++ptr
➢decremented (-- ), e.g. ptr--, --ptr
➢an integer may be added to a pointer ( + or += ), e.g. ptr+2, ptr=ptr+2
➢an integer may be subtracted from a pointer ( – or -= ), e.g. ptr-2, ptr=ptr-2
➢We can subtract two pointers, if they are pointing towards same array
➢We can compare two pointers, if they are pointing towards same array
• Following set of operations are not applicable on pointers
• We cannot add two pointers(addresses)
• We cannot multiply, divide and modulo two pointers(addresses)
• We cannot multiply, divide, modulo any constant from pointer(address)
Pointer arithmetic-Example
#include<stdio.h> //Comparing two pointers
int main() while(p1<=p2)
{ {
int arr[]={1,2,3,4,5,6,7,8,9}; printf("\n%d",*p1);//Comparison of
two pointers (Pointers pointing to the same array)
int *p1,*p2; p1++;
p1=arr; }
p1++;// p1 will point towards next memory //Following are the invalid arithmetic
location operations(Not allowed on pointers)
printf("\n%d",*p1);//2 will be displayed //printf("\n%d",p1+p2);//Invalid arithmetic
p1--;//p1 will point towards previous memory //printf("\n%d",p1/p2);//Invalid arithmetic
location //printf("\n%d",p1*p2);//Invalid arithmetic
printf("\n%d",*p1);// 1 will be displayed //printf("\n%d",p1%p2);//Invalid arithmetic
p1=p1+2;// Adding a constant to pointer(p1 will //printf("\n%d",p1*2);//Invalid arithmetic
point towards 3rd element) //printf("\n%d",p1/2);//Invalid arithmetic
printf("\n%d",*p1);// 3 will be displayed //printf("\n%d",p1%2);//Invalid arithmetic
p1=p1-2;//Subtracting a constant from a return 0;
pointer(P1 will point towards first element)
}
printf("\n%d",*p1);// 1 will be displayed
p2=&arr[4];
printf("\n%d",p2-p1);//Subtracting two
pointers(Returns 4(no. of elements b/w+1)(Pointers
pointing to the same array)
Pointer expressions
• We can perform rich set of operations like: arithmetic, relational,
assignment, conditional, unary, bitwise on pointer variables
• Examples:
*ptr1 + *ptr2
*ptr1 * *ptr2
*ptr1 + *ptr2 - *ptr3
*ptr1 > *ptr2
*ptr1 < *ptr2
*a=10
*b+=20
*z=3.5
*s=4.56743
c = (*ptr1 > *ptr2) ? *ptr1 : *ptr2;
(*ptr1)++
(*ptr1)--
*ptr1 & *ptr2
*ptr1 | *ptr2
*ptr1 ^ *ptr2
All these are the valid pointer expressions, and here we are working on
values(not on addresses)
Pointer to an array(1D)

• A pointer can point towards an array using following notation:


Consider:
int a[]={1,2,3,4,5};
int *p=a; // pointer p starts pointing towards first element of array
Or
int *p=&a[0];
Now we can access elements of given array via pointer, such as:
int i;
for(i=0;i<5;i++)
{
printf(“\n%d”,*(p+i));
}
The Relationship Between Pointers and Arrays

• Arrays and pointers closely related


• Array name is like a constant pointer
• Pointers can do array subscripting operations
• Define an array b[5] and a pointer bPtr
• To set bPtr to point to b[5]:
bPtr = b;
• The array name (b) is actually the address of first element of the
array b[5] which is equivalent to
bPtr = &b[0]
• Explicitly assigns bPtr to address of first element of b
The Relationship Between Pointers and Arrays

• Element b[3]
• Can be accessed by *(bPtr + 3)
• Where 3 is the offset. Called pointer/offset notation
• Can be accessed by bptr[3]
• Called pointer/subscript notation
• bPtr[3] same as b[3]
• Can be accessed by performing pointer arithmetic on the array
itself
*(b + 3)
• Array name itself is an address or pointer. It points to the first
element(0th element) of array.
• The arrays are accessed by pointers in same way as we access arrays
using array name.
• Consider an array b[5] and a pointer bPtr:
• bPtr[3] is same as b[3]
Example-Different notations with pointer to an array
#include<stdio.h>
int main()
{
int a[]={1,2,3,4,5};
int *p=a;
// Different notations with pointer to an array for displaying second element
// Same terminology can be used to display any element
// All will display 2 on screen
printf("\n%d",*(p+1));
printf("\n%d",*(a+1));
printf("\n%d",p[1]);
printf("\n%d",1[p]);
printf("\n%d",1[a]);
return 0;
}
Pointer to an array with pointer arithmetic
#include<stdio.h>
int main()
{
int arr[]={1,2,3,4,5};
int i;
int *p;
p=arr;
printf("\n First value is:%d",*p);
p=p+1;
printf("\n Second value is:%d",*p);
*p=45;
p=p+2;
*p=-2;
printf("\n Modified array is:");
for(i=0;i<5;i++)
{
printf("\n%d",arr[i]);//We can also write i[arr]
}
p=arr;
*(p+1)=0;
*(p-1)=1;
printf("\n Modified array is:");
for(i=0;i<5;i++)
{
printf("\n%d",*(p+i));//We can also write *(i+arr)
Program example 1-WAP to read and display elements
of 1D array using pointer to an array
#include<stdio.h>
int main()
{
int i,n;
int a[10],*parr=a;
printf("\n Enter the number of elements:");
scanf("%d",&n);
printf("\n Enter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",parr+i);
}
printf("\n Entered array elements are:");
for(i=0;i<n;i++)
{
printf("\t %d",*(parr+i));
}
return 0;
}
Program example 2-WAP to find the sum and mean of 1D array elements using pointer to an array
#include<stdio.h>
int main()
{
int i,n,arr[20],sum=0;
int *pn=&n,*parr=arr,*psum=&sum;
float mean=0.0,*pmean=&mean;
printf("\n Enter the number of elements in the array:");
scanf("%d",pn);
for(i=0;i<*pn;i++)
{
printf("\n Enter the number:");
scanf("%d",(parr+i));
}
for(i=0;i<*pn;i++)
{
*psum=*psum+*(arr+i);
}
*pmean=*psum/ *pn;
printf("\n The numbers you entered are:");
for(i=0;i<*pn;i++)
printf("\n%d",*(arr+i));
printf("\n The sum is:%d",*psum);
printf("\n The mean is:%f",*pmean);
return 0;
}
Pointer vs Array
1) the sizeof operator
sizeof(array) returns the amount of memory used by all elements in array
sizeof(pointer) only returns the amount of memory used by the pointer variable itself
2) the & operator
&array is an alias for &array[0] and returns the address of the first element in array
&pointer returns the address of pointer
3) a string literal initialization of a character array
char array[] = “abc” sets the first four elements in array to ‘a’, ‘b’, ‘c’, and ‘\0’
char *pointer = “abc” sets pointer to the address of the “abc” string (which may be stored in
read-only memory and thus unchangeable)
4) Pointer variable can be assigned a value whereas array variable cannot be.
int a[10];
int *p;
p=a; /*legal*/
a=p; /*illegal*/
5) Arithmetic on pointer variable is allowed.
p++; /*Legal*/
a++; /*illegal*/
Q1(Output)
#include<stdio.h>
int main()
{
int a[]={1,2,3,4};
int *p=a,i;
p++;
*(p+1)=29;
p=p+1;
*p=23;
p--;
*(p+0)=12;
p=a;
for(i=0;i<4;i++)
printf("%d ",*(p+i));
return 0;
}
A. 1 12 23 4
B. 1 29 23 12
C. 1 23 12 29
D. 1 23 3 4
Q2(Output)
#include<stdio.h>
int main()
{
int a[]={1,2,3,4};
int *p1=a,i;
int *p2=&a[2];
p2--;
*(p2-1)=90;
p1=p2;
*p1=100;
for(i=0;i<4;i++)
printf("%d ",a[i]);
return 0;
}
A. 1 90 100 4
B. 90 100 3 4
C. 90 2 100 4
D. 1 2 90 100
Q3(Output)
#include<stdio.h>
int main()
{
int a[]={1,2,3,4};
int *p1=a,*p2=&a[3];
p1++;
printf("\n%d %d",p2-p1,*p2-*p1);
return 0;
}
A. 2 2
B. 3 2
C. 3 3
D. 2 3
Q4(Output)
#include<stdio.h>
int main()
{
int a[]={1,2,3,4};
int *p=a;
*(p+1)=*(p+2);
printf("\n%d",a[2]);
return 0;
}
A. 3
B. 2
C. Compile time error
D. 0
Q5(Output)
#include<stdio.h>
int main()
{
int a[]={1,2,3,4};
int *p=a,x;
x=*p++;
printf("\n%d %d",x,*p);
return 0;
}
A. 1 2
B. 2 2
C. 1 1
D. Compile time error
CSE101-Lec#21
Dynamic memory management

©LPU CSE101 C Programming


Dynamic Memory Allocation
• The statement:
int marks[100];
allocates block of memory to 100 elements of
type int and memory is also contiguous. If one
int requires 4 bytes of memory , a total of 400
bytes are allocated.
Why this approach of declaring array is not useful?
• This may lead to wastage of memory if all
allocated memory is not utilized.

©LPU CSE101 C Programming


• Dynamic memory allocation allows a program to obtain more
memory space, while running or to release space when no
space is required.
• There are 4 library functions under "stdlib.h" for dynamic
memory allocation.
Function Use of Function
malloc() Allocates requested size of bytes and returns a pointer
first byte of allocated space
calloc() Allocates space for an array elements, initializes to zero
and then returns a pointer to memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space

©LPU CSE101 C Programming


malloc()
• The name malloc stands for "memory allocation".
• The malloc() function allocates a block of memory of
specified size from the memory heap.
• Syntax:
void * malloc(size);
• Here size is the number of bytes of storage to be allocated.
• If memory is allocated successfully , it returns a pointer to
first location of newly allocated block of memory.
• If memory is not allocated i.e. no enough space exists for new
block or some other reason, returns NULL.

©LPU CSE101 C Programming


malloc()
• Return type of malloc() is void pointer , it has to be cast
to the type of data being dealt with.
• memory allocated by malloc() by default contain the
garbage values.
• Example:
int *p;
p=(int*)malloc(n*sizeof(int));
• In the above example, p is pointer of type integer
• int* tells to what type it will be pointing. int tells that
the malloc() function is type casted to return the
address of integer variable.
• n is the number of elements

©LPU CSE101 C Programming


#include <stdio.h>
#include <stdlib.h> /*required for dynamic
Program to
memory*/ allocate
int main()
memory to
{
int number, *ptr, i; integers.
printf("How many ints would you like store?");
scanf("%d", &number);
ptr = (int *)malloc(number*sizeof(int));
/*allocate memory*/
for(i=0 ; i<number ; i++) {
*(ptr+i) = i;
}
for(i=0 ; i<number ; i++){
printf("%d\n", *(ptr + i));
}
return 0;
}

©LPU CSE101 C Programming


How many ints would you like store? 3
0
1
2

©LPU CSE101 C Programming


calloc()
• The name calloc stands for "contiguous allocation".
• It provides access to memory, which is available for dynamic
allocation of variable-sized blocks of memory.
• Syntax:
void *calloc(size_t nitems, size_t size);
• calloc is similar to malloc, but the main difference is that the values
stored in the allocated memory space is zero by default. With malloc,
the allocated memory could have any garbage value.
• calloc() requires two arguments.
1. The first is the number of variables you'd like to allocate memory
for.
2. The second is the size of each variable.

©LPU CSE101 C Programming


calloc()
• If memory is allocated successfully, function
calloc()returns a pointer to the first location
of newly allocated block of memory otherwise
returns NULL
• Memory allocated by calloc() by default
contains the zero values.
• E.g. If we want to allocate memory for storing n
integer numbers in contiguous memory locations
int *p;
p=(int*)calloc(n, sizeof(int));

©LPU CSE101 C Programming


#include<stdio.h>
#include<stdlib.h> Program to
void main()
{ show calloc()
float *x;
int i,n;
function
printf("how many elements do u want?");
scanf("%d",&n);
x=(float*)calloc(n,sizeof(float));
if(x!=NULL)
{
printf("data is=\n");
for(i=0;i<n;i++)
printf("\n x[%d]=%d ",i,*(x+i));
}
else
printf("calloc failed");
getch();
}

©LPU CSE101 C Programming


how many elements do u want 3
0
0
0

©LPU CSE101 C Programming


Difference between malloc() and calloc()
calloc() malloc()
Function: Allocates a region of memory Allocates "size" bytes of
large enough to hold "n memory.
elements" of "size" bytes each.
Syntax: void *calloc void *malloc
(number_of_blocks, (size_in_bytes);
size_in_bytes);
No. of arguments: 2 1
Contents of The allocated region is initialized The contents of allocated
allocated memory: to zero. memory are not changed. i.e.,
the memory contains garbage
values.

Return value: void pointer (void *). void pointer (void *).
If the allocation succeeds, a If the allocation succeeds, a
pointer to the block of memory pointer to the block of memory
is returned. is returned.
©LPU CSE101 C Programming
realloc()
• Now suppose you've allocated a certain number of
bytes for an array but later find that you want to add
values to it. You could copy everything into a larger
array, which is inefficient, or you can allocate more
bytes using realloc(), without losing your data.
• realloc() takes two arguments.
1. The first is the pointer referencing the memory.
2. The second is the total number of bytes you want to
reallocate.
• Passing zero as the second argument is the equivalent
of calling free.
• Syntax:
void *realloc(pointerToObject, newsize);

©LPU CSE101 C Programming


realloc()
• If memory is allocated successfully, function
realloc()returns a pointer to the first
location of newly allocated block of memory
which may be at same site or at new site and
copy the contents from previous location to a
new location if required , otherwise returns
NULL.

©LPU CSE101 C Programming


#include<stdio.h>
#include <stdlib.h> This example
int main()
{ uses calloc to
int *ptr, i;
ptr = (int *)calloc(5, sizeof(int));
allocate
*ptr = 1; memory
*(ptr+1) = 2;
ptr[2] = 4; then realloc
ptr[3] = 8;
ptr[4] = 16;
ptr = (int *)realloc(ptr, 7*sizeof(int));
printf("Now allocating more memory... \n");
ptr[5] = 32; /* now it's legal! */
ptr[6] = 64;
for(i=0 ; i<7 ; i++){
printf("ptr[%d] holds %d\n", i, ptr[i]);
}
}

©LPU CSE101 C Programming


Now allocating more memory...
ptr[0] holds 1
ptr[1] holds 2
ptr[2] holds 4
ptr[3] holds 8
ptr[4] holds 16
ptr[5] holds 32
ptr[6] holds 64

©LPU CSE101 C Programming


free()
• Deallocates a memory block allocated by
previous call to malloc(), calloc()
or realloc() and return it to memory to
be used for other purposes.
• Syntax:
void *free(void *block);
• The argument of function free() is the
pointer to block of memory which is to be
freed.

©LPU CSE101 C Programming


free()
• The realloc() function can behave the
same as free() function provided the
second argument passed to realloc() is 0.
free(ptr);
which is equivalent to
realloc(ptr,0);

©LPU CSE101 C Programming


Memory Leak
• A condition caused by a program that does not
free up the extra memory it allocates.
• It occurs when the dynamically allocated memory
is no longer needed but it is not freed.
• If we continuously keep on allocating the memory
without freeing it for reuse, the entire heap
storage will be exhausted.
• In such circumstances, the memory allocation
functions will start failing and program will start
behaving unexpectedly

©LPU CSE101 C Programming


What is the return type of malloc() or
calloc()?

A. int *
B. int **
C. void *
D. void **

©LPU CSE101 C Programming


Which of the following statement is correct
prototype of the malloc() function in c ?

A. int* malloc(int);
B. char* malloc(char);
C. unsigned int* malloc(unsigned int);
D. void* malloc(size_t);

©LPU CSE101 C Programming


What is the output of this program?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *j = (int*)malloc(4 * sizeof(int));
*j = 15;
free(j);
printf("%d", *j);
return 0;
}
A. Compilation error
B. Some Garbage value
C. 0
D. Nothing prints

©LPU CSE101 C Programming


CSE101-Lec23
Strings

©LPU CSE101 C Programming


Outline
• Introduction to string
– Declaration
– Initialization
• Reading and writing strings
– functions of the standard input/output library
(stdio.h)
• Processing of strings.

Comparing strings
Determining the length of string

©LPU CSE101 C Programming


Fundamentals of characters
• Characters
– Building blocks of programs
• Every program is a sequence of meaningfully grouped
characters
– Character constant
• An int value represented as a character in single quotes
• 'z' represents the integer value of z (122 ASCII value).

©LPU CSE101 C Programming


Fundamentals of strings
• Strings
– Array of characters treated as a single unit called
string:
• Can include letters, digits and special characters (*, /,
$)
– String literal (string constant) - written in double
quotes
• “Lovely Professional University."

©LPU CSE101 C Programming


Fundamentals of strings
• Strings are arrays of characters
– String is a pointer to first character (like array)
– Value of string is the address of first character
• Each element of the string is stored in a
contiguous memory locations.
• Terminated by a null character(‘\0’) which is
automatically inserted by the compiler to
indicate the end of string.

©LPU CSE101 C Programming


String Definition
• They are defined as
char array_name[size];
e.g. char carname[30];
or char *carname;
• It defines an array name and reserves 30 bytes
for storing characters and single character
consumes 1 bytes each.
• Since the last byte is used for storing null
character so total number of character specified
by the user cannot exceed 29.

©LPU CSE101 C Programming


String Initialization
• String Initialization
– Two ways:
– Define as a character array or a variable of type
char *
char color[] = "blue"; //char array
Or char color[] = { 'b', 'l', 'u', 'e', '\0' };
char *colorPtr = "blue"; //pointer variable

– Remember that strings represented as character


arrays end with '\0'
b •l coloruhas 5 eelements
\0 b l u e \0
color Temporary

©LPU CSE101 C Programming


*colorPtr
char *colorPtr = "blue"; //pointer variable
Printf(“%s”, colorPtr);

Is correct way to use pointer to char. But:


char *colorPtr; //pointer variable
scanf(“%s”, &colorPtr);
printf(“%s”, colorPtr); /* invalid statement %s don’t
work with pointer to char */

©LPU CSE101 C Programming


String Input/Output
• Inputting strings
– Use scanf.
scanf("%s", word);
• Copies input into word[]
• Do not need & (because a string is a pointer)
– Remember to leave last place in the array for '\0‘.
– Because array knows no bounds the string written
beyond char array size will overwrite the data in
memory.
• Displaying strings
– Use printf.
printf("%s", word);

©LPU CSE101 C Programming


#include <stdio.h>
Program to read
void main() and display
{
string
char carname[20]; //string char array
printf(“Enter the name of your car: ");
scanf("%s", carname);
// to display the input
printf(“\nName of car is %s", carname);

} //end main

Enter the name of your car: XUV500


Name of car is XUV500 Output

©LPU CSE101 C Programming


How?
• The last program will print only a single word
not the sentences with white spaces?
• That is if input is
Lovely Professional University
• Output will be: use gets and puts

Lovely
• So how to print:
Lovely Professional University

©LPU CSE101 C Programming


#include <stdio.h>
Program to print
void main() strings with
{
white spaces
char name[100]; //string char array using library
puts(“\nEnter a string: ”); functions
gets(name); //to input string with space

printf(“\nString is: ”)
puts(name); //to output const string

}//end main

Enter a string:
Lovely Professional University Output
String is:
Lovely Professional University
©LPU CSE101 C Programming
#include <stdio.h>
Program to print
void main() strings character
{
by character
char name[]={“Lovely Professional using loop.
University"}; //string char array
int i=0;

while(name[i]!='\0') //untill null character


{
printf("%c", name[i]);
i++;
}//end while

}//end main

Lovely Professional University


Output

©LPU CSE101 C Programming


What is the output of C Program with Strings.?
int main()
{
char ary[]="Discovery Channel";
printf("%s",ary);
return 0;
}
A) D
B) Discovery Channel
C) Discovery
D) Compiler error

©LPU CSE101 C Programming


What is the output of C Program with Pointer.?
int main() { char country[]=“INDIA";
char *ptr;
ptr=country;
while(*ptr != '\0')
{ printf("%c", *ptr);
ptr++;
} return 0;
}

A)I
B) INDIA
C) Compiler error
D) None of the above

©LPU CSE101 C Programming


What is the output of C Program with Pointer.?
int main()
{
char country[]=“INDIA";
char *ptr;
ptr=country;
while(*ptr != '\0')
{
printf("%c", *ptr);

}
return 0;
}
A)I
B) INDIA
C) I infinite times
D) None of the above

©LPU CSE101 C Programming


CSE101-Lec#24
• Some other functions from string handling
library

©LPU CSE101 C Programming


Outline
• String Conversion Functions
• Character arithmetic

©LPU CSE101 C Programming


String Conversion Functions
• String Conversion functions
– In <stdlib.h> (general utilities library)
• Convert strings of digits to integer and
floating-point values and vice versa
Function prototype Function description

double atof( const char *nPtr ); Converts the string nPtr to double.

int atoi( const char *nPtr ); Converts the string nPtr to int.

long atol( const char *nPtr ); Converts the string nPtr to long int.

char * itoa(int value, char *str,int base); Converts the integer value to string

©LPU CSE101 C Programming


atof()
Function atof
• Function atof converts its argument—a string
that represents a floating-point number—to a
double value.
• The function returns the double value.
• If the converted value cannot be
represented—for example, if the first
character of the string is a letter—the
behavior of function atof is undefined.

©LPU CSE101 C Programming


atof()-Program example
#include<stdio.h>
#include<stdlib.h>
int main()
{
double d;
d=atof("99.23");
printf("%.2lf",d);
return 0;
}

©LPU CSE101 C Programming


atoi()
Function atoi
• Function atoi converts its argument—a string
of digits that represents an integer— to an int
value.
• The function returns the int value.
• If the converted value cannot be represented,
the behavior of function atoi is undefined.

©LPU CSE101 C Programming


atoi()-Program example
#include<stdio.h>
#include<stdlib.h>
int main()
{
char x[]="99";
int i;
i=atoi(x);
printf("%d",i);
return 0;
}

©LPU CSE101 C Programming


atol()
Function atol
• Function atol converts its argument—a string of
digits representing a long integer— to a long
value.
• The function returns the long value.
• If the converted value cannot be represented, the
behavior of function atol is undefined.
• If int and long are both stored in 4 bytes, function
atoi and function atol work identically.

©LPU CSE101 C Programming


atol()-Program example
#include<stdio.h>
#include<stdlib.h>
int main()
{
long int i;
char x[]="10000000";
i=atol(x);
printf("%ld",i);
return 0;
}

©LPU CSE101 C Programming


itoa()
• itoa () function in C language converts int data
type to string data type. Syntax for
this function is given below.
• char * itoa ( int value, char * str, int base );
• Base values could be: 2, 8, 10,16(Depending
upon the number system)

©LPU CSE101 C Programming


itoa()-Program example
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a=123;
char str[100];
itoa(a,str,2);
printf("\n Binary value:%s",str);
itoa(a,str,10);
printf("\n Decimal value:%s",str);
itoa(a,str,16);
printf("\n Hexadecimal value:%s",str);
itoa(a,str,8);
printf("\n Octal value:%s",str);
return 0;
}

©LPU CSE101 C Programming


Converting from float to string
• There is no inbuilt function for this type of conversion, so we need to write the explicit
code for the same,
• In the following ftoa1() is a user defined function which is converting floating type value to
string
• Example:
#include<stdio.h>
void ftoa1(float f1,char s[])
{
sprintf(s,"%f",f1);// s is array, %f format specifier and f1 is float variable
}
int main()
{
char str[20];
float f=12.340000;
ftoa1(f,str);//it means convert float value f to string and store it in str// function call//
printf("\n%s",str);
return 0;
}

©LPU CSE101 C Programming


Character arithmetic
• To perform increment , decrement, addition
subtraction operations on the characters.
• These operations work on the ASCII value of
characters.
• Starting from ASCII value of ‘a’ = 97 to the
ASCII value of ‘z’ = 122

©LPU CSE101 C Programming


Increment
• To display next char value
int main()
{
char x = 'a' + 1;
printf("%c", x); // Display Result = 'b‘
printf("%c", ++x); // Display Result = ‘c‘

©LPU CSE101 C Programming


Decrement
• To display previous char value
int main()
{
char x = ‘b' - 1;
printf("%c", x); // Display Result = ‘a‘
}

©LPU CSE101 C Programming


Addition
• Adding two ASCII values
int main()
{
char x = 'a‘ + ‘c’;
printf("%c", x); /* Display Result = - ( addition of
ASCII of a and c is 196) */
}

©LPU CSE101 C Programming


Subtraction
• Subtracting two ASCII values
int main()
{
char x = ‘z’ – ‘a’;
printf("%c",x); /* Display Result = ↓ (difference
between ASCII of z and a ) */
}

©LPU CSE101 C Programming


User Defined Types
(Structures and Union)

©LPU CSE101 C Programming


Outline
• Declaration of a structure
• Definition and initialization of structures.
• Accessing structures.

©LPU CSE101 C Programming


Introduction
• Structures are user defined data types.
• Structures
– Structure is a group of data items of different data types
held together in a single unit.
– Collections of related variables under one name
• Can contain variables of different data types
– Commonly used to define records to be stored in files.

©LPU CSE101 C Programming


Why Use Structures?
• Quite often we deal with entities that are collection of dissimilar
data types.
• For example, suppose you want to store data about a car. You
might want to store its name (a string), its price (a float) and
number of seats in it (an int).
• If data about say 3 such cars is to be stored, then we can follow
two approaches:
– Construct individual arrays, one for storing names, another for
storing prices and still another for storing number of seats.
– Use a structure variable.

©LPU CSE101 C Programming


Structure
• There are three aspects of working with
structures:
– Defining a structure type
– Declaring variables and constants of newly created
type
– Using and performing operations on the objects of
structure type

©LPU CSE101 C Programming


Structure Definition

struct sname {
type var1;
type var2;
type var3;
.
.
type varN;
};

struct is a keyword to define a structure.


sname is the name given to the structure/structure
tag.
type is a built-in data type.
var1,var2,var3,…..,varN are elements of structure
being defined.
; semicolon at the end.
©LPU CSE101 C Programming
Structure Definitions
• Example:
struct car{
char *name; int seats;
float price
};
– struct keyword introduces the definition for structure car
– car is the structure name or tag and is used to declare variables of
the structure type
– car contains three members of type char, float, int
• These members are name, price and seats.
➢No variable has been associated with this structure
➢No memory is set aside for this structure.

©LPU CSE101 C Programming


Structure Definitions
• struct information
– A structure definition does not reserve space in memory .
• Instead creates a new data type used to define structure variables
• Defining variables of structure type
– Defined like other variables:
Car myCar, cars[5], *cPtr;
– Can use a comma separated list along with structure definition:
struct car{
char
*name; int seats;
float price;
} myCar, cars[5], *cPtr;
At this point, the memory is set aside for the structure variable myCar.

©LPU CSE101 C Programming


How the members are stored in
memory
Consider the declarations to understand how the
members of the structure variables are stored in
memory
struct car{
char *name;
int seats;
float price;
}myCar,

©LPU CSE101 C Programming


How the members of the structure variables are
stored in memory
1197
1198
name 1199
1200
1201
seats 1202
1203
1204
1205
price
1206
1207
1208
1209
1210
©LPU CSE101 C Programming 1211
Structure Definitions
• Operations that can be performed on
structures
– Assigning a structure to a structure of the same
type
– Taking the address (&) of a structure
– Accessing the members of a structure
– Using the sizeof operator to determine the size
of a structure

©LPU CSE101 C Programming


Initializing Structures
• Initializer list
– To initialize a structure similarly like arrays
– Example:
car myCar = { “Renault", 500000, 2 };
– Could also define and initialize myCar as follows:
Car myCar;
myCar.name = “Renault”;
myCar.price = 500000;
myCar.seats = 2;

©LPU CSE101 C Programming


Accessing Members of Structures
• Two operators are used to access members of Structures:
– Dot operator (.) used with structure variables
car myCar;
Printf("%d", myCar.seats);
– Arrow operator (->) used with pointers to structure
variables
car *myCarPtr = &myCar;
printf("%d", myCarPtr->seats);
– myCarPtr->name is equivalent to
(*myCarPtr).seats

©LPU CSE101 C Programming


dot Operator
➢ Members are accessed using dot operator.
➢ It provides a powerful and clear way to refer to an
individual element.
• Syntax: sname.vname
• sname is structure variable name.
• vname is name of the element of the structure.
• Eg: the members of the structure variable car can be
accessed as
myCar.name, myCar.seats, myCar.price

©LPU CSE101 C Programming


Use of Assignment Statement
for Structures
• The main advantage of structure is that it can be treated
as single entity.
• The only legal operations that can be performed on
structure are copying to it as a single unit using the
assignment operator.
• Value of one structure variable can be assigned to another
variable of the same type using simple assignment
statement.
• If myCar and newCar are structure variable of type
car, then
newCar = myCar;

©LPU CSE101 C Programming


Use of Assignment Statement for
Structures
• When we assigns value of structure variable myCar to
newCar, all values of members of one structure get
copied into corresponding members of another
structure.
• Or we can copy one member at a time:
– newCar.name = myCar.name;
• Simple assignment cannot be used this way for
arrays.
• This is really a big advantage over arrays where in order
to copy one array into another of same type, we have
copied the contents element by element either using
loop or individually.

©LPU CSE101 C Programming


#include <stdio.h> Program to
struct car{
char *name;
show how to
int seats; float access
price; structure.
}; //end structure car

int main()
{
struct car myCar; //define struct variable
myCar.name = “Renault";
myCar.price = 500000;
myCar.seats = 2;
printf("%s %f %d \n”, myCar.name,
myCar.price, myCar.seats);
} //end main
Renault 500000 2

©LPU CSE101 C Programming


#include <stdio.h>
struct car{ Program to
char name[50];
int seats;
enter data into
float price; structure.
};
main()
{
struct car myCar;
printf(“Enter name of car:\n”);
gets(myCar.name);
printf(“Enter number of seats in car:\n”);
scanf(“%d”, &myCar.seats);
printf(“Enter price of car:\n”);
scanf(“%f”, &myCar.price);
printf(“\n\nParticulars of car are:\n”);
printf(“Car name:%s”,myCar.name);
printf(“\nNumber of seats:%d”,
myCar.seats);
printf(“\nPrice:%f”, myCar.price);
} //end main

©LPU CSE101 C Programming


Enter name of car: Micra
Enter number of seats in car: 4
Enter price of car: 600000

Particulars of car are:


Car name: Micra
Number of seats: 4
Price: 600000

©LPU CSE101 C Programming


Array & Structure

Array Structure
1. It is a collection of data items of same 1. It is a collection of data items of
data type. different data types.
2. It has declaration only. 2. It has declaration & definition.

3. There is no keyword. 3. struct is the keyword.

4. An array name represents the address of 4. A structure name is called tag. It is a


the starting element. short hand notation of the declaration.
5. An array cannot have bit fields. 5. It may contain bit fields.

©LPU CSE101 C Programming


typedef
• typedef
– Creates synonyms (aliases) for previously defined
data types
– Use typedef to create shorter type names
– Example:
typedef struct car CAR;
– Defines a new type name CAR as a synonym for
type struct car *
– typedef does not create a new data type
• Only creates an alias

©LPU CSE101 C Programming


typedef
• C programmers often use typedef to define a structure
type, so a structure tag is not required.
• For example, the following definition
typedef struct {
char
*name; int seats;
flaot price
}car;
creates the structure type car without the need for a
separate typedef statement.

• car myCar; /*we can create variable of


car
without using struct keyword*/
©LPU CSE101 C Programming
What is the size of a C structure.?

A) C structure is always 128 bytes.

B) Size of C structure is the total bytes of all elements of structure.

C) Size of C structure is the size of largest element.

D) None of the above


Choose a correct statement about C structure elements.?

A) Structure elements are stored on random free memory locations

B) structure elements are stored in register memory locations

C) structure elements are stored in contiguous memory locations

D) None of the above.


#include<stdio.h>
struct student{
char name[18];
int roll;
float marks;
};
int main()
{
struct student s1;

printf("%ld",sizeof(s1));
}

1. 28
2. 26
3. 18
4. compiler error
Next Class: Structure,
functions and pointers

©LPU CSE101 C Programming


cse101@lpu.co.in
CSE101-Lec#26
• Pointer to structures
• Nested Structure

©LPU CSE101 C Programming


Pointers to Structure
struct car myCar, *ptr;
It declares a structures variable myCar and a pointer variable ptr
to structure of type car.
ptr can be initialized with the following assignment statement
ptr = &myCar;
HOW WE CAN ACCESS THE ELEMENTS OF STRUCTURE?
*ptr.name,*ptr.seats,*ptr.age
But this approach will not work because dot has higher priority
Correctly way to write is:
(*ptr).name,(*ptr).seats, (*ptr).price)
or
ptr->name, ptr->seats, ptr->price
©LPU CSE101 C Programming
Accessing Members of Structures
• Arrow operator (->) used with pointers to
structure variables
car *myCarPtr = &myCar; //intializing pointer
printf("%s", myCarPtr->name);

– myCarPtr->name is equivalent to
(*myCarPtr).name

©LPU CSE101 C Programming


#include <stdio.h>
struct car{
Program for
char *name; pointer to a
int seats;
float price; structure
};
int main()
{
struct car myCar = {“Renault”,2, 500000};
struct car *myCarPtr; //define a pointer to car
myCarPtr = &myCar; /*assign address of myCar
to myCarPtr */

printf("%s %f %d \n%s %f %d \n%s %f %d\n",


myCar.name, myCar.price, myCar.seats,
myCarPtr->name, myCarPtr->price,
myCarPtr->seats,
(*myCarPtr).name, (*myCarPtr).price,
(*myCarPtr).seats);
} //end main
Renault 500000 2
Renault 500000 2
©LPU CSE101500000
Renault C Programming
2
Q1
Consider the following struct in C. Which is the correct option to change the
ranking variable to 45?
struct video {
char name[50];
int ranking;
};
int main() {
struct video cats = {"CatVid", 53};
struct video *ptr;
ptr = &cats;
return 0;
}
a) ptr.ranking = 45;
b) ranking -> ptr = 45;
c) ptr->ranking = 45;
d) ptr = 45;

©LPU CSE101 C Programming


Q2
Which of the following is an incorrect syntax for
pointer to structure? Assuming
struct temp
{
int b;
} *my_struct;

a) *my_struct.b = 10;
b) (*my_struct).b = 10;
c) my_struct->b = 10;
d) Both *my_struct.b = 10; and (*my_struct).b = 10;

©LPU CSE101 C Programming


Q3
What is the output of C program with structures pointers.?
struct forest
{
int trees;
int animals;
}F1,*F2;
int main()
{
F1.trees=1000;
F1.animals=20;
F2=&F1;
printf("%d ",F2.animals);
return 0;
}
A) 0
B) 20
C) Compiler error
D) None of the above
©LPU CSE101 C Programming
Q4
What is the output of C program with Structure pointer in C.?
int main()
{
struct books{
int pages;
char str[4];
}*ptr;
printf("%d",sizeof(ptr));
return 0;
}
A) 2
B) 6
C) 7
D) 8
©LPU CSE101 C Programming
Nested Structure
• Nested structures are structures as member of
another structure.
• We can also take objects of one structure as
member in another structure.
• Thus, a structure within a structure can be
used to create complex data application.
• Dot operator is used twice because we are
accessing first structure through the object of
second structure.

©LPU CSE101 C Programming


Nested Structure
Two ways of declaring structure within structure
or Nested structure:
• Declare two separate structures
• Embedded structures

©LPU CSE101 C Programming


Example
struct Date
{
int dd;
int mm;
int yy;
};
struct Student
{
char name[20];
int rollno;
int marks;
struct Date dob;
};
Here structure Student is nesting structure and structure date is nested structure

©LPU CSE101 C Programming


Example: embedded structures
struct Student
{
char name[20];
int rollno;
struct date
{
int dd;
int mm;
int yy;
} dob;
};

©LPU CSE101 C Programming


#include<stdio.h>
void main() WAP to read
{
struct time{ and display the
int second;
int minute; car number,
int hour;
}; starting time
struct car
{ and reaching
int carno; time using
struct time st;
}; structure within
struct car myCar; structure.
printf(“\n car no. starting time reaching
time:”);
scanf(“%d”, &myCar.carno);
scanf(“%d %d %d”, & myCar.st.hour,
&myCar.st.minute, &myCar.st.second);
printf(“\n%d”, myCar.carno);
printf(“\t %d:%d:%d \t” myCar.st.hour,
myCar.st.minute, myCar.st.second);
}

©LPU CSE101 C Programming


Q1
struct A {
int a;
float b;
};
struct B {
int c;
float d;
struct A e;
} x; What is the size of x
a) 4
b) 8
c) 16
d) 32

©LPU CSE101 C Programming


Q2
What are the types of data allowed inside a
structure.?
A) int, float, double, long double
B) char, union
C) pointers and Same structure type members
D) All the above

©LPU CSE101 C Programming


Q3
Which of the following statements correct about the
below code?
maruti.engine.bolts=25;
A: Structure bolts is nested within structure engine.
B: Structure engine is nested within structure maruti
C: Structure maruti is nested within structure engine
D: Structure maruti is nested within structure bolts.

©LPU CSE101 C Programming


CSE101-Lec#27
• Union

©LPU CSE101 C Programming


Unions
• union
– Memory that contains a variety of objects over time
– Only contains one data member at a time
– Members of a union share space
– Conserves storage
– Only the last data member defined can be accessed
• union definitions
– Same as struct
union Number {
int x;
float y;
};
union Number value;

©LPU CSE101 C Programming


Union
• Union is similar as structure. The major
distinction between them is in terms of storage.
• In structure each member has its own storage
location whereas all the members of union
uses the same location.
• The union may contain many members of
different data type but it can handle only one
member at a time union can be declared using
the keyword union.

©LPU CSE101 C Programming


Example
• A class is a very good example of structure and union in this
example students are sitting in contiguous memory
allocation as they are treated as a structure individually.
And if we are taking the place of teacher then in a class
only one teacher can teach. After leaving the first teacher
then another teacher can enter.

©LPU CSE101 C Programming


Union Declaration
union item
{
int m;
float x;
char c;
}code;

This declare a variable code of type union item

©LPU CSE101 C Programming


Memory Allocation to Union
❑ As specified in the definition of the
4 bytes size
union (in previous slide), a common
memory block is shared by all the
items of an union.

10 bytes size ❑ The size of the memory block is equal


to the largest size, among all the items
of an union.
❑ So for union A, a 4 bytes (sizeof int =
4) memory block is shared among the
its item.

❑ So for union B, a 10 bytes (sizeof char str[10] = 10) memory block is shared among
the its item.
❑ SO the above program will print 4 and 10 as the sizeof union A and B.
Initializing and accessing union members

#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}

©LPU CSE101 C Programming


#include <stdio.h>
union job{
Program using
char name[32]; union.
float salary;
int worker_no;
}u;
main()
{
printf("Enter name:\n");
scanf("%s",&u.name);
printf("Enter salary: \n");
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %.1f",u.salary);
}

©LPU CSE101 C Programming


WAP to read and display one record using union
#include<stdio.h>
union employee
{
char name[30];
int id;
float salary;
}u;
int main()
{
//union employee u;
printf("\n Enter name:");
gets(u.name);//Initialization
printf("\n Entered name is:%s",u.name);//Accessing
printf("\n Enter id:");
scanf("%d",&u.id);//Initialization
printf("\n Entered id is:%d",u.id);//Accessing
printf("\n Enter salary:");
scanf("%f",&u.salary);//Initialization
printf("\n Entered salary is:%.2f",u.salary);//Accessing
return 0;
}

©LPU CSE101 C Programming


WAP to read and display n number of records using Array of
Unions
#include<stdio.h> printf("\n Entered name
union employee is:%s",u[i].name);
{ printf("\n Enter id:");
char name[30]; fflush(stdin);
int id; scanf("%d",&u[i].id);
float salary; printf("\n Entered id
}u[100]; is:%d",u[i].id);
int main() printf("\n Enter salary:");
{ fflush(stdin);
//union employee u[100]; scanf("%f",&u[i].salary);
int n,i; printf("\n Entered salary
is:%.2f",u[i].salary);
printf("\n Enter value of n:"); }
scanf("%d",&n); return 0;
fflush(stdin); }
for(i=0;i<n;i++)
{
printf("\n Enter name:");
fflush(stdin);
gets(u[i].name);

©LPU CSE101 C Programming


Difference between structure and union

©LPU CSE101 C Programming


Similarities between structure and union
• Both are user-defined data types used to store data of different
types as a single unit.
• Their members can be objects of any type, including other
structures and unions or arrays. A member can also consist of a bit
field.
• Both structures and unions support only assignment = and sizeof
operators. The two structures or unions in the assignment must
have the same members and member types.
• A structure or a union can be passed by value to functions and
returned by value by functions. The argument must have the same
type as the function parameter. A structure or union is passed by
value just like a scalar variable as a corresponding parameter.
• ‘.’ operator is used for accessing members.

©LPU CSE101 C Programming


What is the size of the union?

©LPU CSE101 C Programming


What is the size of the union?

©LPU CSE101 C Programming


Which member of the union will active
after REF Line

©LPU CSE101 C Programming

You might also like