0% found this document useful (0 votes)
15 views

c programming all chapters notes

This document serves as an introduction to C programming, covering fundamental concepts such as computer components, algorithms, flowcharts, and the structure of C programs. It details the characteristics and benefits of computers, input and output devices, the central processing unit, and memory units. Additionally, it explains programming languages, compilers, interpreters, and provides examples of algorithms and flowcharts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

c programming all chapters notes

This document serves as an introduction to C programming, covering fundamental concepts such as computer components, algorithms, flowcharts, and the structure of C programs. It details the characteristics and benefits of computers, input and output devices, the central processing unit, and memory units. Additionally, it explains programming languages, compilers, interpreters, and provides examples of algorithms and flowcharts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 236

C PROGRAMMING

Module 1

Introduction to C Programming

Course Outcome (CO1):


Understand the basic syntax and semantics of C.
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
Introduction to Components
of a computer system

 What is Computer ?

 Characteristics of computer

 Benefits of computer

 Computer Components

 Input Devices

 Output Devices

 Central Processing Unit

 Memory Unit
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHAT IS COMPUTER ?

A computer is a programmable
electronic device that accepts raw
data as input and processes it with a
set of instructions (a program) to
produce the result as output

The father of
the computer:

Charles
Babbage engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHAT IS COMPUTER ?

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CHARACTERISTICS OF COMPUTER

Accurac Diligenc Versatil Multitas


Speed Memory
y e e king

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
BENEFITS OF COMPUTER

Increases
Productivi Storage
ty

Connects
Improves
to the
ability
Internet

Organizes Provides
data and an
informatio entertain
n ment
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
COMPUTER COMPONENTS

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
COMPUTER COMPONENTS

1. Input Devices

 Input is any data or instruction given to the computer


 Input device enables the user to send data, information, or
control signals to a computer
 The prime purpose of input devices are to translate data and
information from human-readable format into electrical
impulses
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
INPUT DEVICES

 Keyboard is a basic input device that is


used to enter data into a computer or
any other electronic device by pressing
keys

 Mouse is a pointing hand-held


input device which is used to move
cursor or pointer across the screen
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
INPUT DEVICES

 Scanner scans the picture or a


document converts it into a digital
format and is displayed on the screen
as an output

 Joystick is a pointing input device like


a mouse and movement of stick
controls the cursor or pointer on the
screen engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
INPUT DEVICES

 Light pen is like a pen. The tip of the


light pen contains a light-sensitive
detector that enables the user to point
to or select objects on the display
screen
 Microphone is used to input the sound
to presentations and with webcams for
video conferencing
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
COMPUTER COMPONENTS

2. Output Devices

 The output device displays the result of the processing of raw


data that is entered in the computer through an input device
 It is used to bring out the information from the computer

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
OUTPUT DEVICES

 Monitor is the display unit or screen of


the computer that displays the
processed data or information as text,
images, audio or video

 Printer is a device that prints text,


images or any information on paper
producing hard copy of the information

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
OUTPUT DEVICES

 A projector is an output device that


enables the user to project the output
onto a large surface such as a big screen
or wall

 Speaker is an output device connected to


a computer's sound card that outputs
sounds generated by the computer

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
COMPUTER COMPONENTS

3. Central Processing
Unit

 Brain of the computer system


 It receives instructions from both the hardware
and active software and produces output
accordingly

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CENTRAL PROCESSING UNIT (CPU)

 Control Unit is used to control the entire


working of a computer system and it controls
the transfer of data between memory and
input/output devices or I/O devices

 Arithmetic and Logic Unit is designed to


perform all the basic arithmetic
operations and logical operations
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
COMPUTER COMPONENTS

4. Memory Unit

 Memory unit is used to retain the program instruction and data for
processing

 Two types of memory:


Primary Memory
Secondary Memory engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
MEMORY UNIT
Primary Memory

 Main memory of the computer


 Directly accessed by the CPU
 Volatile
 Faster access
 Semiconductor Memory - Expensive
 Less storage capacity

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
MEMORY UNIT
Primary Memory

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
MEMORY UNIT
Primary Memory

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
MEMORY UNIT
Secondary Memory

 External Memory
 High storage capacity
 Permanent storage
 Non volatile
 Slower access
 Magnetic or optical memory - Less Expensive

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
MEMORY UNIT

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
Introduction to
Algorithm and Flowchart
 What is Algorithm ?

 Characteristics of algorithm

 How to write an algorithm ?

 Flowchart

 Flowchart Symbols

 How to draw a flowchart ?

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHAT IS ALGORITHM

An algorithm can be defined as a finite set of steps, which has to be


followed while carrying out a particular problem

An algorithm is a distinct computational procedure that takes input as


a set of values and results in the output as a set of values by solving
the problem

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CHARACTERISTICS OF ALGORITHM

Input • Well defined zero or more inputs

Output • Generate at least one output

Unambiguous • Each Instruction should be clear

• Algorithm should terminate after


Finiteness executing finite no. of instructions

• Every instruction should be fundamental


Effectiveness to be carried out, in principle
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
HOW TO WRITE AN ALGORITHM

Example: Add two numbers

Step 1: Start
Step 2: Read values num1 and num2.
Step 3: Add num1 and num2 and assign the result to
sum.
sum←num1+num2
Step4: Display sum
engineering _munotes
Step 5: Stop
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
HOW TO WRITE AN ALGORITHM
Example: Find the largest number among three
numbers
Step 1: Start
Step 2: Read variables a, b and c.
Step 3: If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 4: Stop engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
FLOWCHART

A flowchart is a visual representation of the


sequence of steps and decisions needed to
perform a process

A flowchart is a powerful business tool - With


proper design and construction, it
communicates the steps in a process very
effectively and efficiently.

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
FLOWCHART SYMBOLS

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
HOW TO DRAW A FLOWCHART
Example: Add two numbers

Step 1: Start
Step 2: Read values num1 and num2.
Step 3: Add num1 and num2 and assign the result to
sum.
sum←num1+num2
Step 5: Display sum
Step 5: Stop
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
HOW TO DRAW A FLOWCHART
Example: Find the largest number among three
numbers
Start
Input a, b,
c

No Is Yes
a>b ?
Yes Is No No Is Yes
b>c ? a>c ? Print a is
Print b is Print c is
the largest
the largest the largest
number
number number

Endengineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
Introduction to C
Programming
 What is Programming Language ?
 Types of Programming Languages
 What is Compiler ?
 What is Interpreter ?
 Compiler Vs Interpreter
 C Programming Language
 Features of C
 Applications of C
 C Program Structure
 Compilation Process
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHAT IS PROGRAMMING LANGUAGE
A programming language is a computer language that is
used by programmers (developers) to communicate with
computers

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPES OF PROGRAMMING LANGUAGES

Low Level Programming Language  Machine Dependent


 Runs without the need of compiler and
interpreter
 Example: 0 1 (Binary)

 User friendly
High Level Programming Language
 Used to develop applications, websites

Requires compiler and interpreter
 Example: Python, C, C++, Java

Middle Level Programming  Related to both high level and Machine level
Language languages
 Requires Assembler
 Example: Assembly Language
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPES OF PROGRAMMING LANGUAGES

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHAT IS COMPILER ?
A compiler is a computer program that transforms code
written in a high-level programming language into the
machine code

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHAT IS INTERPRETER ?

An interpreter is a computer program, which


coverts each high-level program statement into
the machine code.

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
COMPILER VS INTERPRETER

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
COMPILER VS INTERPRETER

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
C PROGRAMMING LANGUAGE

 C is a general-purpose, structured programming


language that is extremely popular, simple, and flexible
to use

 Developed in 1972 by Dennis Ritchie at bell laboratories


of AT&T, located in the U.S.A.

 Mother of Programming Languages - C programming is


considered as the base for other programming
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
FEATURES OF C

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
APPLICATIONS OF C

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
C PROGRAM STRUCTURE
/* C program to Print Hello World */

