PSC 1
PSC 1
02/08/2024
School of Engineering and Technology, Sapthagiri NPS University
Problem Solving Using C
TABLE OF CONTENTS
Module 1 ................................................................................................................................................................. 4
1. INTRODUCTION TO PROGRAMMING CONCEPTS ......................................................................... 4
1.1 Computer Languages ................................................................................................................................ 4
1.2 Programming Language Translators ....................................................................................................... 6
1.3 Software ....................................................................................................................................................... 6
1.4 Modular Approach in Programming ......................................................................................................... 8
1.5 Structured programming ............................................................................................................................ 9
1.6 Algorithm .................................................................................................................................................... 10
1.7 Flowchart.................................................................................................................................................... 16
1.8 Overview of C Language ......................................................................................................................... 20
1.9 History of C ................................................................................................................................................ 20
1.10 Character set of C language ................................................................................................................. 22
1.11 C Tokens.................................................................................................................................................. 23
1.12 Keywords ................................................................................................................................................. 23
1.13 Identifiers ................................................................................................................................................. 24
1.14 Constants................................................................................................................................................. 24
1.15 Data types................................................................................................................................................ 27
1.16 Variables .................................................................................................................................................. 30
1.17 Format Specifiers ................................................................................................................................... 33
1.18 Operators and Expressions .................................................................................................................. 38
1.19 C Operators ............................................................................................................................................. 40
1.20 Type Conversion .................................................................................................................................... 59
1.21 Library functions in C ............................................................................................................................. 62
Module 2 ............................................................................................................................................................... 65
2. MANAGING INPUT AND OUTPUT OPERATIONS .............................................................................. 65
2.1 Unformatted I/O statements ................................................................................................................ 65
2.2 Formatted I/O Functions ...................................................................................................................... 68
2.3 Decision Making Statements .............................................................................................................. 72
2.4 Ternary operator ................................................................................................................................... 90
2.5 Looping structure in C .......................................................................................................................... 91
2.6 Break statement .................................................................................................................................... 97
2.7 Continue statement .............................................................................................................................. 97
2.8 Goto statement...................................................................................................................................... 98
2.9 C Programs .......................................................................................................................................... 99
Programming Language
A programming language is a set of symbols, grammars and rules with the help of which one
is able to translate algorithms to programs that will be executed by the computer. The
programmer communicates with a machine using programming languages.
Before moving on to any programming language, it is important to know about the various
types of languages used by the computer. Let us first know what the basic requirements of
the programmers were & what difficulties they faced while programming in that language.
1.1.1 Low Level Language: The term low level highlights the fact that it is closer to a
Machine Language: This is the language (in the form of 0’s and 1’s, called binary numbers)
understood directly by the computer. It is machine dependent. It is difficult to learn and even
more difficult to write programs.
Assembly Language: This is the language where the machine codes comprising of 0’sand
1’s are substituted by symbolic codes (called mnemonics) to improve their understanding. It
is the first step to improve programming structure. Assembly language programming is
simpler and less time consuming than machine level programming, it is easier to locate and
correct errors in assembly language than in machine language programs. It is also machine
dependent. Programmers must have knowledge of the machine on which the program will
run.
1.1.2 High Level Language: Low level language requires extensive knowledge of the
hardware since it is machine dependent. To overcome this limitation, high level language
has been evolved which uses normal English, which is easy to understand to solve any
problem. High level languages are computer independent and programming becomes quite
easy and simple. Various high-level languages are given below:
a. BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used, easy
to learn general purpose language. Mainly used in microcomputers in earlier days.
b. COBOL (Common Business Oriented language): A standardized language used
for commercial applications.
c. FORTRAN (Formula Translation): Developed for solving mathematical and
scientific problems. One of the most popular languages among scientific
community.
d. C: Structured Programming Language used for all purpose such as scientific
application, commercial application, developing games etc.
e. C++: Popular object-oriented programming language, used for general purpose.
As you know that high level language is machine independent and assembly language
though it is machine dependent yet mnemonics that are being used to represent instructions
are not directly understandable by the machine. Hence to make the machine understand the
instructions provided by both the languages, programming language instructors are used.
They transform the instruction prepared by programmers into a form which can be interpreted
& executed by the computer. Flowing are the various tools to achieve this purpose:
1.2.1 Compiler: The software that reads a program written in high level language and
translates it into an equivalent program in machine language is called as compiler. The
program written by the programmer in high level language is called source program and the
program generated by the compiler after translation is called as object program.
1.2.2 Interpreter: it also executes instructions written in a high-level language. Both complier
& interpreter have the same goal i.e. to convert high level language into binary instructions,
but their method of execution is different. The complier converts the entire source code into
machine level program, while the interpreter takes 1 statement, translates it, executes it &
then again takes the next statement.
1.2.3 Assembler: The software that reads a program written in assembly language and
translates it into an equivalent program in machine language is called as assembler.
1.2.4 Linker: A linker or link editor is a computer program that takes one or more object files
generated by a compiler and combines them into a single executable file, library file, or
another object file.
1.3 Software
Software is a set of instructions, data or programs used to operate computers and execute specific
tasks. It is the opposite of hardware, which describes the physical aspects of a computer.
Software is a generic term used to refer to applications, scripts and programs that run on a device.
System Software:
System Software is necessary to manage computer resources and support the execution of
application programs. Software like operating systems, compilers, editors and drivers, etc., come
under this category. A computer cannot function without the presence of these. Operating systems
are needed to link the machine-dependent needs of a program with the capabilities of the machine
on which it runs. Compilers translate programs from high-level language to machine language.
Application Software:
Application software is designed to fulfill the user’s requirement by interacting with the user directly.
It could be classified into two major categories are generic or customized. Generic Software is
software that is open to all and behaves the same for all of its users. Its function is limited and not
customized as per the user’s changing requirements. However, on the other hand, customized
software is the software products designed per the client’s requirement, and are not available for
all.
System software is used for operating the The user uses application software to
computer hardware. perform a specific task.
System software provides the platform for Application software cannot run without the
running application software. presence of system software.
The user does not interact with system In the application software, the user
software because it works in the background. interacts directly.
System software runs automatically when the Application software runs when the user
computer is turned ON and STOP when the requests it.
computer shutdown.
● Each sub-module contains something necessary to execute only one aspect of the desired
functionality.
● Modular programming emphasis on breaking large programs into small problems to increase
the maintainability, readability of the code and to make the program handy to make any
changes in future or to correct the errors.
In Structured Programming, the code is divided into functions or modules. It is also known as
modular programming. Modules or functions are a set of statements which performs a sub task. As
each task is a separate module, it is easy for the programmer to test and debug. It is also easy to
do modifications without changing the whole program.
When changing the code, the programmer has to concentrate only on the specific module. C
and Pascal are some examples of Structural Programming languages.
Unstructured Programming
In Unstructured Programming, the code is written as a single whole block. The whole program
is taken as a single unit. It is harder to do changes in the program. This paradigm was used
in earlier versions of BASIC, COBOL, and FORTRAN. Unstructured programming languages
have a limited number of data types like numbers, arrays, strings.
1.6 Algorithm
The word “algorithm” relates to the name of the mathematician Al-khowarizmi, which means a
procedure or a technique. Software Engineer commonly uses an algorithm for planning and
solving the problems. An algorithm is a sequence of steps to solve a particular problem or
algorithm is an ordered set of unambiguous steps that produces a result and terminates in a finite
time
The algorithm and flowchart include following three types of control structures.
1. Sequence: In the sequence structure, statements are placed one after the other and
the execution takes place starting from up to down.
2. Branching (Selection): In branch control, there is a condition and according to a
condition, a decision of either TRUE or FALSE is achieved. In the case of TRUE, one of
the two branches are explored; but in the case of FALSE condition, the other alternative
is taken. Generally, the ‘IF-THEN’ is used to represent branch control.
3. Loop (Repetition): The Loop or Repetition allows a statement(s) to be executed
repeatedly based on certain loop condition e.g. WHILE, FOR loops.
Advantages of algorithm
Before writing an algorithm for a problem, one should find out what is/are the inputs to the
algorithm and what is/are expected output after running the algorithm. Now let us take some
exercises to develop an algorithm for some simple problems: While writing algorithms we will
use following symbol for different operations:
Problem2: Write an algorithm to read two numbers and find their sum.
Inputs to the algorithm:
First num1.
Second num2.
Expected output:
Sum of the two numbers.
Algorithm:
Step1: Start
Step2: Read\input the first num1.
Step3: Read\input the second num2.
Step4: Sum num1+num2 // calculation of sum
Step5: Print Sum
Step6: End
Else
Display c is the largest number.
Else
If(b>c)
Display b is the largest number
Else
Display c is the largest number
Step5: Stop
Problem5: Design an algorithm which gets a natural value n as its input and
calculates odd numbers equal or less than n. Then write them in the standard
output:
1. Start
2. Read n
3. I ← 1
4. Write I
5. I ← I + 2
6. If ( I <= n) then go to line 4
7. End
Problem6: Design an algorithm which generates even numbers between
1000 and 2000 and then prints them in the standard output. It should also
print total sum:
1. Start
2. I ← 1000 and S ← 0
3. Write I
4. S ← S + I
5. I ← I + 2
6. If (I <= 2000) then go to line 3
else go to line 7
7. Write S
8. End
Properties of Algorithm
Donald Ervin Knuth has given a list of five properties for a, algorithm, these properties are:
1) Finiteness: An algorithm must always terminate after a finite number of steps. It means
after every step one reaches closer to the solution of the problem and after a finite number
of steps algorithm reaches to an end point.
3) Input: Any operation you perform needs some beginning value/quantities associated with
different activities in the operation. So, the value/quantities are given to the algorithm before
it begins.
operations should be basic, so that even they can in principle be done exactly and in a finite
amount of time by a person, by using paper and pencil only.
1.7 Flowchart
The first design of flowchart goes back to 1945 which was designed by John Von
Neumann. Unlike an algorithm, Flowchart uses different symbols to design a solution to a
problem. It is another commonly used programming tool. By looking at a Flow chart one
can understand the operations and sequence of operations performed in a system.
Flowchart is often considered as a blueprint of a design used for solving a specific
problem.
Advantages of flowchart:
Predefined Process
Preparation
Indicates preparation taken for
Hexagon the following step
Algorithm
Step - 1 Start
C: temperature in Celsius
F: temperature
Fahrenheit
Algorithm
Step -1 Start
Step - 3 F = (9.0/5.0 x C) + 32
Step - 5 Stop
Algorithm
Step-1 S t a r t
Step-4 Stop
Start
Value of
number 1
Value of
number 2
Stop
1.9 History of C
⮚ C is a general-purpose programming language developed by Dennis Ritchie at
AT&T Bell laboratories in 1972.
Advantages/Features of C Language
C language is very popular language because of the following features:
● Definition:
Purpose:
Ex 2: Area of Circle
Disadvantage:
⮚ It is very difficult to translate the solution of lengthy and complex problem in English to
C
C Programming Concepts
🡺 Digits (0-9)
🡺 Special Symbols (~ ‘! @ # % & * () - + / $ = \ {
🡺 } [ ] : ; “ “ ? etc)
# Hash ( Left ]
Right
parenthesis
bracket
$ Dollar sign ) Right
: Colon
parenthesis
^ + Plus, sign ;
Caret Semicolon
1.11 C Tokens
⮚ Tokens are the smallest or basic units of a C program.
1.12 Keywords
⮚ The tokens which have predefined meaning in C language are called keywords.
⮚ They are reserved for specific purposes in C language they are called Reserved
Words.
⮚ There are totally 32 keywords supported in C they are:
1.13 Identifiers
Definition:
⮚ Identifiers are the names given to program elements such as variables, constants,
function names, array names etc.
⮚ It consists of one or more letters or digits or underscores.
1.14 Constants
Definition:
Constants refers to fixed values that do not change during the execution of a program
The different types of constants are:
1. Integer constant
2. Real constant/Floating Pointing constant
3. Enumeration constant
4. Character constant
5. String constant
Integer constant
⮚ Definition: An integer is whole number without any decimal point.no extra
characters are allowed other than + or _ .
Three types of integers
⮚ Octal integers: are constants with a combination of Digits from 0 to 7 but it has a
prefix of 0
Ex: 027, 0657, 0777645
⮚ 215.5
⮚ -71.
⮚ +0.56 etc...
⮚ mantissa e exponent
⮚ It always starts with backslash; hence they are called as backslash constants.
\\ Backslash Backslash
\0 NULL
String constant
A sequence of characters enclosed within pair of double quotes is called string constant.
The string always ends with a NULL character.
Ex: “9”
“SNPS”
⮚ An int is a keyword using which the programmer can inform the compiler that the
data associated with this keyword should be treated as integer.
⮚ C supports 3 different types of integer:
o short int,
o int,
o long int
1.16 Variables
⮚ A variable is a name given to memory location where data can be stored.
⮚ Using variable name data can be stored in a memory location and can be accessed
or manipulated very easily.
● Rules for variables
⮚ No extra symbols are allowed other than letters, digits and Underscore
Example:
Sum –
valid For1-
valid
for -invalid (it is a keyword)
Declaration of variables:
⮚ Giving a name to a memory location is called declaring a variable.
⮚ Reserving the required memory space to store the data is called defining a variable.
⮚ General Syntax:
From the examples we will come to know that “a” is a variable of type integer and allocates 2 bytes
of memory. “x” and “y” are two variables of type float which will be allocated 4 bytes of memory for
each variable. “sum” is a double type variable which will be allocated with 8 bytes of memory for
each.
Variable Initialization
⮚ Variables are not initialized when they are declared and defined, they contain
garbage values (meaningless values)
⮚ The method of giving initial values for variables before they are processed is called
variable initialization.
⮚ General Syntax:
Var_name = expr;
Where,
Var_name is the name of the variable.
⮚ The “expr” on the right-hand side is evaluated and stored in the variable name
(Var_name) on the left-hand side.
⮚ The expression on the right-hand side may be a constant, variable or a larger
formula built from simple expressions by arithmetic operators.
Examples:
● int a=10;
● float x;
x=20;
// creates a variable y of float type and assigns value 20 to it.
● int a=10,b,b=a;
// creates two variables a and b. “a” is assigned with value 10, the value of “a” is assigned
to variable “b”. Now the value of b will be 10.
● price = cost*3;
● Square = num*num;
OUTPUT FUNCTION
⮚ print: Print the data stored in the specified memory location or variable.
⮚ Format: The data present in memory location is formatted in to appropriate data type.
⮚ Format string may be any character. The characters included within the double
quotes will be displayed on the output screen
⮚ Example: printf(“Welcome to India”);
Output:
Welcome to India
Method 2:
output:
integer=10, floating=20.00000
⮚ While specifying the variable name make sure that it matches the format
specifiers within the double quotes.
Symbols Meaning
%c Character
%o octal number
%s String
%lf Double
⮚ List of addresses of variables consist of the variable name preceded with &
symbol (address operator).
Example: int a;
float
b;
scanf(“%d%f”,&a,&b);
No escape sequences or additional blank spaces should be specified in the format specifiers.
● Ex: scanf(“%d %f”,&a,&b); //invalid
scanf(“%d\n%f”,&a,&b); //invalid
● & symbol is must to read the values, if not the entered value will not be stored in
the variable specified. Ex: scanf(“%d%f”,a,b);//invalid.
A Simple C Program
Example 1: Let us discuss a simple program to print the Hello SNPS
/*program to print Hello snps*/
#include<stdio.h>
void main( )
{
printf (“Hello SNPS”);
}
Output: Hello SNPS
⮚ Firstly, we have declared the header files stdio.h for including standard input
and output which will be printf and scanf statements.
⮚ Next, we start with the main program indicated by void main( )
⮚ Within the main program we declare the required variables for calculating the simple
interest. So, we declare p, t and r as float type and si as float type.
⮚ After which the values to p, t and r are read from keyboard using scanf.
⮚ Computed the simple interest by the formula (p*t*r)/100 and the result is
assigned to si.
⮚ Display the result si.
Structure of C Program
Comments/Documentation Section
Preprocessor Directives
Global declaration section
void main( ) [Program Header]
{
Local Declaration part
Execution part
Statement 1
------------
------------
Statement n
}
● Comments/Documentation Section
⮚ Provides instructions to the compiler to include some of the files before compilation
starts.
⮚ Some examples of header files are
#include <stdio.h>
#include
<conio.h>
#include
<string.h>
#include <math.h>
#include<stdlib.h> Etc…
⮚ There will be some variable which has to be used in anywhere in program and
used in more than one function which will be declared as global.
● The Program Header
⮚ Series of statements that performs specific task will be enclosed within braces { and
}
Subroutine Section: All user defined functions that are called in main function should be
defined.
.
Example: +, - ,*
Operand:
● The entity on which a operator operates is called an operand. Here the entity may
be a constant or a variable or a function.
● An operator may have one or two or three operands.
Example: a+b-c*d/e%f
In this example there are 6 operands ie a, b, c, d, e, f and 5 operators i.e +,-,*,/ and %.
Expression:
● A combination of operands and operators that reduces to a single value is called
an expression.
Eg:a+b/d
Classification of operators
⮚ The Operators are classified into four major categories based on the number of
operands as shown below:
⮚ Unary Operators
1) Binary Operators
2) Ternary Operators
3) Special Operators
1. Unary Operators: An operator which acts on only one operand to produce the result
is called unary operator. The Operators precede the operand.
Examples: -10
-a
--b
2. Binary Operators: An operator which acts on two operands to produce the result is
called a binary operator. In an expression involving a binary operator, the operator is
in between two operands.
Examples: a + b a*b
⮚ Since there are three operands a, b and c (hence the name ternary) that are
associated with operators? and it is called ternary operator.
1.19 C Operators
C operators can be classified based on type of operation
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Arithmetic operators
The operators that are used to perform arithmetic operation such as addition,
subtraction, multiplication, division etc are called arithmetic operators.
⮚ The operators are +, - ,* , / , %.
⮚ Let a=10, b=5. Here, a and b are variables and are known as operands.
Multiplication * a* b = 10 * 5 50 1 L-R
Modulus % a % b = 10 % 5 0 1 L-R
(Remainder)
/*Program to illustrate the use of arithmetic operators is given below*/
#include<stdio.h>
void main()
{
int a, b, sum,diff,mul,divres,modres;
printf(“enter a and b value\n”);
scanf(“%d %d”,&a,&b);
sum=a+b;
diff=a-b;
mul=a*b;
divres=a/b;
modres=a%
b;
printf(“%d, %d, %d ,%d ,%d\n”, sum,diff,mul,divres,modres);
}
Output: 35,25,150,6,0
Mathematical C expression
Expression
a÷b a/b
S=a+b+c S=(a+b+c)/2
2
ax2+bx+c a*x*x+b*x+c
e|a| exp(abs(a))
Relational Operators
⮚ We often compare two quantities depending on their relation, take certain decisions.
⮚ For example, we compare the age of two persons, or the price of two items, and
so on. These comparisons can be done with the help of relational operators.
⮚ The operators that are used to find the relationship between two operands are called as
relational expression.
⮚ An expression such as
a<b or 1<20
Relational operator in C
Logical Operators
⮚ The operator that are used to combine two or more relational expression
is called logical operators.
⮚ Result of logical operators is always true or
false.
Logical Operators in C are:
Operator Meaning Precedence Associativity
|| logical OR 3 L->R
Example:
36 && 0
=1 && 0
=0(False)
Logical OR (||)
The output of logical operation is false if and only if both the operands are evaluated to
false.
Example:
36 || 0
=1 || 0
=0(True)
Logical NOT
It is a unary operator. The result is true if the operand is false and the result is
false if the operand is true.
operand !
operand
True (1) False(0)
Example:
(a) !0=1 (b) !36
!1=0
NOTE: The logical operators && and | | are used when we want to test more than one condition
and make decisions.
An example: a>b && x==10
The above logical expression is true only if a>b is true and x==10 is true. If either (or
Syntax: Variable=expression;
Ex:
So,
3. The expression on right side of assignment is evaluated and the result is converted
into type of variable on left hand side of Assignment operator.
4. The converted data is copied into variable which is present on left hand side (LHS)
of assignment operator.
Example:
int a;
int
a=100;
int b;
b=a; // a value i.e 100 is assigned to b
var op = exp;
where
v is a variable, exp is an expression and op is a C library arithmetic operator.
The operator op= is known as the shorthand assignment operator.
The assignment statements
var op= exp; is equivalent to v= var op (exp). with var evaluated only once.
The operators such as +=, -=, *=,/= are called assignment
operators. Example:
The statement
x = x+ 10; can be written as x + = 10;
Example:
Solve the equation x*=y+z when x=10, y=5 and
z=3 Solution: x*=y+z can be written as
x=x*(y+z)
x =10*(5+3)
x=10*8
x=80
⮚ C allows two very useful operators not generally found in other languages. These
are the increment and decrement operators:
++ and --
⮚ The operator ++ adds 1 to the operand, while -- subtracts 1. The increment and
decrement operators are Unary operators.
⮚ The increment and decrement operators are classified into two categories:
Post
Increment:
Eg1:
#include<stdio.h> Output:21
void main() Description: Initial value of a is 20 after
{ int a=20; execution of a++, the value of a will be
21. a++;
printf(“%d”,a);
}
Eg2:
#include<stdio.h> Output : a= 21
void main( ) b=20
{
int a=20,b;
b=a++;
printf(“a=%d”,a);
printf(“b=%d”,b);
}
Post
Decrement: Eg
1:
#include<stdio.h> Output:19
void main() Description: Initial value of a is 20 after
{ int a=20; execution of a--, the value of a will be
19. a--;
printf(“%d”,a);
}
Pre-Decrement:
Eg 1:
#include<stdio.h> Output:19
void main() Description: Initial value of a is 20 after
{ int a=20; execution of --a, the value of a will be 19.
--a;
printf(“%d”,a);
}
Consider the following (let a=20)
Post increment
b=a++ current value of a used, b=a //b=20 a
is incremented by 1 a=a+1
//a=21
Pre-increment
b=++a a is incremented by 1, a=a+1 //a=21
incremented value of a used, b=a //b=21
The operator which operates on 3 operands are called Ternary operator or conditional
operator.
Syntax: (exp1)? exp2: exp3
where exp1, exp2, and exp3 are expressions and
In this example, Max will be assigned the value of b i.e b=15. This can be achieved using
the if… else statements as follows:
if (a>b)
x=a;
else
x=b;
Bitwise Operators
Bitwise operators are used to manipulate the bits of given data. These operators are used
for testing the bits, or shifting them right or left. Bitwise operators may not be applied to
float or double.
Operator Meaning Preceden Associativi
ce ty
~ Bitwise Negate 1 R->L
<< Bitwise Left Shift 2 L->R
>> Bitwise Right Shift 2 L->R
& Bitwise AND 3 L->R
^ Bitwise XOR (exclusive OR) 4 L->R
| Bitwise OR 5 L->R
0 & 0 0
0 & 1 0
1 & 0 0
1 & 1 1
a=10 00001010
b=6 00000110 (a&b)
c=2 00000010
2)Bitwise OR (|)
If the corresponding bit positions in both the operands are 0, then OR operation results
in 0; otherwise 1.
operand OR operand Result
1 2
0 | 0 0
0 | 1 1
1 | 0 1
1 | 1 1
a=10 00001010
b=6 00000110 (a|b)
c=2 00001110
0 ^ 0 0
0 ^ 1 1
1 ^ 0 1
1 ^ 1 0
a=10 00001010
b=6 00000110 (a^b)
c=12 00001100
First
operand
The content of the first operand is shifted towards the left by the number bit
positions specified in the second operand.
Example:
#include<stdio.h> OUTPUT: 5<<1=10
void main()
{ int a,b; a=5; b=a<<1;
printf(“ %d<<1=%d”,a,b);
}
Right shift operator (>>)
The operator that is used to shift the data by a specified number of bit positions towards
right is called right shift operator.
After right shift operation, LSB bit should be discarded and MSB is empty and should be
filled with 0.
b=a>>num Second operand
Firs operand
t
The first operand is the value to be shifted.
The content of first operand are shifted towards right by the number bit positions
specified in second operand.
Example:
#include<stdio.h> OUTPUT: 10>>1=5
void main()
{ int a,b;
a=10;
b=a>>1
;
printf(“ %d>>1=%d”,a,b);
}
Bitwise negate:
The operator that is used to change every bit from 0 to 1 and 1 to 0 in the specified
operand is called bitwise negate operator. It is used to find one’s compliment of an
operand.
Example:
#include<stdio.h>
void main()
{int a=10,b; b=~a;
printf(“Negation of a is %d”,b);
}
Tracing:
a=10 00001010
b=245 11110101
Special Operators
C supports some special operators of interest such as comma operator, sizeof operator.
The Comma Operator
❖ The comma operator can be used to link the related expressions together. A
comma- linked list of expressions are evaluated from left to right. The comma
operator has least precedence among all operator.
❖ It is a binary operator which is used to:
E.g. a=12,35,678;
2. Combine two or more statements into a single statement.
E.g. int a=10;
int b=20;
int c=30;
can be combined using comma operator as
follows: int a=10, b=20, c=30;
Examples:
1. sizeof(char); Output:1 Byte
2 int a; Output:2 Byte
sizeof(a)
Precedence [Priority]
It is the rule that specifies the order in which certain operations need to be
performed in an expression. For a given expression containing more than two
operators, it determines which operations should be calculated first.
Associativity
If all the operators in an expression have equal priority then the direction
or order chosen left to right or right to left to evaluate an expression is called
associativity.
Associativity
Right associativity:
Operators in Order of
Precedence
Operator Category Associativity
(Highest to Lowest)
Reference
Unary Operators ++, --, sizeof(), ~, +, - Right to Left(R->L)
Member Access -> or * L->R
Arithmetic Operators *, /, % L->R
Arithmetic Operators -, + L->R
Shift Operators <<, >> L->R
Relational Operators <, <=, >, >= L->R
Equality Operators ==, != L->R
Bitwise AND & L->R
Bitwise XOR ^ L->R
Bitwise OR | L->R
Logical AND && L->R
Logical OR || L->R
Conditional Operator ?: R->L
Assignment Operator =, +=, -=,*=, /=, %= R->L
Comma Operator , L->R
1. Integer Expressions
The rules to be followed while evaluating any expressions are shown below.
corresponding values.
● Evaluate each of the expression based on precedence and associativity.
● C can evaluate the expression if and only if the data types of two operands are
same.
● This process of converting data from lower rank to higher rank is called
as Implicit type conversion (ITC).
For example,
● If one operand type is int and other operand type is float, the operand
with type int is promoted to float.
double
float
unsigned long int
long int
unsigned int
int
Short int
char
Lower rank
datatype
Examples:
i. 5+3=8
int + int = int
ii. 5 + 3.5
= 8.5
int + float = float
main()
{
float a;
a = (float)5 / 3;
}
Gives result as 1.666666. This is because the integer 5 is converted to floating
point value before division and the operation between float and integer results in
float.
ITC ETC
Library functions in C are also inbuilt functions in C language. These inbuilt functions are
located in some common location, and it is known as the library. All the functions are used
to execute a particular operation. These library functions are generally preferred to obtain
the predefined output.
#include <stdio.h>
int main()
{
printf("Catch me if you can.");
}
If you try to use printf() without including the stdio.h header file, you will get an error.
Suppose, you want to find the square root of a number. To compute the square root of a
number, you can use the sqrt() library function. The function is defined in the math.h
header file.
#include <stdio.h>
#include <math.h>
int main()
{
float num, root;
printf("Enter a number: ");
scanf("%f", &num);
// Computes the square root of num and stores in root.
root = sqrt(num);
printf("Square root of %.2f = %.2f", num, root);
return 0;
#include <math.h>
#include <stdio.h>
// Driver code
int main()
{
double base, power, result;
base = 10.0;
power = 2.0;
Output
10.0^2.0 = 100.00
// program to illustrate log() functions
#include <math.h>
#include <stdio.h>
// Driver code
int main()
{
4 <limits.h> These limits specify that a variable cannot store any value beyond
these limits, for example-
An unsigned character can store up to a maximum value of 255.
6 <stdio.h> The stdio.h header defines three variable types, several macros,
and various
function for performing input and output.
The program takes some I/P- data, process it and gives the O/P.
C language has 2 types of I/O statements; all these operations are carried out through
function calls.
getchar( ):- It reads single character from standard input device. This function donot
require any arguments.
Syntax: - char variable_name = getchar( );
Ex: - char x;
x = getchar( );
putchar (): - This function is used to display one character at a time on the standard output
device.
Syntax:- putchar(char_variable);
Ex:- char x;
putchar(x);
program:
main( )
{
char ch;
printf(―enter a char‖);
ch = getchar( );
printf(―entered char
is‖); putchar(ch);
}
Output:
enter a char a
entered char is a
getc() :- This function is used to accept single character from the file.
Syntax: char variable_name = getc();
Ex:- char c;
c = getc();
gets( ):- This function is used to read group of characters(string) from the standard I/P
device.
Syntax:- gets(character array variable);
Ex:- gets(s);
puts( ):- This function is used to display string to the standard O/P device.
Syntax:- puts(character array variables);
Ex:- puts(s);
program:
main()
{
char s[10];
puts(―enter name‖);
gets(s);
puts(―print name‖);
puts(s);
}
Output:
getch(): - This function reads a single character directly from the keyboard without
displaying on
the screen. This function is used at the end of the program for displaying the output (without
pressing (Alt-F5).
getche(): - This function reads a single character from the keyboard and echoes(displays)
it to
the current text window.
Ex:- char c
c = getche();
program:
main()
{
char ch, c;
printf(―enter
char‖); ch = getch();
printf(―%c‖, ch);
printf(―enter
char‖); c = getche();
printf(―%c‖,c);
Output: -
enter character a
enter character b
b
program:
main()
{
char a;
printf(―enter
char‖); a = getchar();
if (isupper(a))
{
x= tolower(a);
putchar(x);
}
else
putchar(toupper(a));
}
scanf( ) , fscanf()
printf() , fprintf()
scanf( ) : -scanf() function is used to read information from the standard I/P device.
Control string (also known as format string) represents the type of data that the user is
going to accept and gives the address of variable. (char-%c , int-%d , float - %f , double-
%lf).Control string and variables are separated by commas. Control string and the
variables going to I/P should match with each other.
Ex: - int n;
scanf(―%d‖,&n);
The percentage sign (%) indicates that a conversion specification follows. w is an integer
number that specifies the field width of the number to be read and d known as data type
character indicates that the number to be read is in integer mode.
Ex: - scanf(―%2d,%5d‖,&a&b);
50 31426
The field width of real numbers is not to be specified unlike integers. Therefore, scanf reads
real numbers using the simple specification %f.
23.45 34.5
Ex: scanf(―%s‖,name1);
Griet
Formatted Output:
printf( ): This function is used to output any combination of data. The outputs are produced
in such a way that they are understandable and are in an easy to use form. It is necessary
for the programmer to give clarity of the output produced by his program.
The control string indicates how many arguments follow and what their types are.
The var1, var2 etc... are variables whose values are formatted and printed according to
the specifications of the control string.
The arguments should match in number, order and type with the format specifications.
We have a number of situations where we may have to change the order of execution of
statements based on certain conditions or repeat a group of statements until certain
specified conditions are met.
2.3.1The if Statement
alternative.
The syntax is shown below:
if(expression)
{
statement1;
}
Firstly, the expression is evaluated to true or false.
If the expression is evaluated to true, then statement1 is
executed. If the expression is evaluated to false, then
statement1 is skipped. The flow diagram is shown below:
Output:
Enter any non- zero integer:7
Number is positive number
printf(“Num
ber is
negative
number”)
Output:
Enter any non-zero integer:7
Number is positive number
#include<stdio.h>
main()
{
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b):
if a>b
printf(“a is greater”)
else
printf(“b is greater”);
}
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
return 0;
}
Output:
Enter an integer: 7
7 is an odd integer.
#include <stdio.h>
int main() {
char c;
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: ");
scanf("%c", &c);
OUTPUT:
Enter an alphabet: G
G is a consonant.
#include <stdio.h>
int main() {
return 0;
}
OUTPUT:
Enter three different numbers: 4 2 7
7.00 is the largest number.
#include <stdio.h>
int main() {
double num;
printf("Enter a number: ");
scanf("%lf", &num);
if (num <= 0.0) {
if (num == 0.0)
printf("You entered 0.");
else
printf("You entered a negative number.");
}
else
printf("You entered a positive number.");
return 0;
}
Output:
Enter a number: 4
You entered a positive number.
return 0;
}
OUTPUT:
Enter an integer: 10
Factorial of 10 = 3628800
if(expr3)
statement3
else
} State
ment
4
• Here, firstly expr1 is evaluated to true or false.
Example1: Program to select and print the largest of the 3 numbers using
nested “if-else” statements.
#include<stdio.h>void main()
{
int a,b,c;
printf(“Enter Three Values: \n”);
scanf(“%d %d %d ”, &a, &b, &c);
printf(“Largest Value is: ”) ;
if(a>b)
{
if(a>c)
printf(“ %d ”, a);
else
printf(“ %d ”, c);
}
else
{
if(b>c)
printf(“ %d”, b);
else
printf(
} “ %d”,
} c)
Example 2:
Problem Statement: Determine the grade of a student based on their score.
⚫ If the score is above 90, it's an 'A'.
⚫ If the score is between 80 and 90, check if it's above 85 for an 'A-' or else 'B+'.
Below 80, if it's above 70, it's a 'C', otherwise, it's a 'D'.
#include <stdio.h>
int main() {
int score = 88;
// Check if score is greater than 90
if (score > 90) {
printf("Grade: A\n");
} else {
// Score is 90 or below, check if score is greater than 80
if (score > 80) {
// Score is between 81 and 90, check if score is above 85
if (score > 85) {
printf("Grade: A-\n");
} else {
printf("Grade: B+\n");
}
} else {
// Score is 80 or below, check if score is above 70
if (score > 70) {
printf("Grade: C\n");
} else {
printf("Grade: D\n");
}
}
}
return 0;
}
}
else if(expression2)
{
statement2;
}
else if(expression3)
{
statement3
}
else
Default statement
Example: Program to find largest from three numbers given by user to explain
working of if-else-if statement or ladder.
#include<stdio.h>
int main()
{
int a,b,c;
printf("Enter three numbers: \n");
scanf("%d%d%d", &a, &b, &c);
if(a>b && a>c)
{
printf("Largest = %d", a);
}
else if(b>a && b>c)
{
printf("Largest = %d", b);
}
else
{
printf("Largest = %d", c);
}
return(0);
}
Output
Enter three numbers:
12
33
17
Largest = 3
...
default: statement;
}
The value of expression is tested for equality against the values of each of the
constants specified in the case statements in the order written until a match is found.
The statements associated with that case statement are then executed until a break
statement or the end of the switch statement is encountered.
The default section is optional -- if it is not included the default is that nothing happens
and execution simply falls through the end of the switch statement.
int x,y,z;
char a,b;
float f;
#include <stdio.h>void
main()
{
double num1, num2, result ;char
op ;
Note : The break statement need not be included at the end of the case statement body
if it is logically correct for execution to fall through to the next case statement (as in the
case of division by 0.0) or to the end of the switch statement (as in the case of default :
).
#include<stdio.h>
main()
{
int marks,index;
char grade[10];
printf(“Enter your marks”);
scanf(“%d”,&marks);
index=marks/10;
switch(index)
{
case 10 :
case 9:
case 8:
case 7:
case 6: grade=”first”;
break;
case 5 : grade=”second”;
break;
case 4 : grade=”third”;
break;
default : grade =”fail”;
break;
}
printf(“%s”,grade);
}
if (condition)
expr_1 ;
else
expr_2 ;
The? operator is a ternary operator in that it requires three arguments. One of the
advantages of the? operator is that it reduces simple conditions to one simple line of
code which can be thrown unobtrusively into a larger section of code.
For Example: - to get the maximum of two integers, x and y, storing the larger in max.
max = x >= y ? x : y ;
if ( x > = y )
max = x ;
else
max = y ;
giving the same result but the former is a little bit more sufficient.
The for statement is most often used in situations where the programmer knows in
advance how many times a particular set of statements are to be repeated. The for
statement is sometimes termed a counted loop.
initialisation
FALSE
test condition
TRUE
continue
with next
iteration
statement body
increment
end of statement
Note: The square braces above are to denote optional sections in the syntax but are
not part of the syntax. The semi-colons must be present in the syntax.
#include <stdio.h>void
main()
{
int x ;
Curly braces are used in C to denote code blocks whether in a function as in main() or
as the body of a loop.
For Example: - To print out all numbers from 1 to 100 and calculate their sum.
#include <stdio.h>void
main()
{
int x, sum = 0 ;
Multiple Initialization
C has a special operator called the comma operator which allows separate
expressions to be tied together into one statement.
For example, it may be tidier to initialize two variables in a for loop as follows: -
Sometimes for statement may not even have a body to execute as in the following
example where we just want to create a time delay.
It is possible to build a nested structure of for loops, for example the following creates a large time
delay using just integer variables.
unsigned int x, y;
int i, n;
return 0;
}
Output
The while statement is typically used in situations where it is not known in advance how many
iterations are required.
FALSE
test condition
TRUE
continuewith nextiteration
statement body
end of statement
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
Output:
1
2
3
4
5
while ( i )
sum += i-- ;// note the use of postfix decrement operator! printf (“Sum is %d \n”, sum);
}
where it should be recalled that any non-zero value is deemed TRUE in the condition section of the
statement.
2.5.3 Do while
The terminating condition in the “for” and “ while” loops are always tested before the body of the loop is
executed -- so of course the body of the loop may not be executed at all.
In the do while statement on the other hand the statement body is always executed at least once
as the condition is tested at the end of the body of the loop.
Syntax: do
{
statement body;
} while (condition);
statement body
FALSE
end of
statement
Example: To read in a number from the keyboard until a value in the range 1 to 10 is entered.
int i ;do
{
scanf( "%d\n", &i ) ;
} while ( i < 1 && i > 10 ) ;
In this case we know at least one number is required to be read so the do-while might be the natural
choice over a normal while loop.
When a break statement is encountered inside a while, for, do/while or switch statement the statement is
immediately terminated, and execution resumes at the next statement following the statement.
For Example: -
...
for ( x = 1 ; x <= 10 ; x++ )
{
if ( x > 4 )
break;
printf( “%d “ , x ) ;
}
printf( "Next executed\n" );//Output : “1 2 3 4 NextExecuted”
The continue statement terminates the current iteration of a while, for or do/while statement and
resumes execution back at the beginning of the loop body with the next iteration.
For Example: -
for ( x = 1; x <= 5; x++ )
{
if ( x == 3 )
continue ; printf( “%d “, x ) ;
}
printf( “Finished Loop\n” ) ; // Output : “1 2 4 5 Finished Loop”
Example: Program to detect the entered number as to whether it is even or odd. Use goto
statement.
#include<stdio.h>void main()
{
int x;
printf(“Enter a Number: \n”); scanf(“%d”, &x);
if(x % 2 = = 0)
goto even;
else
goto odd;
even:printf(“%d is Even Number”);return;
odd:printf(“ %d is Odd Number”);
}
Output:
Enter a Number:5
5 is Odd Number.
2.9 C Programs
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
return 0;
}
Output:
Enter an integer: 1001
1001 is a palindrome.
while (exp != 0) {
result *= base;
--exp;
}
printf("Answer = %.0Lf", result);
return 0;
}
OUTPUT:
3.1 Arrays
An Array is a collection of similar data elements. Array is one of the most used data structures in C
programming. It is a simple and fast way of storing multiple values under a single name.
An array in C is a fixed-size collection of similar data items stored in contiguous memory locations. It can
be used to store the collection of primitive data types such as int, char, float, etc., and also derived and
user-defined data types such as pointers, structures, etc.
10 20 30 40 50
a. A single dimensional array is a linear list of related data items of same data type.
b. In memory, all the data items are stored in contiguous memory
locations.
Declaration of one-dimensional array (Single dimensional array)
Syntax:
datatype array_name[size];
int a[5];
The above statement allocates 5*2=10 Bytes of memory for the array a.
float b[5];
The above statement allocates 5*4=20 Bytes of memory for the array b.
a. Each element in the array is identified using integer number called as index.
b. If n is the size of array, the array index starts from 0 and ends at n-1.
i. Declaration of arrays only allocates memory space for array. But array elements are not
initializedand hence values have to be stored.
ii. Therefore, to store the values in array, there are 3 methods
1.Initialization
2.Assigning Values
3.Input values from keyboard through scanf()
Where
✓ datatype can be char,int,float,double
✓ array name is the valid identifier
✓ size is the number of elements in array
✓ v1, v2, v3… ... vn are values to be assigned.
2 4 34 3 4
➢ Example:
int a[5]={10,20,30,40,50};
10 20 30 40 50
➢ The compiler will set the size based on the number of initial values.
Example:
int a[ ]={10,20,30,40,50};
In the above example the size of an array is set to 5
String Initialization
S N P S \0
S[0] S[1] S[2] S[3] S[4]
10 20 30
{
scanf(“%d”,&a[i]);
}
printf(“array elements are\n”):
for(i=0; i<n;i++)
{
printf(“%d”,a[i]);
}
}
}
printf(“sum is %d\n”,sum):
Or
data_type
array_name[row_size][column_size];
For example:
int a[2][3];
✓ The above statements allocate memory for 3*4=12 elements i.e 12*2=24 bytes.
Data_type array_name[exp1][exp2]={
{a1,a2,….an},
{b1,b2, .bn},
…………….
……………..
{z1,z2,…zn}
};
int a[3][3]={
{10,20,30},
{40,50,60},
{70,80,90}
};
10 20 30
40 50 60
70 80 90
➢ If the number of values to be initialized is less than the size of array, then the
elements areinitialized from left to right one after the other.
➢ The remaining locations initialized to zero automatically.
➢ Example:
int a[3][3]={
{10,20},
{40,50},
{70,80}
};
{
b[i][j]=a[i][j];
}
}
printf(“matrix b is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
}
#include<stdio.h>void main()
{
int m,n,i,j,a[3][3];clrscr();
printf(“enter number of rows and columns\n”);scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
big=a[0][0]; for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(big>a[i][j])
big=a[i][j];
}
}
printf(“big is %”,big);
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
{
c[i][j]=0; for(k=0;k<n;k++)
{
c[i][j]= c[i][j]+a[i][k]*b[k][j];
}
}
}
printf(“resultant matrix a is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
printf(“resultant matrix a is \n”);
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
printf(“resultant matrix a is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
Write a program to find sum of each row and sum of each column
#include<stdio.h>
void main()
{
int m,n,i,j,rsum,csum,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
for(j=0;j<n;j++)
{
rsum=rsum+a[i][j];
}
printf(“sum is %d”,rsum);
}
for(i=0;i<m;i++)
{
csum=0;
for(j=0;j<n;j++)
{
csum=csum+a[i][j];
}
printf(“sum is %d”,csum);
}
7 }
#include<stdio.h>void main()
{
int m,n,i,j,sum=0,a[3][3];
printf(“enter number of rows and columns\n”);scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<m;i++)
{
sum=sum+a[i][j];
}
printf(“sum is %d”,rsum);
}
3.4 Strings
3.4.1 C Strings
In C language a string is group of characters (or) array of characters, which is terminated by
delimiter \0 (null).
Thus, C uses variable-length delimited strings in programs.
char city[8]={„N‟,‟E‟,‟W‟,‟Y‟,‟O‟,‟R‟,‟K‟,‟\0‟};
The string city size is 8 but it contains 7 characters and one-character space is for NULL terminator.
In C, characters can be manipulated in the same way as we do with numbers. When we use a
character constant or a character variable in an expression, it is automatically converted into an
integer value, where the value depends on the local character set of the system. For example, if we
write
int i;
char ch 'A';
i = ch;
printf("%d", i);
C also enables programmers to perform arithmetic operations on character variables and character
constants. So, if we write
int i;
char ch = 'A';
i = ch + 10;
printf("%d", i);
Character variables and character constants can be used with relational operators as shown in the
example below,
char ch = 'C';
Output:
Output:
Output:
formatted input function: - scanf can be used with %s format specification to read a string.
Ex: - char name[10];
scanf(“%s”,name);
getchar(): - It is used to read a single character from keyboard. Using this function repeatedly we
may read entire line of text
(2) gets(): - It is more convenient method of reading a string of text including blank
spaces.
Printf(“%10.4s”,name);
printf(“%-10.4s”,name);
Char arr[row][col];
where,
Initialization: -
int main()
{
int n1; // n1 is a local variable to main()
}
void func()
{
int n2; // n2 is a local variable to func()
}
Output: n = 7
variables.
➢ The static variables can be declared outside the function and inside the function.
They have the characteristics of both local and global variables.
➢ Static can also be defined within a function.
Ex:
static int a,b;
Example Program to illustrate static variables
#include <stdio.h>
void display();
int main()
{
display();
display();
}
void display()
{
static int c = 1;
c += 5; // c = c + 5
printf("%d ",c);
}
OUTPUT:
6 11
✓ During the first function call, the value of ‘c’ is initialized to 1. Its value is increased by 5.
✓ Now, the value of ‘c’ is 6, which is printed on the screen.
✓ During the second function call, ‘c’ is not initialized to 1 again. It's because ‘c’ is a static variable.
✓ The value ‘c’ is increased by 5. Now, its value will be 11, which is printed on the screen.
#include <stdio.h>
int main()
{
register int count = 0;
while (count < 5)
{
printf("Count: %d\n", count);
count++;
}
return 0;
}
OUTPUT:
Count: 0
Count: 1
Count: 2
Count: 3
Count:
• In the above figure main() calls another function, func1() to perform a well-defined task.
• main() is known as the calling function and func1() is known as the called function.
• When the compiler encounters a function call, instead of executing the next statement in
the calling function, the control jumps to the statements that are a part of the called
function.
• After the called function is executed, the control is returned back to the calling program.
• It is not necessary that the main() can call only one function, it can call as many functions
as it wants and as many times as it wants. For example, a function call placed within a for
loop, while loop or do-while loop may call the same function multiple times until the
condition holds true.
• It is not that only the main() can call another functions. Any function can call any other
function. In the fig. one function calls another, and the other function in turn calls some other
function.
Uses of Functions
• C functions are used to avoid rewriting same logic/code again and again in a program .
• There is no limit in calling C functions to make use of same functionality wherever required.
• We can call functions any number of times in a program and from any place in a program.
• A large C program can easily be tracked when it is divided into functions.
• The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve
the functionality and to improve understandability of very large programs.
Where,
• function-name: any valid identifier
• Return-value-type:
o data type of the result (default int)
o void – indicates that the function returns nothing
• Parameter-list:
o Also called formal parameters.
o A list of variables, comma separated list, declares parameters:
o A type must be listed explicitly for each parameter unless, the parameter is of type
int.
• Declarations and statements: function body (block)
o Variables can be declared inside blocks (can be nested)
o You cannot create functions within inside other functions.
• Returning control
▪ If nothing returned
o return;
o or, until reaches right brace
▪ If something returned
o return expression;
• function_name: It is the identifier of the function. Use appropriate names for the
functions that specify the purpose of the function.
• parameter_list: It is the list of parameters that a function expects in parentheses. A
parameter consists of its data type and name. If we don’t want to pass any parameter,
we can leave the parentheses empty.
#include <stdio.h>
// Function prototype
float calculateRectangleArea(float length, float width);
int main()
{
float length = 5.0;
float width = 3.0;
// Function call
float area = calculateRectangleArea(length, width);
return 0;
}
// Function definition
float calculateRectangleArea(float length, float width)
{ return length * width;
Output
The area of the rectangle is: 15.00
The Data Type of the return value will depend upon the return type of function declaration.
For instance, if the return type is int, then the return value will be int.
In these types of functions program, we are going to calculate the multiplication of 2 integers
using the user defined functions without arguments and return keywords.
#include<stdio.h>
int Multiplication();
int main()
{
int Multi;
Multi = Multiplication();
printf("\n Multiplication of a and b is = %d \n", Multi );
return 0;
}
int Multiplication()
{
int Multi, a = 20, b = 40;
Multi = a * b;
return Multi;
}
Output
These Types of Functions allows the user to enter 2 integers. Next, we are going to pass those
values to the user-defined function to calculate the sum.
#include<stdio.h>
void Addition(int, int);
void main()
{
int a, b;
printf("\n Please Enter two integer values \n");
scanf("%d %d",&a, &b);
//Calling with dynamic values
Addition(a, b);
}
void Addition(int a, int b)
{
int Sum;
Sum = a + b;
printf("\n Addition of %d and %d is = %d \n", a, b, Sum);}
#include<stdio.h>
int Multiplication(int, int);
int main()
{
int a, b, Multi;
printf("\n Please Enter two integer values \n");
scanf("%d %d",&a, &b);
//Calling the with dynamic values
Multi = Multiplication(a, b);
printf("\n Multiplication of %d and %d is = %d \n", a, b, Multi);
return 0;
}
Multi = a * b;
return Multi;
}
• Call by value in which values of the variables are passed by the calling function to the called
function.
• Call by reference in which address of the variables are passed by the calling function to the
called function.
Mentioning the size of the array is optional. So the syntax can be written as:
n both of the above syntax, even though we are defining the argument as array it will still be
passed as a pointer. So we can also write the syntax as:
But passing an array to function results in array decay due to which the array loses information
about its size.
// Drive code
int main()
{
int arr[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
func(arr);
return 0;
}
Output
Size of arr[] in main(): 32bytes
As we can see,
• The size of the arr[] in the main() function (where arr[] is declared) is 32 bytes which
is = sizeof(int) * 8 = 4 * 8 = 32 bytes.
• But in the function where the arr[] is passed as a parameter, the size of arr[] is shown
as 8 bytes (which is the size of a pointer in C).
It is due to the fact that the array decays into a pointer after being passed as a parameter.
#include <stdio.h>
void print_string(char str[])
{
printf("%s\n", str);
}
int main()
{
char message[] = "Hello, world!";
print_string(message);
return 0;
}
Output:
Hello, world!
• The print_string function takes a single argument, str, which is an array of characters (i.e.,
a string).
• In the main function, a string message is defined and initialized with the value "Hello,
world!". This string is then passed as an argument to the print_string function.
• The print_string function uses the printf function to print the string passed to it, along with a
newline character to add a line break after the string.
#include <stdio.h>
void print_string(char *str)
{
printf("%s\n", str);
}
int main()
{
char message[] = "Hello, world!";
print_string(message);
return 0;
}
Output:
Hello, world!
Explanation
• The main function declares a string message with the value "Hello, world!", and passes it
to the print_string function.
• The print_string function takes a pointer to a character as an argument and uses
the printf function to print the string passed to it, along with a newline character.
Nested function is not supported by C because we cannot define a function within another
function in C. We can declare a function inside a function, but it’s not a nested function.
Because nested functions definitions cannot access local variables of the surrounding blocks,
they can access only global variables of the containing module. This is done so that lookup of
global variables doesn’t have to go through the directory. As in C, there are two nested scopes:
local and global (and beyond this, built-ins). Therefore, nested functions have only a limited use.
If we try to approach nested function in C, then we will get compile time error.
Output:
#include<stdio.h>
void add( int n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add(int n)
{
n = n + 10;
printf("\n The value of num in the called function = %d", n);
}
Output:
The value of num before calling the function = 2
The value of num in the called function = 12
The following points are to be noted while passing arguments to a function using the call-by-value
method.
• When arguments are passed by value, the called function creates new variables of the same
data type as the arguments passed to it.
• The values of the arguments passed by the function are copied into the newly created
variables.
• Arguments are called by value when the called function does not need to modify the values
of the original variables in the calling function.
• Values of the variables in the calling function remain unaffected when the arguments are
passed by using call-by-value technique.
● To indicate that an argument is passed using call by reference, an ampersand sign (&) is
placed after the type in the parameter list. This way, changes made to that parameter in the
called function body will then be reflected in its value in the calling program.
#include<stdio.h>
void add( int *n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(&num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add(int *n)
{
*n = *n + 10;
printf("\n The value of num in the called function = %d", *n);
}
Output:
The value of num before calling the function = 2
The value of num in the called function = 12
Classic example for recursive function is sum of Natural number using Recursion
#include <stdio.h>
int sum(int n);
int main() {
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
Output:
Initially, the sum() is called from the main() function with number passed as an argument.
Suppose, the value of n inside sum() is 3 initially. During the next function call, 2 is passed to
the sum() function. This process continues until n is equal to 0.
When n is equal to 0, the if condition fails and the else part is executed returning the sum of
4.11 Pointers
Pointer is a variable that stores the address of another variable. A pointer in c is used to allocate
memory dynamically at run time. The Pointer variable might be belonging to any of the data type
such as int, float, chat, double,short etc.
Syntax:
Data_type*var_name;
Example:
Int*p;
Char*p;
1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers
Increment/Decrement of a Pointer
Increment: It is a condition that also comes under addition. When a pointer is incremented, it
actually increments by the number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of
an int), and the new address will point to 1004. While if a float type pointer is incremented then
it will increment by 4(size of a float) and the new address will be 1004.
Decrement: It is a condition that also comes under subtraction. When a pointer is decremented,
it actually decrements by the number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size
of an int), and the new address will point to 996. While if a float type pointer is decremented
then it will decrement by 4(size of a float) and the new address will be 996.
p++;
printf("p++ = %u\n", p); //p++ = 6422292 +4 // 4 bytes
p--;
printf("p-- = %u\n", p); //p-- = 6422288 -4 // restored to original value
float b = 22.22;
float *q = &b;
printf("q = %u\n", q); //q = 6422284
q++;
printf("q++ = %u\n", q); //q++ = 6422288 +4 // 4 bytes
q--;
printf("q-- = %u\n", q); //q-- = 6422284 -4 // restored to original value
char c = 'a';
char *r = &c;
printf("r = %u\n", r); //r = 6422283
r++;
printf("r++ = %u\n", r); //r++ = 6422284 +1 // 1 byte
r--;
printf("r-- = %u\n", r); //r-- = 6422283 -1 // restored to original value
return 0;
}
Output
p = 1441900792
p++ = 1441900796
p-- = 1441900792
q = 1441900796
q++ = 1441900800
q-- = 1441900796
r = 1441900791
r++ = 1441900792
r-- = 1441900791
For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as
an address. If we add integer 5 to it using the expression, ptr = ptr + 5, then, the final address
stored in the ptr will be ptr = 1000 + sizeof(int) * 5 = 1020.
For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as
an address. If we subtract integer 5 from it using the expression, ptr = ptr – 5, then, the final
address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.
Example of Subtraction of Integer from Pointer, below is the program to illustrate pointer
Subtraction:
Output
Pointer ptr2 before Subtraction: 0x7ffd718ffebc
The subtraction of two pointers is possible only when they have the same data type. The result
is generated by calculating the difference between the addresses of the two pointers and
calculating how many bits of data it is according to the pointer data type. The subtraction of two
pointers gives the increments between the two pointers.
For Example:
Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are subtracted. The
difference between addresses is 4 bytes. Since the size of int is 4 bytes, therefore
the increment between ptr1 and ptr2 is given by (4/4) = 1.
Example of Subtraction of Two Pointer
// Driver Code
int main()
{
int x = 6; // Integer variable declaration
int N = 4;
// Pointer declaration
int *ptr1, *ptr2;
ptr1 = &N; // stores address of N
ptr2 = &x; // stores address of x
printf(" ptr1 = %u, ptr2 = %u\n", ptr1, ptr2);
// %p gives an hexa-decimal value,
// We convert it into an unsigned int value by using %u
return 0;
}
Output
ptr1 = 2715594428, ptr2 = 2715594424
Comparison of Pointers
We can compare the two pointers by using the comparison operators in C. We can implement
this by using all operators in C >, >=, <, <=, ==, !=. It returns true for the valid condition and
returns false for the unsatisfied condition.
1. Step 1: Initialize the integer values and point these integer values to the pointer.
2. Step 2: Now, check the condition by using comparison or relational operators on
pointer variables.
3. Step 3: Display the output.
Example of Pointer Comparison
}
else {
printf("Pointer to Array Name and First Element "
"are not Equal.");
}
return 0;
}
Output
Pointer to Array Name and First Element are Equal.
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output
m = 10
n = 20
After Swapping:
m = 20
n = 10
Example
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a an
d b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameter
s do change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 2
0, b = 10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
Example:
#include<stdio.h>
int main()
{
int i, x[20], sum = 0,n;
printf("Enter the value of n: ");
scanf("%d",&n);
printf("Enter number one by one\n");
for(i = 0; i < n; ++i)
{
/* Equivalent to scanf("%d", &x[i]); */ scanf("%d", x+i);
// Equivalent to sum += x[i]
sum += *(x+i);
}
printf("Sum = %d", sum);
return 0;
}
Output
Enter the value of n: 5
Enter number one by one
5
10
15
20
25
Sum = 75
• Pointers can be used to manipulate two-dimensional arrays also.
• A two-dimensional array can be represented by the pointer expression as follows
• *(*(a+i)+j) or *(*(p+1)+j)
printf("\n\n");
}
// signal to operating system program ran fine
return 0;
}
Output
arr[2][3]=44Address of 0 th array 2692284448
arr[0][0]=11
arr[0][1]=22
arr[0][2]=33
arr[0][3]=44
Address of 1 th array 2692284464
arr[1][0]=55
arr[1][1]=66
arr[1][3]=88
Address of 2 th array 2692284480
arr[2][0]=11
arr[2][1]=66
arr[2][2]=77
arr[2][3]=44
Here,
Example
char name[4][25];
• The name is a table containing four names, each with maximum of 25 characters.
• The total storage requirements are 75 bytes.
• The individual strings will of equal lengths.
Example
char *names[4] = { “Anu", “Banu", “Chandru", “Deepak" };
#include
const int MAX = 4;
int main ()
{
char *names[] = { “Anu", “Banu", “Chandru", “Deepak" };
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
Output
Value of names[0] = Anu
Value of names[1] = Banu
Example
struct inventory
{
int no;
char name[30];
float price;
}
product[5], *ptr ;
• The name product represents the address of the zero-th element of the structure array.
• ptr is a pointer to data objects of the type struct inventory.
• The assignment
ptr = product ;
will assign the address of product [0] to ptr.
• Its member can be access
ptr –>name ;
ptr –> no ;
ptr –> price;
The symbol “–>” is called the arrow operator or member selection operator.
• When the pointer ptr is incremented by one (ptr++) :The value of ptr is actually increased by
sizeof(inventory).
• It is made to point to the next record.
• We can also use the notation (*ptr).no;
• When using structure pointers, we should take care of operator precedence.
Example
void main ()
{
struct book
{
char name[25];
char author[25];
int edn;
};
struct book b1 = { "Programming in C", "E Balagurusamy", 2 } ;
struct book *ptr ; ptr = &b1 ;
printf ( "\n%s %s edition %d ", b1.name, b1.author, b1.edn ) ;
printf ( "\n%s %s edition %d", ptr- >name, ptr->author, ptr->edn ) ;
}
Output
Programming in C E Balagurusamy edition 2
Programming in C E Balagurusamy edition 2
In static memory allocation whenever the program executes it fixes the size that the program is
going to take, and it can’t be changed further. So, the exact memory requirements must be known
before. Allocation and deallocation of memory will be done by the compiler automatically. When
everything is done at compile time (or) before run time, it is called static memory allocation.
1. malloc()
2. calloc()
3. free()
4. realloc()
1. malloc()
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single
large block of memory with the specified size. It returns a pointer of type void which can be cast
into a pointer of any form. It doesn’t Initialize memory at execution time so that it has initialized
each block with the default garbage value initially.
Syntax of malloc() in C
For Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
return 0;
}
Output
2. Calloc() method
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of the
float.
Example of calloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
return 0;
}
Output
Enter number of elements: 5
3. free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated
using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is
used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of
memory by freeing it.
Syntax of free() in C
free(ptr);
Example of free()
#include <stdio.h>
#include <stdlib.h>
int main()
{
return 0;
}
Output
Enter number of elements: 5
4.realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation
of a previously allocated memory. In other words, if the memory previously allocated with the
help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.
re-allocation of memory maintains the already present value and new blocks will be initialized
with the default garbage value.
Syntax of realloc() in C
Example of realloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
free(ptr);
}
return 0;
}
Output
Enter number of elements: 5
4.17 Macros
The macro in C language is known as the piece of code which can be replaced by the macro
value. The macro is defined with the help of #define preprocessor directive and the macro
doesn’t end with a semicolon (;). Macro is just a name given to certain values or expressions it
doesn't point to any memory location.
Whenever the compiler encounters the macro, it replaces the macro name with the macro value.
Two macros could not have the same name.
In C, we must use the #define directive, then the macro’s name and value, to define a macro. The
following is the syntax to define a macro.
For example, if you want to define a macro for the value of pi, you can write:
#define PI 3.14159
Example:
#include<stdio.h>
// This is macro definition
#define PI 3.14
void main()
{
// declaration and initialization of radius
int radius = 5;
// declaration and calculating the area
float area = PI * (radius*radius);
// Printing the area of circle
printf("Area of circle is %f", area);
}
Output:
Area of circle is 78.500000
In the above code example, we wrote a program to calculate the area of a circle with the help of a
given radius. We defined the PI constant as a macro with the value 3.14
The macro in C language is classified based on the different types of values that it replaces.
An object like macros in C programming is simply the macros that get replaced by certain values
or segments of code.
In the above example, in the introduction, we saw the macro with the name PI and value 3.14 it is
an example of an object like macros.
#define MIN 1
#define TRUE 1
#define FALSE 0
In the function like macros are very similar to the actual function in C programming.
We can pass the arguments with the macro name and perform the actions in the code segment.
Let's consider the following code example which is the modification of the previous code -
#include <stdio.h>
#define PI 3.14
void main()
int radiusInt = 5;
Output:
Area of circle is 19.625000
Area of circle is 78.500000
See in the above code, we added the function-like macro at line no. 7.
The macro name is Area which takes the argument r as a radius that we have passed at line no.
15 and line no. 22.
At the time of preprocessing the value Area(radius) gets replaced with the processed macro value
and it is assigned to the area variable.
At line no. 15, we passed the value of radius as a float and at line no. 22 we passed the value of
radius as a float of type integer. So, macros gave us the advantage to use the same macro for
different datatypes because there is no type checking of arguments.
When we use one macro inside another macro, then it is known as the chain-like macro.
We already saw the example of a chain-like macro in the above code example where we used the
PI in Area. Let's discuss it a little more -
#define PI 3.14
#define Area(r) (PI*(r*r))
In the above code snippet, we can see we used the object like macro PI inside the function like
macro Area.
Here first parent macro gets expanded i.e. the functional macro Area and then the child macro
gets expanded i.e. PI. This way when we use one macro inside another macro, it is called a chain
macro.
In this example, `myheader.h` declares a macro `SQUARE(x)` and a function prototype `add`.
2. Implement the Functions:
Implement the functions declared in the header file in a separate source file (`.c` file).
// myfunctions.c
#include "myheader.h"
int add(int a, int b) {
return a + b;
}
Ensure that you include the header file `myheader.h` in the source file that contains the
implementations.
4. Compile:
When compiling your program, ensure that you include all relevant source files.
```
gcc main.c myfunctions.c -o myprogram
```
This command compiles `main.c` and `myfunctions.c` into an executable named `myprogram`.
5. Execute:
Run the compiled program.
./myprogram
The output is printed in `main.c`, which uses the functions and macros defined in `myheader.h`.
By following these steps, you can create and implement user-defined header files in C using macros
effectively. This modular approach enhances code organization, readability, and reusability.
Module 5
5.1 Structures
• A structure simply can be defined as a user-defined data type which groups logically related
items under one single unit. We can use all the different data items by accessing that single
unit.
• All the data items are stored in contiguous memory locations.
• It is not only permitted to one single data type items and it can store items of different data
items.
Example 1:
struct student
{
char name[100];
int roll;
float marks;
};
Example 2:
Suppose we need to store the details of an employee. It includes ID, name, age, salary,
designation and several other factors which belong to different data types.
struct Empl
{
int emp_id;
float salary;
char designation[20];
int depart_no;
int age_of_emp;
};
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
[OR]
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
Example :
C Program to declare a structure student with field name and roll no. take input from user and
display them.
#include<stdio.h>
struct student
{
char name[10];
int roll;
};
void main()
{
struct student s1;
clrscr();
printf("\n Enter student record\n");
printf("\n student name\t");
scanf("%s",s1.name);
printf("\nEnter student roll\t");
scanf("%d",&s1.roll);
printf("\nstudent name is %s",s1.name);
printf("\nroll is %d",s1.roll);
getch( );
}
OUTPUT:
Enter student record
Student name yaswanth
Enter student roll 35
5.2 Unions
• A union is a user-defined data type similar to a structure, but with a key difference: all
members of a union share the same memory location. This means only one member can
hold a value at any given time.
• The size of the union is determined by the size of its largest member.
• Unions are useful for memory management and situations where a variable may take on
different types of values at different times.
Syntax of union
union UnionName {
dataType member1;
dataType member2;
// more members
};
data.f = 220.5;
printf("data.f: %.2f\n", data.f);
Defining of Union
• A union has to defined, before it can be used.
• The syntax of defining a union is
union <union_name>
{
<data_type> <variable_name>;
<data_type> <variable_name>;
………….
<data_type> <variable_name>;
};
Example:
To define a simple union of a char variable and an integer variable
union shared
{
char c;
int i;
};
This union, shared, can be used to create instances of a union that can hold either a character
value(c) or an integer value( i ).
• The union data type allocates the space equal to space needed to hold the largest data
member of union.
• The union allows different types of variable to share same space in memory.
• The method to declare, use and access the union is same as structure.
• Memory Allocation:
o Structures: Each member has its own memory location. The total size of the
structure is the sum of the sizes of all members.
o Unions: All members share the same memory location. The size of the union is the
size of its largest member.
• Usage:
o Structures: Used when you need to store multiple related data items together.
o Unions: Used when you need to store one of several possible data items in the
same memory location, optimizing for memory usage.
struct outer_struct
{
In the above example of nested structure in C, there are two structures Student (depended
structure) and another structure called School(Outer structure).
• The structure School has the data members like numberOfStudents, numberOfTeachers,
and the Student structure is nested inside the structure School and it has the data members
like name, class, roll_Number.
• To access the members of the school structure, you use dot notation.
• For example, to access the numberOfStudents member of the school structure, you would
use the following syntax:
struct school s;
s.numberOfStudents = 100;
• To access the members of the nested student structure, you would use the following syntax:
o s.std.class = 10;
o s.std.roll_Number = 1;
• Note that the dot notation is used to access the members of the std structure, which is a
member of the school structure.
• The nested structure student contains three members: name, class, and roll_Number.
• This structure can be useful in situations where you need to store information about a
student, such as their name, class, and roll number.
1. Separate structure
2. Embedded structure
1. Separate structure
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
Embedded structure
• The embedded structure enables us to declare the structure inside the structure.
• Hence, it requires less line of codes but it cannot be used in multiple data structures.
struct Employee
int id;
char name[20];
struct Date
int dd;
int mm;
int yyyy;
}doj;
}emp1;
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
• To create an array of structure, first structure is declared and then array of structure
is declared just like an ordinary array.
struct employee
{
int emp_id;
char name[20];
char dept[20];
float salary;
};
• In this example, the first structure employee is declared, then the array of structure
created using a new type i.e. struct employee.
• Using the above array of structure, 10 set of employee records can be stored and
manipulated.
scanf(“%d”, emp[0].emp_id);
struct employee
{
int emp_id;
char name[20];
char dept[20];
float salary;
}emp[10];
typedef struct
{
int emp_id;
char name[20];
char dept[20];
float salary;
}employee;
employee emp[10];
Example:
C program to read records of three different students in structure having member name, roll
and marks, and displaying it.
#include<stdio.h>
/* Declaration of structure */
struct student
{
char name[30];
int roll;
float marks;
};
int main()
{
/* Declaration of array of structure */
struct student s[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter name, roll and marks of student:\n");
Name: Mohan
Roll: 18
Marks: 90.00
Name: Manjula
Roll: 19
Marks: 78.00
• We can use the dot (.) operator to access the individual members of the structure and pass
them to the function.
Example:
• Let us create a structure to hold the details of a student, such as the name of the student, roll
number, and marks.
• We want to print only the roll number and marks using a function.
• In this case, passing the entire structure to the function is unnecessary when we want to print
only a few structure members.
#include <stdio.h>
struct student
{
char name[50];
int per, rno; // declare percentage and roll number as
✓ In the above example, we created a structure to hold the name, roll number, and percentage of
the student.
✓ A function named display() is created, which takes the roll number and the percentage of the
student as the parameter.
✓ Using the dot (.) operator, we accessed the member of the structure and passed it to the
function.
OUTPUT:
Enter percentage: 98
Displaying information
Roll number: 42
Percentage: 98
✓ Passing the parameter as a value will make a copy of the structure variable, passing it to the
function.
✓ Making a copy of all the members and passing it to the function takes a lot of time and consumes
a lot of memory.
✓ Pointers are the variables that hold the address of other variables.
Example:
int main()
{
struct car tata;
printf("Enter the model name : ");
scanf("%s",tata.name);
printf("\nEnter the seating capacity : ");
scanf("%d",&tata.seat);
printf("\nEnter the fuel type : ");
scanf("%s",tata.fuel);
print_struct(&tata);
return 0;
}
void print_struct(struct car *ptr)
{
printf("\n---Details---\n");
printf("Name: %s\n", ptr->name);
printf("Seat: %d\n", ptr->seat);
printf("Fuel type: %s\n", ptr->fuel);
printf("\n");
}
Explanation:
• In the above code, a structure named car and a function named print_struct() are defined.
• The structure stores the model name, seating capacity, and the fuel type of the vehicle.
• In the main() function, we created a structure variable named tata and stored the values.
• Later the address of the structure is passed into the print_struct() function, which prints the
details entered by the user.
• To access the pointer members, we use the arrow operator -> operator.
OUTPUT:
---Details---
Name: ALtroz
Seat: 5
5.6 typedef in C
• The typedef is a keyword that is used to provide existing data types with a new name.
• The C typedef keyword is used to redefine the name of already existing data types.
• When names of datatypes become difficult to use in programs, typedef is used with user-
defined datatypes, which behave similarly to defining an alias for commands.
Syntax of typedef
typedef <existing_name> <alias_name>
• In the above syntax, 'existing_name' is the name of an already existing variable while 'alias
name' is another name given to the existing variable.
• For example, suppose we want to create a variable of type unsigned int, then it becomes
a tedious task if we want to declare multiple variables of this type.
• To overcome the problem, we use a typedef keyword.
• typedef unsigned int unit;
• In the above statements, we have declared the unit variable of type unsigned int by using a
typedef keyword.
• we can create the variables of type unsigned int by writing the following statement:
• unit a, b; instead of writing
o unsigned int a, b;
• the typedef keyword provides a shortcut by providing an alternative name for an already
existing variable.
• This keyword is useful when we are dealing with the long data type especially, structure
declarations.
Example 1 (typedef):
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is: %d",i);
printf("\nValue of j is: %d",j);
return 0;
}
OUTPUT:
Value of i is :10
Value of j is :20
• The above statement shows the creation of a variable, i.e., s1, but the statement is quite big.
• To avoid such a big statement, we use the typedef keyword to create the variable of type
student.
struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;
• In the above statement, we have declared the variable stud of type struct student.
• Now, we can use the stud variable in a program to create the variables of type struct student.
• It is a user-defined data type that consists of integer values, and it provides meaningful
names to these values.
• The use of enum in C makes the program easy to understand and maintain.
• In the above declaration, we define the enum named as flag containing 'N' integer constants.
• We can also change the default value of the integer constants at the time of the declaration.
Example:
enum fruits
{
mango=2,
apple=1,
strawberry=5,
papaya=7,
};
#include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
// creating today variable of enum week type
enum week today;
today = Wednesday;
printf("Day %d",today+2);
return 0;
}
OUTPUT:
Day 5
• The idea of bit-field is to use memory efficiently when we know that the value of a field or
group of fields will never exceed a limit or is within a small range.
• Bit fields in C language are used when the storage of our program is limited.
Bit-fields are variables that are defined using a predefined width or size.
Example: (Bitfields)
Consider the following example code.
struct Date
{
unsigned int day;
unsigned int month;
unsigned int year;
};
• Here, the variable of Date structure allocates 6 bytes of memory.
• In the above example structure, the members day and month both does not requires 2
bytes of memory for each.
• Because member day stores values from 1 to 31 only which requires 5 bits of memory,
and the member month stores values from 1 to 12 only which required 4 bits of memory.
• So, to save the memory, we use the bitfields.
• Consider the following structure with bitfields.
struct Date
{
unsigned int day : 5;
unsigned int month : 4;
unsigned int year;
};
1.Limited Storage: Bit-fields are a suitable choice when you have limited memory or storage
resources, as they allow you to represent and manipulate data in a compact way, using fewer bits
than standard data types.
2.Device Status and Information: In situations where devices need to transmit status or
information encoded as multiple bits, bit-fields are an efficient means of representing this data,
optimizing the use of available bits and ensuring efficient communication.
3.Encryption Routines: Encryption algorithms often work at the bit level to manipulate and
transform data.
Bit-fields can be a valuable tool in encryption routines to access and manipulate specific bits within
a byte, making them useful for bitwise operations and encryption-related tasks.
✓ When the main function of a program contains arguments, then these arguments are known as
Command Line Arguments.
✓ The main function can be created with two methods: first with no parameters (void) and second
with two parameters.
✓ The parameters are argc and argv, where argc is an integer and the argv is a list of command
line arguments.
✓ argc denotes the number of arguments given, while argv[] is a pointer array pointing to each
parameter passed to the program. If no argument is given, the value of argc will be 1.
✓ Using command line arguments, we can control the program execution from the outside of the
program.
✓ Generally, all the command line arguments are handled by the main() method. Generally, the
command line arguments can be understood as follows.
✓ When command line arguments are passed main() method receives them with the help of two
formal parameters and they are:
➢ int argc
➢ char *argv[ ]
• int argc - It is an integer argument used to store the count of command line arguments are
passed from the command line.
• char *argv[ ] - It is a character pointer array used to store the actual values of command line
arguments are passed from the command line.
Example:
// C Program to illustrate command line arguments
#include<stdio.h>
#include<conio.h>
int main(int argc, char *argv[])
{
int i;
if(argc == 1)
{
printf("Please provide command line arguments!!!");
return 0;
}
else
{
printf("Total number of arguments are - %d and they are\n\n", argc);
for(i=0; i<argc ; i++)
{
printf("%d -- %s \n", i+1, argv[i]);
}
return 0;
}
}
• #undef directive tell the compiler to undefine existing FILE_SIZE and define it as 45.
▪ #ifndef MESSAGE
▪ #define MESSAGE "You wish!"
▪ #endif
• #ifndef directive tells the compiler to define MESSAGE only if MESSAGE is not already
defined.
5.11 Files in C
• File handing in C is the process in which we create, open, read, write, and close operations
on a file.
• C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf()
to perform input, output, and many different C file operations in our program.
1. Reusability:
Data stored in files can be accessed, modified, and deleted as needed, providing high reusability
of information.
2. Portability:
• Files can be easily transferred between different systems without data loss.
• This feature minimizes the risk of coding errors and ensures seamless operation across
platforms.
3. Efficiency:
• File handling in C simplifies the process of accessing and manipulating large amounts of
data.
• It allows programs to efficiently retrieve specific information from files with minimal code,
saving time and reducing the likelihood of errors.
4. Storage Capacity:
• Files provide a means to store vast amounts of data without the need to hold everything in
memory simultaneously.
• This capability is particularly useful for handling large datasets and prevents memory
overload in programs.
• The mode determines where the file is positioned when opened, and what functions are
allowed.
• After you close a file, you can reopen the file in a different mode, depending on what you
are doing.
➢ Read mode
➢ Update mode
➢ Create mode
➢ Append mode
Read mode:
Update mode:
• You can update a record by repositioning the file to the beginning of the record, then writing
the new data.
Create mode:
• If a file by that name does not exist, the openfile() statement creates the file.
• If a file by that name exists, it overwrites the existing file, except in VMS (Virtual Machine
System).
• VMS: 4GL (Fourth Generation Language) creates a new version of the file. It does not
overwrite the file unless the file version limit is reached.
• You cannot read, position or rewind a file opened with create mode.
Append Mode:
• You cannot read, position or rewind a file opened with append mode.
Opening a file
To open a file in C, the fopen() function is employed, specifying the filename or file path along with
the desired access modes.
Syntax of fopen()
Parameters
• file_name: If the file resides in the same directory as the source file, provide its name;
otherwise, specify the full path.
• access_mode: Specifies the operation for which the file is being opened.
Return Value
• If the file fails to open, it returns NULL.There are many modes for opening a file:
}
printf("File opened successfully!");
return 0;
}
Create a File in C
• The fopen() function in C not only opens existing files but also creates a new file if it doesn't
already exist.
• This behavior is achieved by using specific modes that allow file creation, such as "w",
"w+", "wb", "wb+", "a", "a+", "ab", and "ab+".
FILE *file_ptr;
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Declare a file pointer variable to store the value returned by fopen
FILE* file_ptr;
// Open or create the file "filename.txt" in write mode
file_ptr = fopen("filename.txt", "w");
// Check if the file is opened successfully
if (file_ptr == NULL)
{
printf("Failed to create/open the file. The program will now exit.");
exit(1);
}
printf("File created/opened successfully!");
return 0;
• To read the file character by character, we use getc(). And to read line by line, we use
fgets().
Function Description
Retrieves input from a file using a formatted string and variable
fscanf()
argument list.
fgets() Obtains a complete line of text from the file.
fgetc() Reads a single character from the file.
fgetw() Reads a numerical value from the file.
fread() Extracts a specified number of bytes from a binary file.
}
while (s != EOF);
fclose(fp);
return 0;
}
In the above program, the getc() function is utilized to read the file character by character until
it reaches the end of the file (EOF).
Write to a File
• File writing operations in C are facilitated by functions like fprintf() and fputs().
• Additionally, C programming provides several other functions suitable for writing data to a
file.
Function Description
This function uses a formatted string and variable arguments list to print
fprintf()
output to the file.
fputs() Prints an entire line in the file along with a newline character at the end.
Example:
#include <stdio.h>
int main()
{
FILE *fptr;
int num = 42;
Syntax of fclose()
fclose(file_pointer);
Here, file_pointer is a pointer to the opened file that you want to close.
Example:
FILE *fptr;
fclose(fptr);
After completing the necessary file operations in C, the fclose() function is called to close the file
pointed to by fptr.
#include <stdio.h>
#include <string.h>
int main()
{
// Declare a pointer for the file
FILE *diaryFile;
// Content to be written into the file
char diaryEntry[150] = "Diary of a Programmer - "
"Today, I learned about file handling in C, "
"which feels like unlocking a new programming superpower.";
fputs(diaryEntry, diaryFile);
fputs("\n", diaryFile); // New line at the end of the entry
}
// Closing the file to save changes
fclose(diaryFile);
printf("Diary entry successfully recorded in LearningDiary.txt\n");
printf("File closed. Diary saved.\n");
}
return 0;
}
OUTPUT:
Text Files: Text files contain human-readable characters and are typically created and edited
using text editors. Functions like fscanf(), fprintf(), fgets(), and fputs() are used to read from and
write to text files.
Binary Files: Binary files contain data in a format that is not human-readable. They are used for
storing and retrieving structured data efficiently. Functions like fread() and fwrite() are used for
binary file I/O operations
Text file
• The user can create these files easily while handling files in C.
• It can be created by any text editor with a .txt or .rtf (rich text) extension.
• Since text files are simple, they can be edited by any text editor like Microsoft Word,
Notepad, Apple Text Edit, etc.
Binary file
• When intending to operate on a file in binary mode, utilize the access modes "rb", "rb+",
"ab", "ab+", "wb", or "wb+" with the fopen() function.
Example:
In this example, the file "example.bin" is opened in binary mode for reading using the "rb"
access mode.
• When writing data to a binary file, the fwrite() function proves invaluable.
• This function allows us to store information in binary form, comprising sequences of bits
(0s and 1s).
Syntax of fwrite()
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *file_pointer);
Parameters
ptr: A reference to the memory block holding the data intended for writing.
file_pointer: The FILE pointer associated with the output file stream.