#include<stdio.h>

#define MAX 10

int a = 20;

int main()
{
printf(“Hello World”);
printf(“a = %d”, a);
return 0;
engineering _munotes
}
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
COMPILATION PROCESS

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
Basics of C
 Constants

 Keywords

 Identifiers

 Variables

 Types of Variables

 Data Types

 Operators

 Unary Operators

 Binary Operators

 Ternary Operators

 Operator Precedence

 Operator Associativity

 Input and Output Functions

 Format Specifiers

 engineering
Formatted I/O _munotes
Functions

PRPEARED BY: PROF. Unformatted


 SAYLEE I/O Functions
NARKHEDE ©
CONSTANTS IN C
 Constants or literals are like variables, but their values
are fixed
 Once defined, value of the constant cannot be changed

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CONSTANTS IN C
1. Numeric
Constants

Integer Constants: Sequence of digits


Rules for Constructing Integer Constants:
• Decimal Integer
 An Integer constant must have at least
Example:
12 250 -4500 0 one digit
 It can be either positive or negative
• Octal Integer
 No commas or blanks or special symbols
Example:
05 0632 are allowed
 Allowable range is -32768 to 32767
• Hexadecimal Integer
Example:
0X6A 0x79BD 0X346 engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CONSTANTS IN C
1. Numeric
Constants
Real Constants: (Floating point constants)
Numbers having fractional part Rules for Constructing Real Constants:
Example:  An real constant must have at least one
34.89 -22.1845 +0.76 digit and decimal point
 It can be either positive or negative
Exponential Representation of Real Constants: No commas or blanks or special symbols
Example: are allowed
6.78e3 -0.45E-4

Mantiss Exponen engineering _munotes


a t
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CONSTANTS IN C
2. Character
Constants
Rules for Constructing Single Character
Single Character Constants:
Constants:
Single character or Single Digit or Single
 Length of character constant can be 1
Special Symbol enclosed within single
character
inverted commas
 Character constant should be in single
inverted commas
Example:
‘A’ ‘m’ ‘8’ ‘@’

Note: 8 ≠ ‘8’ engineering _munotes


PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CONSTANTS IN C
2. Character
Constants

String Constants:
Rules for Constructing String Constants:
Sequence of characters enclosed within double
 String constants should be enclosed
quotes
within double quotes
Example:
 String constants can be of any length
“college” “m” “a8bn”
 String constant ends with a null
character assigned to it by the compiler
Note:
1. ‘a’ ≠ “a”
2. Compiler will add ‘\0’ (null character at the engineering _munotes
end of the string PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CONSTANTS IN C
2. Character
Constants

Backslash Character Constants: (Escape


Sequences)
Backslash characters have a specific meaning
which is known to the compiler

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CONSTANTS IN C
Defining Constant

Two ways to define constants

1. Using const Keyword 2. Using #define pre-processor


Syntax: Syntax:
const data_type constant_name = value; #define const_name value
Example: Example:
const int A = 10; #define PI 3.14

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
KEYWORDS IN C

Keywords are the reserved words having


specific meaning defined to the compiler

 32 Keywords in C
 Keywords cannot be used as a variable names

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
KEYWORDS IN C

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
IDENTIFIERS IN C
Identifiers represent the name in the C program; Like
names of variables, functions, arrays, structures, unions,
labels

Note:
C is a case
sensitive
language

Sum ≠ sum
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
IDENTIFIERS IN C

Rules for Constructing String Constants:


 An identifier can only have alphanumeric characters (a-z , A-Z , 0-9) (i.e. letters
& digits) and underscore( _ ) symbol.
 Identifier names must be unique
 The first character must be an alphabet or underscore.
 You cannot use a keyword as identifiers.
 Only the first thirty-one (31) characters are significant.
 It must not contain white spaces.
 Identifiers are case-sensitive.

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
VARIABLES IN C
A variable is a name given to the memory location
where data is stored depending upon the type of
the variable

Variable Declaration:
100 104
Syntax:
10 20
data_type variable_name;
n1 n2
Example:
140 200
int choice;
5 ‘a’
char ans;
n3 ch
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
VARIABLES IN C

Variable Initialization:
Variable initialization means assigning some value to that variable

Example:
int ch;
ch = 10;
OR
Variable Declaration and initialization on the same line
int ch = 10;

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPES OF VARIABLES

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPES OF VARIABLES
1. Local Variables

 A variable that is declared inside the function or block is called a local variable
 Scope: Lies within the function or block of code
 Life: Stay in the memory till the end of the program
 Example:
void fun1()
{
int lv = 20;
printf(“value = %d”, lv);
} engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPES OF VARIABLES
2. Global
Variables

 A variable that is declared outside the function or block is called a global


variable
 Value of global variable can be changed by any function
 Scope: Available to all functions
 Life: Stay in the memory till the end of the program
 Example:
int gv = 10;
void fun1()
{
int lv = 20; engineering _munotes
printf(“value of lv = %d \n value of gv= %d ”, lv, gv);
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPES OF VARIABLES
3. Static
Variables

 A variable declared with static keyword which retains its value within the
function calls is called as static variable
 Cannot be initialized again
 Scope: Local to the function or block
 Life: Value retains within the function calls
 Example:
static int a = 11;

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPES OF VARIABLES
4. Automatic
Variables

 All variables in C that are declared inside the block, are automatic variables by
default
 Explicit declaration using auto keyword
 Scope: Local to the function or block
 Life: Till the end of the block
 Example:
void fun1()
{
int a = 10; // Automatic
auto int b = 20; engineering _munotes
} PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPES OF VARIABLES
5. External Variables

 We can share a variable in multiple C source files by using an external variable


 extern keyword is used
 Scope: Global in other files too
 Life: Till the end of the program Pro1.c
Pro2.c
 Example:
#include<stdio.h>
extern int a; extern int a = 10;
#include “pro1.h”

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
DATATYPES IN C
Data types refer to the characteristics of data stored into
a variable

Data type helps you find Size, range and type of 100 104

value 10 20
C Data Types are used to: n1 n2

 Identify the type of a variable when it declared 140 200


 Identify the type of the return value of a 5 ‘a’
function n3 ch
 Identify the type of a parameter expected by a
engineering _munotes
function
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
DATATYPES IN C

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
DATATYPES IN C
Primitive Data Types

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
DATATYPES IN C
Primitive Data Types

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
DATATYPES IN C
Primitive Data Types

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
DATATYPES IN C
Primitive Data Types

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
OPERATORS IN C
 C operators are symbols that are used to perform mathematical or logical
manipulation
 The C programming language is rich with built-in operators
 Operators take part in a program for manipulating data and variables and form
a part of the mathematical or logical expressions
Mathematical Expression:

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
OPERATORS IN C
Operators are symbols or a set of symbols that change or assign values,
combine values, or check or verify values in your code

Types of Operators:
1. Unary Operator
2. Binary Operator
3. Ternary Operator

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
UNARY OPERATORS
Unary Operators are the operators which require single operand to perform any action

1. Sizeof
2. Unary minus
3. Logical NOT
4. Increment
5. Decrement
6. & (Addrss of)
7. * (Value of)

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
UNARY OPERATORS
Unary Operators are the operators which require single operand to perform any action

1. sizeof: return the size of an operand in bytes (prefix Operator)

Example: sizeof(operand)
2. unary minus: it negates a value (Prefix Operator)
Example: a = -10;
b = -a;
3. Logical NOT: The logical NOT operator inverts the value of a Boolean variable (Prefix
Operator)
engineering _munotes
Example: c = True
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
UNARY OPERATORS
Unary Operators are the operators which require single operand to perform any action

4. Increment: (Prefix and Postfix)


Increment : ++ (increases a numeric value by 1) a=a+1

a) Post Increment:

Example: a++
b) Pre Increment:

Example: ++a
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
UNARY OPERATORS
Unary Operators are the operators which require single operand to perform any action

5. Decrement: (Postfix and Prefix)


Decrement: -- (decreases a numeric value by 1) a=a‒1

a) Post Decrement:

Example: a--
a) Pre Decrement:

Example: --a
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
UNARY OPERATORS
Unary Operators are the operators which require single operand to perform any action

6. & (Address of): Returns the address of a variable (Prefix Operator)


Example: &a

7. * (Value of): Returns value stored at the address (Works with pointers)
Example: *a

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
BINARY OPERATORS
Binary Operators are the operators which require two operands to perform any action

1. Arithmetic
2. Relational
3. Logical
4. Bitwise
5. Assignment

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
BINARY OPERATORS
1. Arithmetic Operators: used to perform arithmetic/mathematical operations

Consider a = 20 and b = 10

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
BINARY OPERATORS
2. Relational Operators: used to compare two values

Consider
a=5
b = 10

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
BINARY OPERATORS
3. Logical Operators: used to test more than one condition
Consider x = 10 and y = 20

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
BINARY OPERATORS
4. Bitwise Operators: used to perform bit level operations

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
BINARY OPERATORS
5. Assignment Operators: used for assigning a value to a variable

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TERNARY OPERATOR
 The ternary operator is also called as “Conditional Operator”

 Syntax:
Condition ? expression1 : expression2
Example:
x = a > b ? a+10 : b;
 A ternary operator is a short form of if-else
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
OPERATOR PRECEDENCE
The precedence of operators determines which operator is
executed first if there is more than one operator in an
expression

Two ways to solve


= (10+20)*30

=900

=10+(20*30)

=610
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
OPERATOR PRECEDENCE
Problem:
 To generate machine level instructions that could properly evaluate arithmetic
expression
X = (a / b)* (c ‒ d)
X=a/b*c-d

X = (a / b * c) - d

Understand the meaning of an expression:


Decide the order in which the operations are to be carried out
 Fix the order of evaluation, assign each operator a priority
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
OPERATOR PRECEDENCE

Understand the meaning of an expression: (A + B) - C


 Evaluate the expression from right to left or left to right (This
A+ B - C
A + (B ‒ C)
order of evaluation, from left to right or right to left, is called
associativity)

Operators Precedence and Associativity are two characteristics of


operators that determine the evaluation order of sub-expressions in
absence of brackets

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
OPERATOR PRECEDENCE

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
OPERATOR ASSOCIATIVITY

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
PRACTICE QUESTION

What is the output of the code:


#include<stdio.h>
int main()
{
int a = 15;
printf("\n %d %d %d %d", a++, --a, a--, ++a);
// Updated
//Printed
printf("\n %d %d %d", a++, a--, --a);
return 0;
}

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
INPUT OUTPUT FUNCTIONS

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
FORMAT SPECIFIERS

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
FORMATED I/O FUNCTIONS
printf()

Syntax:
printf(“Format string”, List of variables);
Example:
printf(“\n Value of a = %d”, a);

Format string can contain:


 Characters to print
 Conversion specification (%)
 Escape Sequences (\) engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
FORMATED I/O FUNCTIONS
scanf()

Syntax:
scanf(“Format string”, List of addresses of variables);
Example:
scanf(“%d %f %c”, &a, &b, &c);

Format string can contain:


 Conversion specification (%)

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
UNFORMATED I/O FUNCTIONS
Unformatted Input
functions

getch(): getche():
getch() is used to get a character getche() is used to get a character
from the console but does not echo to from the console and echo to the
the screen screen

Library: conio.h Library: conio.h

Example: Example:
char ch; char_munotes
engineering ch;
ch = getch(); ch = getche();
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
UNFORMATED I/O FUNCTIONS
Unformatted Input
functions

getchar(): gets():
getchar() is used to get or read the gets() accepts single or multiple
input (i.e a single character) at characters of string including spaces
runtime
Library: stdio.h
Library: stdio.h
Example :
Example: char ch[10];
char ch; gets(ch);
engineering _munotes

ch = getchar(); PRPEARED BY: PROF. SAYLEE NARKHEDE ©


UNFORMATED I/O FUNCTIONS
Unformatted Output
functions

putch(): putchar():
putch displays any alphanumeric putchar() displays any alphanumeric
characters to the standard output device characters to the standard output device

Syntax: Syntax:

putch(variable_name); putchar(variable_name);

Example: Example:

char ch = 'a'; char ch = 'a';

putch(ch); putchar(ch);
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
UNFORMATED I/O FUNCTIONS
Unformatted Output
functions

puts():
puts() displays single or multiple characters of string including
spaces to the standard output device

Syntax:
puts(variable_name);

Example:
char ch[10]="Example";
puts(ch); engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
C PROGRAMMING

Module 2

Control Structures

Course Outcome (CO2):


Demonstrate the use of control structures.
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHAT IS CONTROL STRUCTURE ?

 A statement that is used to control the flow of execution in a


program is called control structure
 It combines instruction into logical unit
 Logical unit has one entry point and one exit point

There are three types of control structures


available in C:
1) Sequence structure (straight line paths)
2) Selection structure (one or many branches)
3)Loop structure (repetition of a set of activities)
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
SEQUENCE STRUCTURE

In Sequence structure instructions are executed in the order they are written following the
sequential flow

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
SELECTION STRCTURE

 Selection structures are used to perform


‘decision making‘ and then branch the
program flow based on the outcome of
decision making
 It selects a statement to execute on the
basis of condition
 Statement is executed when the condition
is true and ignored when it is false

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
LOOP STRUCTURE

 A loop structure is used to execute a


certain set of actions for a predefined
number of times or until a particular
condition is satisfied

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
Decision Control
Structures
 If statement

 If else statement

 Nested if else

 Else if ladder

 Switch Case Statement

 If else vs switch case

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
IF STATEMENT

 if statement is used to check a given condition and


perform operations depending upon the correctness
of that condition
 It is mostly used in the scenario where we need to
perform the different operations for the different
conditions

Syntax:
if(expression)
{
engineering _munotes
//code to be executed PRPEARED BY: PROF. SAYLEE NARKHEDE ©
IF STATEMENT

#include<stdio.h>
int main()
{
int n;
Example: Find whether the
printf("Enter a number:");
given number is even number scanf("%d", &n);
if(n%2 == 0)
{
printf("%d is even number“ ,n);
}
return 0;
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
IF ELSE STATEMENT


The if-else statement is used to perform two
operations for a single condition
i.e., one is for the correctness of the condition,
and the
other is for the incorrectness of the condition
 if and else block cannot be executed
simultaneously

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
IF ELSE STATEMENT
int main()
Example: Find whether the given {
number is even number or odd number int n;
printf("Enter a number:");
scanf("%d", &n);
Syntax: if(n%2 == 0)
if(expression) {
printf("%d is even
{
number“ ,n);
//code to be executed if condition is }
true else
} {
else printf("%d is odd number“ ,
n);
{
}
//code to be executed if condition is return 0;
false engineering _munotes
}
} PRPEARED BY: PROF. SAYLEE NARKHEDE ©
NESTED IF ELSE STATEMENT


When an if else statement is
present inside the body of another
“if” or “else” then this is called
nested if else

It is used when there are more
than one condition to check at a
time

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
NESTED IF ELSE STATEMENT
Syntax:
if(condition)
{
if(condition2)
{
//Statements inside the body of nested "if"
}
else
{
//Statements inside the body of nested "else"
}
}
else
{
//Statements inside the body of "else"
} engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
NESTED IF ELSE STATEMENT
Example: Find whether the person is eligible for marriage or not based on the age
and gender
#include<stdio.h> else
int main() {
{ if(age>= 18)
int age; printf("\n Eligible for marriage");
char gender; else
printf("\n Your gender ? (M/F)"); printf("\n Not eligible for Marriage");
scanf("%c", &gender); }
printf("\n Enter your age:"); return 0;
scanf("%d", &age); }
if(gender == 'M')
{
if(age >= 21)
printf("\n Eligible for marriage");
else
printf("\n Not eligible for Marriage");
}

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
ELSE IF LADDER

 The if-else-if ladder statement is an


extension to the if-else statement
 In if-else-if ladder statement, if a
condition is true then the statements
defined in the if block will be executed,
otherwise if some other condition is true
then the statements defined in the
else-if block will be executed, at the
last if none of the condition is true then
the statements defined in the else block engineering _munotes
will be executed PRPEARED BY: PROF. SAYLEE NARKHEDE ©
ELSE IF LADDER
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
else
{
//code to be executed if all the conditions
engineering are
_munotes
false
} PRPEARED BY: PROF. SAYLEE NARKHEDE ©
NESTED IF ELSE STATEMENT
Example: Find start date of vaccination based on the age of
the person
#include<stdio.h>
int main()
{
int age;
printf("\n Enter your age:");
scanf("%d", &age);
if(age >= 60)
printf("\n Vaccination will start from 1st Feb 2021");
else if(age >= 45)
printf("\n Vaccination will start from 1st March 2021 ");
else if(age >= 18)
printf("\n Vaccination will start from 1st May 2021 ");
else
printf("\n Not eligible for Vaccination");
return 0; engineering _munotes
}
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
SWITCH CASE STATEMENT
Syntax:
 The switch statement in C is an alternate to if- switch (expression)
else-if ladder statement which allows us to {
execute multiple operations for the different case constant1:
possible values of a single variable called switch // statements
variable break;

 Switch statement in C tests the value of a case constant2:


variable and compares it with multiple cases // statements
break;
 .
Once the case match is found, a block of
statements associated with that particular case .
is executed .
default:
 // default statements
If a case match is NOT found, then the default
statement is executed, and the control goesengineering
out }
_munotes
of the switch block PRPEARED BY: PROF. SAYLEE NARKHEDE ©
SWITCH CASE STATEMENT
Rules for Switch Statement:
 The switch expression must be of an integer or
character type
 The case value must be an integer or character
constant

The case value can be used only inside the switch
statement

The break statement in switch case is not must.
 If there is no break statement found in the case, all
the cases will be executed present after the matched
case (fall through the state of C switch statement)
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
SWITCH CASE STATEMENT
Example: Write a C Program to perform addition, subtraction, multiplication, division and modulus operations
using switch case.
#include<stdio.h> case 3:
#include<stdlib.h> printf("\n multiplication = %d", n1*n2);
int main() break;
{ case 4:
int ch, n1, n2; printf("\n division = %d", n1/n2); break;
printf("\n MENU \n 1. addition \n 2. subtraction") case 5:
; printf("\n remainder = %d", n1%n2);
printf(" \n 3. multiplication \n 4. division"); break;
printf(" \n 5. modulus \n 6. exit \n Enter you case 6:
choice:"); exit(0);
scanf("%d", &ch); default:
printf("\n Enter two numbers:"); printf("\n You have entered wrong choice!!");
scanf("%d %d", &n1, &n2); break;
switch(ch) }
{ return 0;
case 1: }
printf("\n addition = %d", n1+n2);
break;
case 2: engineering _munotes
printf("\n subtraction = %d", n1-n2);
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
break;
IF ELSE VS SWITCH CASE

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
Loop Control Structures

 Looping structure

 for loop

 do while loop

 while loop

 break statement

 continue statement

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
LOOPING STRUCTURE

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
FOR LOOP

For loop specifies the three things:


 Setting a loop counter to an initial value
 Testing a loop counter to determine whether its value has reached the number of
repetitions required
 Increasing the value of loop counter each time the program within the loop has been
Syntax:
executed
for(initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
} engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
FOR LOOP

Flowchart of For loop

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
FOR LOOP

Example: Print 1 to 10 numbers using for


loop

#include<stdio.h>
int main()
{
int i;
for(i=1; i<=10; i++)
printf(“%d”, i);
return 0;
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHILE LOOP

 While loop is also known as a pre-tested loop


 It can be viewed as a repeating if statement
 The while loop is mostly used in the case where the number of iterations is not known in
advance
Syntax:
initialization expression;
while (test_expression)
{
// statements

update_expression;
} engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHILE LOOP

Flowchart of while
loop

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHILE LOOP

Example: Print 1 to 10 numbers using while


loop

#include<stdio.h>
int main()
{
int i = 1;
while(i <= 10)
{
printf(“%d”, i);
i++;
}
return 0;
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
DO WHILE LOOP
 A do...while loop is similar to the while loop except that the condition is always executed
after the body of a loop so it is an exit-controlled loop
 The do-while loop is mainly used in the case where we need to execute the loop at least
once
 The do-while loop is mostly used in menu-driven programs where the termination
condition depends upon the end user
Syntax:
initialization expression;
do
{
// statements

update_expression;
} while (test_expression);
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
DO WHILE LOOP

Flowchart of do-while
loop

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHILE LOOP

Example: Print 1 to 10 numbers using do - while


loop

#include<stdio.h>
int main()
{
int i = 1;
do
{
printf(“%d”, i);
i++;
} while(i <= 10);
return 0;
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
BREAK STATEMENT

 The break is a keyword in C which is used to bring the program control out of
the loop
 The break statement is used inside loops or switch statement and it is
associated with if

Syntax:
//loop or switch case
break;

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
BREAK STATEMENT
Example: Find sum of any 5 numbers entered only between 1
to 10
#include<stdio.h>
int main()
{
int n, count = 0, sum=0;
printf(“\n Get sum of any 5 numbers between 1 to 10”);
do
{
printf(“\n Enter a number only between 1 to 10”);
scanf(“%d”, &n);
if(n < 1 && n > 10)
break;
sum = sum + n;
count++;
}while(count <= 5);
return 0;
engineering _munotes
}
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CONTINUE STATEMENT

 The continue statement skips the current iteration of the loop and continues with the
next iteration
 When the continue statement is executed in the loop, the code inside the loop following
the continue statement will be skipped and next iteration of the loop will begin.

Syntax:
//loop or switch case
continue;

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CONTINUE STATEMENT

Example: Print 1 to 10 numbers except 4 using for


loop

#include<stdio.h>
int main()
{
int i;
for(i=1; i<=10; i++)
{
if(i == 4)
continue;
printf(“%d”, i);
}
return 0;
} engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
C PROGRAMMING

Module 3

Functions

Course Outcome (CO3):


Decompose a problem into functions and synthesize a
complete program.
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
Functions
❖ What is Function ?
❖ Advantages of Functions
❖ Types of functions
❖ How function works ?
❖ Parameter Passing
❖ Return Statement
❖ Call by Value
❖ Call by Reference
❖ Recursive function
❖ How recursion works ?
❖ How to write recursive function ?
❖ Recursive Function Call
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
WHAT IS FUNCTION ?

❖ A function is a block of code that performs a specific task


❖ Functions are building blocks of any programming language
❖ It is a reusable block of code that makes a program easier to understand, test and can be easily
modified without changing the calling program

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
ADVANTAGES OF FUNCTIONS

❖ It provides modularity to your program's structure


❖ It makes your code reusable. You just have to call the function by its name to use it,
wherever required
❖ In case of large programs with thousands of code lines, debugging and editing becomes
easier if you use functions
❖ It makes the program more readable and easy to understand

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPES OF FUNCTIONS

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPES OF FUNCTIONS

Library functions
❖ Library functions are those functions which are already defined in C library
❖ Example: printf(), scanf(), strcat() etc.
❖ You just need to include appropriate header files to use these functions

User-defined functions:
❖ User Defined Functions are those functions which are defined by the user at the time of writing
program
❖ These functions are made for code reusability and for saving time and space

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
HOW FUNCTION WORKS
return_type function_name (argument list)
{
function body;
return_type function_name (argument list); }

Function Function
Declaration Definition

Function Call

function_name (argument list);


engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
HOW FUNCTION WORKS

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
HOW FUNCTION WORKS

Function declaration: (Function Prototype)


❖ A function must be declared globally to tell the compiler about the function name, function
parameters, and return type
Function call:
❖ Function can be called from anywhere in the program
❖ The parameter list must not differ in function calling and function declaration
Function definition:
❖ It contains the actual statements which are to be executed
❖ The program control comes to function definition when the function is called
❖ Only one value can be returned from the function

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
HOW FUNCTION WORKS

void add(); // Function Declaration


int main()
{
add(); // Function Call
Example: Write a C Program return 0;
to perform addition of two }
numbers using function.
void add() // Function Definition
{
int n1,n2;
printf("\n Enter two numbers:");
scanf("%d %d", &n1, &n2);
printf("\n Addition of %d and %d = %d", n1, n2, n1+n2);
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
PARAMETER (ARGUMENT) PASSING

❖ The mechanism used to convey information to the


function is the argument
❖ A function's arguments are used to receive the
necessary values by the function call

Actual arguments:
The values that are passed to the called function from the
main function are known as Actual arguments
Formal arguments:
The variables declared in the function prototype or
definition are known as Formal arguments
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
PARAMETER (ARGUMENT) PASSING
void add(int a, int b); // Function Declaration
int main()
Formal
{ Arguments
int n1,n2;
Example: Write a C Program printf("\n Enter two numbers:");
to perform addition of two scanf("%d %d", &n1, &n2);
numbers using function.
add(n1, n2); // Function Call
return 0; Actual
} Arguments
void add(int n1, int n2) // Function Definition
{
Formal
printf("\n Addition of %d and %d = %d", a, b, a+b);
Arguments
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
RETURN STATEMENT

❖ The return statement is used to terminate the


execution of a function and transfer program
control back to the calling function
❖ A function may contain one or more return
statements
❖ A function can return only one value at a time
❖ Return type of a function and return value data
type should be same

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
PARAMETER (ARGUMENT) PASSING

Parameter passing can be done in two ways: (Types of function calls)


1. Call by value
2. Call by reference

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CALL BY VALUE

❖ The value of the actual parameters is copied into the formal parameters
❖ The arguments in the function call (Actual arguments) are not modified by the change
in parameters of the called function (Formal arguments)
❖ Different memory is allocated for actual and formal parameters

a b a b
Actual Argument 10 20 10 20 Formal Argument

100 150 200 250

Local to main Local to function


engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CALL BY VALUE

Example: Write a C Program to swap two numbers

void swap(int , int); void swap(int a, int b)


int main() {
{ int temp;
int a = 10; temp = a;
int b = 20; a = b;
printf(“\n Before swapping the values in main”); b = temp;
printf(“ a = %d, b = %d ",a, b); printf(“\n After swapping values in function”);
swap(a, b); printf(“a = %d, b = %d“, a, b);
printf(“\n After swapping values in main); }
printf(“a = %d, b = %d ",a, b);
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CALL BY REFERENCE

❖ The address of the variable is passed into the function call as the actual parameter
❖ The value of the actual parameters can be modified by changing the formal parameters since
the address of the actual parameters is passed
❖ Same memory is allocated for both formal parameters and actual parameters

a a
Actual Argument 10 100 Formal Argument

100 200
Normal Variable Pointer that stores the address
of actual argument
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
CALL BY REFERENCE

Example: Write a C Program to swap two numbers

void swap(int *, int *); void swap(int *a, int *b)


int main() {
{ int temp;
int a = 10; temp = *a;
int b = 20; *a = *b;
printf(“\n Before swapping the values in main”); *b = temp;
printf(“ a = %d, b = %d ",a, b); printf(“\n After swapping values in function”);
swap(&a, &b); printf(“a = %d, b = %d“, *a, *b);
printf(“\n After swapping values in main); }
printf(“a = %d, b = %d ",a, b);
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
RECURSIVE FUNCTION

❖ Recursion is the process of defining a problem or solution of the problem in terms of itself
❖ Recursion is the process in which function calls itself directly or indirectly
❖ Recursive Function:
A function which calls itself is called as a recursive function

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
HOW RECURSION WORKS

int sum(int n)
{
if(n = = 1)
return 1; n=1 sum(1) return 1
else
return n + sum(n-1);
n=2 sum(2) return 3
}
n=3 sum(3) return 6
int main()
{ n=4 sum(4) return 10
int n = 4, result;
result = sum(n); n=4 main() result = 10
printf(“%d”, result);
return 0; Stack
}

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
HOW TO WRITE RECURSIVE FUNCTION

Divide the problem into smaller subproblems


Solve one part of the problem or reduce the size of the problem

Steps to design recursive algorithm: void fun()


1. Determine the base case to stop the recursion {
if( )
2. Determine the general case { Base Case
3. Combine the base case and the general cases into the algorithm …..
}
else
{ General Case
…… (Recursive
Procedure)
}
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
HOW TO WRITE RECURSIVE FUNCTION
Calculate Factorial of 5 int Fact() int Fact()
int Fact()
{ { {
if( n =if(=)1) if( )
Fact(1) = 1
{ { { Base Case
Fact(2) = 2 * 1 = 2 * Fact(1) 1; …..
return…..
} } }
Fact(3) = 3 * 2 * 1 = 3 * Fact(2) else else else
{ { { General Case
Fact(4) = 4 * 3 * 2 * 1 = 4 * Fact(3) ……
returnn n* *Fact(n-1)
Fact(n-1); (Recursive
} } Procedure)
Fact(5) = 5 * 4 * 3 * 2 * 1 = 5 * Fact(4) } } }
}

Fact(n) = n * Fact(n-1)

Base Case is the case that solves the problem and helps to stop recursion
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
RECURSIVE FUNCTION CALL

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
MODULE 4

ARRAYS AND STRINGS

engineering _munotes
WHAT IS AN ARRAY ?

An array is a collection of similar type of data.

 Array is a variable that can store multiple

values

 Derived data type

 Stores primitive type of data like int, float,

char
engineering _munotes
 Data is stored in a contiguous memory
ARRAY BASICS
 Need of an array
 What is an array ?
 Array Declaration
 Array elements in memory
 Accessing Array elements
 Array Initialization
 Entering Data into array
 Accessing data from array engineering _munotes
ARRAY DECLARATION
 Arrays are declared like a variable.

 Array declaration tells compiler which type of array it is and what is the

size of an array.

Syntax:

data_type array_name[array_size];

Example:

int arr[10]; One Dimensional Array engineering _munotes


ARRAY ELEMENTS IN MEMORY

engineering _munotes
ACCESSING ARRAY ELEMENTS

Array elements are accessed using indices

Array index always starts from 0

engineering _munotes
ARRAY INITIALIZATION
Initialization of an array at the time of declaration:

int arr[5] = {1,2,3,4,5};

int arr[ ] = {1,2,3,4,5};

Initialization of each element in an array using index:

arr[0] = 1;

arr[1] = 2;

arr[2] = 3;

arr[3] = 4;

arr[4] = 5; engineering _munotes


ENTERING DATA INTO ARRAY

11 21 33 40 05

engineering _munotes
ACCESSING DATA FROM ARRAY

engineering _munotes
ACCESSING DATA FROM ARRAY

Iteration 1 Iteration Iteration


i=0 3 5
i=2 i=4
0 1 2 3 4

11 21 33 40 5

200 204 208 212 216

Iteration Iteration
2 4
i=1 i=3
engineering _munotes
EXAMPLE

int main(){
int a[20];
printf("\n Printing values in array");
int i, n; for(i=0; i<n; i++)
printf("\n How many elements you want {
to enter? ");
printf("\n a[%d] = %d ", i, a[i]);
scanf("%d", &n);
printf("\address of a[%d] = %u", i, &a[i]);
printf("\n Enter values in an array"); }
for(i=0; i<n; i++) return 0;
{ printf("\n Enter value at a[%d] = " }
,i); scanf("%d", &a[i]);
engineering _munotes
}
PASSING ARRAY ELEMENTS TO A FUNCTION

Passing arrays elements to the function can be done in two ways:

Call by value (Passing element of an array to the function)

Call by reference (Passing addresses of elements of an array to the


function)

engineering _munotes
PASSING ARRAY ELEMENTS TO A FUNCTION Call by value

#include<stdio.h>

void display(int); // Function Declaration return 0;


}
int main()
\\ Function Definition
{
void display(int x)
int a[5] = {11,12,13,14,15};
{
int i;
printf("%d ",x);
printf("\nDisplaying array elements\n");
}
for(i=0; i<5; i++)

display(a[i]); // function call by value engineering _munotes


Call by reference (Passing addresses of elements of an array to the
function)

#include<stdio.h> display(&a[i]); // function call by reference

void display(int *); // Function Declaration return 0;

int main() }

{ \\ Function Definition

int a[5] = {11,12,13,14,15}; void display(int *x)

int i; {

printf("\nDisplaying array elements\n"); printf("%d ",*x);

for(i=0; i<5; i++) }


engineering _munotes
PASSING AN ENTIRE ARRAY TO A FUNCTION
#include<stdio.h>
\\ Function Definition
void display(int [], int); // Function void display(int x[5], int n)
Declaration {

int main(){ int i;


for(i=0; i<n; i++)
int a[5] = {11,12,13,14,15};
{
printf("\nDisplaying array elements\n"); printf("%d “, x[i]);
display(a, 5); // display(200,5); }
}
return 0;
engineering _munotes
}
2 DIMENSIONAL ARRAYS

 2-dimensional array

 2-D array declaration


 2-D array initialization
 2-D array elements in memory
 Entering data into 2-D array
 Reading data from 2-D array

engineering _munotes
2- DIMENSIONAL ARRAY


2-dimensional array is called as a matrix with rows and columns

 Each element in 2-d array is represented with row and column number

 2-dimensional array is a collection of several 1-dimensional arrays

engineering _munotes
2- DIMENSIONAL ARRAY

0 1 2 3

0 11 33 45 23

1 70 15 55 66

2 9 63 12 50

engineering _munotes
2 – D ARRAY DECLARATION

Syntax:

data_type array_name[rows][columns];
0 1 2 3
Example: a[0][0] a[0][1] a[0][2] a[0][3]
0
int a[3][4]; a[1][0] a[1][1] a[1][2] a[1][3]
1
// a is a 2-dimensional array with 3 rows and
a[2][0] a[2][1] a[2][2] a[2][3]
4 columns 2

engineering _munotes
2 – D ARRAY INITIALIZATION

int a[3][4] = {11,12,13,14,21,22,23,24,31,32,33,34};


Or
int a[3][4] = {

{11,12,13,14},

{21,22,23,24},

{31,32,33,34}

};
engineering _munotes
2 – D ARRAY INITIALIZATION

engineering _munotes
2 – D ARRAY DECLARATION

Valid Declarations:

 int a[3][4];

 int a[][4];

Invalid Declarations:

 int a[][];

 int a[3][];

engineering _munotes
ENTERING DATA INTO 2-D ARRAY

engineering _munotes
READING DATA FROM 2-D ARRAY

engineering _munotes
MATRIX OPERATIONS

Different Matrix operations:

 Matrix Addition

 Matrix Subtraction

 Matrix Multiplication

 Matrix Transpose

engineering _munotes
MATRIX ADDITION

 A matrix can only be added to (or subtracted from) another matrix if the two matrices have the
same dimensions

 To add two matrices, just add the corresponding entries, and place this sum in the corresponding
position in the matrix which results

engineering _munotes
MATRIX MULTIPLICATION

 You can only multiply two matrices if their dimensions are compatible , which means the
number of columns in the first matrix is the same as the number of rows in the second matrix

 In matrix multiplication first matrix one row element is multiplied by second matrix all column
elements

 Add the products

engineering _munotes
MATRIX MULTIPLICATION

a[2][2] b[2][3] c[2][3]

0 1 2 0 1 2

0 1 2 3 0 24 33 42

1 4 5 6 1 9 12 15

1*3
1*2 +++2*4
4*3
1*1
4*1
4*2 2*6
2*5
5*4
5*5 15
5*6 ==== 9
12
42
24
33
engineering _munotes
MATRIX TRANSPOSE
Transpose of a matrix is obtained by changing rows to columns and columns
to rows

 Transpose of A[i][j] is the matrix A[j][i]


a[3][2]
a[2][3]

0 1
0 1 2
0 1 4
0 1 2 3
1 2 5
1 4 5 6 engineering _munotes
2 3 6
ARRAY OF POINTERS

A pointer variable always contains an address, an array of pointers


would be nothing but a collection of addresses.
The addresses present in the array of pointers can be addresses of
isolated variables or addresses of array elements or any other
addresses. All rules that apply to an ordinary array apply to the array
of pointers as well.

engineering _munotes
EXAMPLE

# include<stdio.h>
int main( ) {
int *arr[ 4 ] ; /* array of integer
for ( m = 0 ; m <= 3 ; m++ )
pointers */
printf ( "%d\n", * ( arr[ m ] ) ) ;
int i = 31, j = 5, k = 19, l = 71, m ;
return 0 ;
arr[ 0 ] = &i ;
}
arr[ 1 ] = &j ;
arr[ 2 ] = &k ;
arr[ 3 ] = &l ;
engineering _munotes
STRINGS

 What is string ?
 Sting Declaration
 String Initialization
 Accepting String from user
 String functions

engineering _munotes
WHAT IS STRING ?

String is a collection of characters terminated by ‘\0’ (Null character)


 String is a one dimensional array of characters terminated by null character ‘\0’

 Each element in character array takes one byte of memory

Null character ‘\0’:

 Used to indicate termination of string

 ASCII value of ‘\0’ is 0

engineering _munotes
STRING DECLARATION

 String can be declared as an array of characters

Syntax:

char string_name[size];

Example:

char s[5];

engineering _munotes
, b = 20

STRING INITIALIZATION
Two ways:

1. By Character array

2. By String literal

1. By character array:

‘\0’ to be added explicitly

char str[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

2. By string literal:

‘\0’ is added by the compiler implicitly


engineering _munotes
char str[6] = “Hello”;
STRING INITIALIZATION

Note: (Not acceptable assignment to string variable)

char str[20]; // string declaration

str = “helloworld”; // assigning value to string variable

// error: assignment to expression with array type

engineering _munotes
ACCEPTING STRING FROM USER
int main(){
#include <stdio.h>
char name[20];
int main(){
printf("Enter name: ");
char name[20];
scanf("%[^\n]s", name);
printf("Enter name: ");
printf("Your name is %s", name);
scanf("%s", name);
return 0; }
printf("Your name is %s", name);
Here, [^\n] indicates that scanf( ) will keep
return 0; } receiving characters into name[ ] until \n is
engineering _munotes
encountered.
ACCEPTING STRING FROM USER

# include<stdio.h>
scanf( ) is not capable of receiving
int main( ) {
multi-word strings. Therefore,
names such as ‘Debashish Roy’ char name[ 25 ] ;
would be unacceptable. The way to printf ( "Enter your full name: " ) ;
get around this limitation is by
using the function gets( ). The gets ( name ) ;
usage of functions gets( ) and its puts ( "Hello!" ) ;
counterpart puts( ) is shown below.
puts ( name ) ;
return 0 ;
engineering _munotes
}
PRINTING A STRING
# include<stdio.h>
int main( ) {
char name[ ] = “engineering" ;
int i = 0 ;
while ( i <= 10)
{
printf ( "%c", name[ i ] ) ;
i++ ;
}
printf ( "\n" ) ;
return 0 ; engineering _munotes
}
PRINTING A STRING

# include <stdio.h>
int main( )
{
printf ( "\n" ) ;
char name[ ] = "Klinsman" ;
return 0 ;
int i = 0 ;
}
while ( name[ i ] != '\0' )
{
printf ( "%c", name[ i ] ) ;
i++ ;
}
engineering _munotes
PRINTING A STRING
# include <stdio.h>
int main( )
{
char name[ ] = "Klinsman" ; printf ( "\n" ) ;
char *ptr ; return 0 ;
ptr = name ; /* store base address of string }
*/
while ( *ptr != '\0' )
{
printf ( "%c", *ptr ) ;
ptr++ ; engineering _munotes

}
STRING FUNCTIONS
String library functions:

o/p:
 String Library functions are
Before swapping the values in main a=10,b=20
available in string.h header
After swapping values in function a=20,b=10 file
After swapping values in main a =20,b=10
 To use string library
functions in a program you
need to include string.h
header file

engineering _munotes #include<string.h>


STRING FUNCTIONS : strlen()

#include <stdio.h>

Counts the number of characters present #include<string.h>


in the string
int main(){
Syntax:
char s[20] = “college”;
strlen(str);
int len;

len = strlen(s);

printf(“Length of string s = %d”, len);


engineering _munotes
return 0;}
FIND LENGTH OF A STRING WITHOUT USING STRLEN() FUNCTION

#include <stdio.h>

int main(){

char s[20] = "college";

int i = 0;

while(s[i] != '\0')

i++;

printf("Length of string s = %d", i);


engineering _munotes
return 0; }
strcpy()
#include<string.h>
Copies the content of one string into
int main(){
another
char s[20] = "college";

char d[20];
Syntax:
strcpy(d, s);
strcpy(destination, source);
printf("Source string s = %s", s);

printf("Destination string d = %s", d);


engineering _munotes
return 0;}
COPY THE CONTENT OF ONE STRING INTO ANOTHER STRING
WITHOUT USING strcpy() FUNCTION

#include <stdio.h>
int main(){
char s[20] = “college”;
printf(“Source string s = %s”, s);
char d[20];
printf(“Destination string d = %s”, d);
int i = 0;
return 0;
while(s[i] != ‘\0’)
}
{
d[i] = s[i];
i++;
} engineering _munotes
strcmp()
Compares two strings to check #include<string.h>
whether they are same or different int main(){
 If the two strings are equal it char s[20] = “college”;
returns 0
if(strcmp(s, “college”) == 0)
 Else it returns ASCII value
printf(“Strings are equal);
difference
else
Syntax:
printf(“Strings are different”);
strcmp(string1, string2);
return
engineering 0;}
_munotes
COMPARE TWO STRINGS WITHOUT USING strcmp() FUNCTION

else{
int main(){ cmp = 1;
char s[20] = “college”; break; }
char d[20] = “terna”; }
int i = 0; if(cmp == 0)
while(s[i] != ‘\0’ || d[i] != ‘\0’)
printf(“Strings are equal);
{
if(d[i] == s[i] { else
cmp = 0; printf(“Strings are different”);
i++;}
return 0;
engineering _munotes
}
strcat()

#include<string.h>
Concatenates two strings
int main(){
i.e. concatenate source string at the end
char s[20] = "college";
of destination string
char d[20] = "terna ";
Syntax:
strcat(d, s);
strcat(destination, source);
printf("Source string s = %s", s);

printf("Destination string d = %s", d);

return 0;
engineering _munotes
}
CONCATENATE TWO STRINGS WITHOUT USING strcat() FUNCTION

int main(){
char s[20] = “college”;
char d[20] = “terna”;
int i = 0, j = 0; printf(“Source string s = %s”, s);

while(d[i] != ‘\0’) printf(“Destination string d = %s”, d);

i++; return 0;

while(s[j] != ‘\0’) { }

d[i] = s[j];
i++;
j++; engineering _munotes
}
strlwr and strupr
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <string.h>

int main()
int main()
{
{
char string[] = "strupr in c";
char string[] = "Strlwr in C";
printf("%s\n",strupr(string));
printf("%s\n",strlwr(string));
return 0;
return 0;
}
engineering _munotes
}
C PROGRAMMING

Module 5

Structure and Union

Course Outcome (CO5):


Demonstrate the use of structure and union in C language

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
Structure
 Introduction of structure

 Structure Declaration

 Structure Variable

 Structure Variable Initialization

 Structure elements in memory

 Structure Example

 Typedef

 Array of structures

 Nested Structure

 Passing Structure to function

 Assigning value of one structure to another


engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
INTRODUCTION OF
STRUCTURE
Array is used to store several elements of same type
eg. Roll no. of students can be stored in an array of type int
int roll_no[60];

Problem Statement:
Store students information like roll no., name, department, college, marks
Roll No. – int
Name – char[10]
Department – char[5]
Marks – float

There are two approaches:


1. Construct individual arrays, one for roll no, one for name, one for class…..
2. Use a structure
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
STRUCTURE DECLARATION
Structure is a user defined data type that can hold different types of data together in a single
type

Defining a structure:

Each element in a structure is called as member


struct structure_name struct student
{ {
structure element 1; int roll_no;
structure element 2; char student_name[10];
structure element 3; char dept[10];
. float marks;
. };
.
};

Syntax Example
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
STRUCTURE VARIABLE

Structure is user defined data type, variables of that type can be declared

Different ways to declare variables are -

struct student struct student struct student


{ { {
int roll_no; int roll_no; int roll_no;
char student_name[10]; char student_name[10]; char student_name[10];
char dept[5]; char dept[5]; char dept[5];
float marks; float marks; float marks;
}s1, s2, *s3; }; };
struct student s1; struct student s1, s2;
struct student s2;

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
STRUCTURE VARIABLE INITIALIZATION

struct student Structure elements can be accessed using


{
dot operator
int roll_no;
char student_name[10];
char dept[5];
Syntax:
float marks;
}; structureVariable.structureElement
struct student s1={10, ”Neha”, “IT” 90.50};
Example:
struct student s2={12, “Ram”, “Comp”, 85.00};
struct student s3 = {0}; s1.roll_no
s1.dept

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
STRUCTURE ELEMENTS IN
MEMORY
struct student
{
int roll_no;
char student_name[10];
char dept[5];
float marks;
};
struct student s1={10, ”Neha”, “IT”, 90.50};

s1.roll_no s1.student_name s1.dept s1.marks

100 104 114 119 123

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
STRUCTURE EXAMPLE
Problem statement: Define structure student with members roll_no, student_name,
dept, marks and accept student record from user and display student record.
struct student
{
int roll_no;
char student_name[10];
char dept[5];
float marks;
};
struct student s1={10, ”Neha”, “IT”, 90.50};

int main()
{
struct student s2;
printf(“\n Enter s2 information:”);
scanf(“%d %s %s %f”, &s2.roll_no, s2.student_name, s2.dept, &s2.marks);
printf(“\n Displaying s1 record: %d %s %s %.2f”, s1.roll_no, s1.student_name, s1.dept,s1.marks);
printf(“\n Displaying s2 record: %d %s %s %.2f”, s2.roll_no, s2.student_name, s2.dept,s2.marks);
return 0;
} engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPEDEF
typedef is a keyword used to assign alternative names to existing datatypes

It is mostly used with user defined data types, when names of the data types become complicated to use in programs

Syntax: typedef existing_datatype new_datatype

struct student typedef struct student Old Data type


{ {
int roll_no; int roll_no;
char student_name[10]; char student_name[10];
char dept[10]; char dept[10];
float marks; float marks;
}; }stud; New Data type
struct student s1={10, ”Neha”, “IT”, 90.50}; stud s1={10, ”Neha”, “IT”, 90.50};
struct student s2={12, “Ram”, “Comp”, 85.00}; stud s2={12, “Ram”, “Comp”, 85.00};

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
TYPEDEF
Problem statement: Define structure student with members roll_no, student_name,
dept, marks and accept student record from user and display student record.
typedef struct student
{
int roll_no;
char student_name[10];
char dept[5];
float marks;
}stud;
stud s1={10, ”Neha”, “IT”, 90.50};

int main()
{
stud s2;
printf(“\n Enter s2 information:”);
scanf(“%d %s %s %f”, &s2.roll_no, s2.student_name, s2.dept, &s2.marks);
printf(“\n Displaying s1 record: %d %s %s %.2f”, s1.roll_no, s1.student_name, s1.dept,s1.marks);
printf(“\n Displaying s2 record: %d %s %s %.2f”, s2.roll_no, s2.student_name, s2.dept,s2.marks);
return 0;
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
ARRAY OF
STRUCTURES
Problem Statement: Store information of 60 students and print it.
Solution: Use Array of Structure

struct student typedef struct student


{ {
int roll_no; int roll_no;
char student_name[10]; char student_name[10];
char dept[10]; char dept[10];
float marks; float marks;
}; }stud s[60];
struct student s1={10, ”Neha”, “IT”, 90.50};
struct student s2={12, “Ram”, “Comp”, 85.00};
…….

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
ARRAY OF
STRUCTURES

S[0].roll_no S[0].student_name S[0].dept S[0].marks

S[1].roll_no S[1].student_name S[1].dept S[1].marks

S[2].roll_no S[2].student_name S[2].dept S[2].marks

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
ARRAY OF
STRUCTURES
typedef struct student
{
int roll_no;
char student_name[10];
char dept[5];
float marks;
}stud;
stud s[5];

int main()
{
int i;
printf(“\n Enter Student information:”);
for(i=0; i<5; i++)
{
printf(“\n Enter values of s[%d] record: ”, i+1);
scanf(“%d %s %s %f”, &s[i].roll_no, s[i].student_name, s[i].dept, &s[i].marks);
printf(“\n Displaying s[%d] record: %d %s %s %.2f”, i+1, s[i].roll_no, s[i].student_name, s[i].dept, s[i].marks);
}
return 0;
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
NESTED STRUCTURES
struct address
{
char city[10];
int pin;
};

struct address add;

struct student
{
int roll_no;
char student_name[10];
char dept[10];
float marks;
struct address add;
};
struct student s1 = {10, “Neha”, “IT”, 90.50, “Mumbai”, 400011};

Print student s1 record:


printf(“Roll no = %d Name= %s Dept = %s Marks = %.2f City = %s Pin = %d ”, s1.roll_no, s1.student_name, s1.dept, s1.marks,
s1.add.city, s1.add.pin); engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
NESTED STRUCTURES
struct address
{
char city[10];
int pin;
};
struct address add;

struct student
{
int roll_no;
char student_name[10];
char dept[10];
float marks;
struct address add;
};
struct student s1 = {10, “Neha”, “IT”, 90.50, “Mumbai”, 400011}

int main()
{
printf(“\n Displaying s1 record: ”);
printf(“\n %d %s %s %f %s %d”, s1.roll_no, s1.student_name, s1.dept, s1.marks, s1.add.city, s1.add.pin);
return 0;
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
PASSING STRUCTURE TO
FUNCTION

Two ways to pass structure to a function


 Passing individual structure members to a function

 Passing an entire structure to a function

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
PASSING INDIVIDUAL MEMBER TO A
FUNCTION
#include<stdio.h> int main()
typedef struct student {
{ stud s1 = {11, “Mohit”, 98.7};
int rollno; printf("\nDisplay student information\n");
char name[20]; display(s1.rollno, s1.name, s1.marks); return 0;
float marks; }
}stud; void display(int r, char n[20], float m)
{
printf("%d %s %f ",r, n, m);
}

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
PASSING ENTIRE STRUCTURE TO A
FUNCTION
#include<stdio.h> int main()
typedef struct student {
{ stud s1 = {11, “Mohit”, 98.7};
int rollno; printf("\nDisplay student information\n");
char name[20]; display(s1);
float marks; return 0;
}stud; }
void display(stud s)
{
printf("%d %s %f ",s.rollno, s.name, s.marks);
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
PASSING ENTIRE STRUCTURE TO A
FUNCTION
Structure and Pointer

 Structure members can be accessed using arrow


typedef struct student
operator (->) when they are accessed by pointer
{
int rollno;
char name[20];
float marks;
}stud s1;

stud *ptr = &s1;

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
PASSING ENTIRE STRUCTURE TO A
FUNCTION
Structure and Pointer

int main()
#include<stdio.h>
{
typedef struct student
stud s1 = {11, “Mohit”, 98.7};
{ printf("\nDisplay student information\n");
int rollno; display(&s1);
char name[20]; return 0;
}
float marks;
void display(stud *ptr)
}stud;
{
printf("%d %s %f ",ptr->rollno, ptr->name, ptr->marks);
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
ASSIGNING VALUE OF ONE STRUCTURE TO
ANOTHER

typedef struct student  Assigning all elements at a time:


{ s2 = s1;
int rollno;
char name[20];  Assigning one elements value at a time:
float marks;
s3.rollno = s1.rollno;
}stud s1,s2,s3;
strcpy(s3.name,s1.name);
stud s1 = {1, “naina”, 80.5};
S3.marks = s1.marks;

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
Union

 Introduction of Union

 Union variable

 Accessing union members

 Memory allocation

 Union example

 Structure vs Union

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
INTRODUCTION OF
UNION
Union is a user-defined data type which can hold collection
of different type of data in the same memory location

Defining a union:

union keyword is used for defining a union having members of different type
union union_name union student
{ {
union element 1; int roll_no;
union element 2; char student_name[10];
union element 3; char dept[10];
. float marks;
. };
.
};

Syntax Example
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
UNION VARIABLE

Union is user defined data type, variables of that type can be declared

Different ways to declare variables are -

union student union student union student


{ { {
int roll_no; int roll_no; int roll_no;
char student_name[10]; char student_name[10]; char student_name[10];
char dept[5]; char dept[5]; char dept[5];
float marks; float marks; float marks;
}s1, s2, s3; }; };
union student s1; union student s1, s2;
union student s2;

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
ACCESSING UNION MEMBERS
union student Union elements can be accessed using dot operator (Using Variable s1)
{
int roll_no; Syntax: unionVariable.unionElement
char student_name[10];
Example:
char dept[5];
float marks; s1.roll_no
};
s1.dept
union student s1, *s2;
Union elements can be accessed using arrow operator
(Using Pointer variable *s2)
Syntax: unionVariable->unionElement
Example:
s2->roll_no
s2->dept
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
MEMORY ALLOCATION

Memory is not allocated while defining a union but it is allocated while declaring a variable of union
All union elements share same memory
Memory equal to the size of largest element is allotted to union
Union can contain different types of elements but not all elements can be initialized at a time
Only one element can be accessed at a time

union student
{ student_name = 10 bytes
int roll_no;
char student_name[10];
char dept[5];
float marks; 101 110
};
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
UNION EXAMPE

union student
{
int roll_no;
char student_name[10]; Invalid Initialization:
};
union student s1={10, “Neha”};
int main()
{
union student s2;
printf(“\n Enter rollno:”);
scanf(“%d”, &s2.roll_no);
printf(“%d”, s2.roll_no);
printf(“\n Enter name”);
scanf(“%s”, s2.student_name);
printf(“%s”, s2.student_name);
return 0;
}
engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
STRCTURE VS UNION

struct student
{
char name[40];
int roll_no;
int phone_number
};

union student
{
char name[40];
int roll_no;
int phone_number
};

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©
STRCTURE VS UNION

engineering _munotes
PRPEARED BY: PROF. SAYLEE NARKHEDE ©

You might also like