PPS Notes
PPS Notes
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 1
CSE Department, LCIT Bilaspur
Computer Block Diagram System: Mainly computer system consists of three parts that are
central processing unit (CPU), Input Devices, and Output Devices. The Central Processing Unit
(CPU) is divided into two parts again: arithmetic logic unit (ALU) and the control unit (CU).
The set of instruction is in the form of raw data.
A large amount of data is stored in the computer memory with the help of primary and
secondary storage devices. The CPU is like the heart/brain of the computer. The user does not
get the desired output, without the necessary option taken by the CPU. The Central processing
unit (CPU) is responsible for the processing of all the instructions which are given by the user to
the computer system.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 2
CSE Department, LCIT Bilaspur
The CPU contains two parts: the arithmetic logic unit and control unit. We have discussed
briefly the arithmetic unit, logical unit, and control unit which are given below:
Control Unit
The control unit (CU) controls all the activities or operations which are performed inside the
computer system. It receives instructions or information directly from the main memory of the
computer.
When the control unit receives an instruction set or information, it converts the instruction set to
control signals then; these signals are sent to the central processor for further processing. The
control unit understands which operation to execute, accurately, and in which order.
Arithmetic and Logical Unit
The arithmetic and logical unit is the combinational digital electronic circuit that can perform
arithmetic operations on integer binary numbers. It presents the arithmetic and logical operation.
The outputs of ALU will change asynchronously in response to the input. The basic arithmetic
and bitwise logic functions are supported by ALU.
Storage Unit
The information or set of guidelines are stored in the storage unit of the computer system. The
storage unit provides the space to store the data or instruction of processed data. The
information or data is saved or hold in computer memory or storage device. The data storage is
the core function and fundamental of the computer components.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 3
CSE Department, LCIT Bilaspur
Processor.
Main Memory.
Secondary Memory.
Input Devices.
Output Devices.
These are mainly five components of the computer system. The computer hardware, computer
software, and liveware exist in the element of the computer system.
Processor
The processor is an electric circuitry within the computer system. The Central processing unit is
the central processor or main processor of the computer system. The processor carries out the
instructions of the computer program with the help of basic arithmetic and logic, input/output
operations.
Main Memory
The Random Access Memory is the main memory of the computer system, which is known as
RAM. The main memory can store the operating system software, application software, and
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 4
CSE Department, LCIT Bilaspur
other information. The Ram is one of the fastest memory, and it allows the data to be readable
and writeable.
Secondary memory
We can store the data and programs on a long-term basis in the secondary memory. The hard
disks and the optical disks are the common secondary devices. It is slow and cheap memory as
compare to primary memory. This memory is not connected to the processor directly.
It has a large capacity to store the data. The hard disk has a capacity of 500 gigabytes. The data
and programs on the hard disk are organized into files, and the file is the collection of data on
the disk. The secondary storage is direct access by the CPU; that's why it is different from the
primary storage.
The hard disk is about 100 times the capacity of the main memory. The main difference
between primary and secondary storage is speed and capacity. There are several large blocks of
data which are copied from the hard disk into the main memory.
Input Devices
The user provides the set of instruction or information to the computer system with the help of
input devices such as the keyboard, mouse, scanner, etc. The data representation to the
computer system is in the form of binary language after that the processor processes the
converted data. The input unit implements the data which is instructed by the user to the system.
We can enter the data from the outside world into the primary storage as the input through input
devices. The input devices are the medium of communication between the outside world and the
computer system.
There are some important features of input devices which are given below:
1. The input devices receive or accept the data or instruction from the user, who exist in the
outside world.
2. These devices convert the data or instruction into the machine-readable form for further
processing.
3. The input device performs like the connection between the outside world and our
computer system.
4. The keyboard and mouse are common examples of input devices.
5. When the whole procedure is finished, we get the desired output from the output devices
such as monitor, printer, etc.
Output Devices
The output devices produce or generate the desired result according to our input, such as a
printer, monitor, etc. These devices convert the data into a human-readable form from binary
code.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 5
CSE Department, LCIT Bilaspur
The computer system is linked or connected to the outside world with the help of output
devices. The primary examples of output devices are a printer, projector, etc.
These devices have various features which are given below:
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 6
CSE Department, LCIT Bilaspur
What is an Algorithm?
Algorithms can be simple and complex depending on what you want to achieve.
The Algorithm designed is language-independent, i.e. they are just plain instructions that can
be implemented in any language, and yet the output will be the same, as expected.
2. They help to automate processes and make them more reliable, faster, and easier to
perform.
3. Algorithms also enable computers to perform tasks that would be difficult or impossible for
humans to do manually.
4. They are used in various fields such as mathematics, computer science, engineering,
finance, and many others to optimize processes, analyze data, make predictions, and provide
solutions to problems.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 7
CSE Department, LCIT Bilaspur
Clear and Unambiguous: The algorithm should be clear and unambiguous. Each of its
steps should be clear in all aspects and must lead to only one meaning.
Well-Defined Outputs: The algorithm must clearly define what output will be yielded and
it should be well-defined as well. It should produce at least 1 output.
Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
Feasible: The algorithm must be simple, generic, and practical, such that it can be
executed with the available resources. It must not contain some future technology or
anything.
Input: An algorithm has zero or more inputs. Each that contains a fundamental operator
must accept zero or more inputs.
Output: An algorithm produces at least one output. Every instruction that contains a
fundamental operator must accept zero or more inputs.
Finiteness: An algorithm must terminate after a finite number of steps in all test cases.
Every instruction which contains a fundamental operator must be terminated within a finite
amount of time. Infinite loops or recursive functions without base conditions do not
possess finiteness.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 8
CSE Department, LCIT Bilaspur
Effectiveness: An algorithm must be developed by using very basic, simple, and feasible
operations so that one can trace it out by using just paper and pencil.
Properties of Algorithm:
It should terminate after a finite time.
It should produce at least one output.
It should take zero or more input.
It should be deterministic means giving the same output for the same input case.
Every step in the algorithm must be effective i.e. every step should do some work.
Advantages of Algorithms:
It is easy to understand.
An algorithm is a step-wise representation of a solution to a given problem.
In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for
the programmer to convert it into an actual program.
Disadvantages of Algorithms:
Writing an algorithm takes a long time so it is time-consuming.
Understanding complex logic through algorithms can be very difficult.
Branching and looping statements are difficult to show in Algorithms (imp).
Example:
Step 1: Start
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 6: Stop
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 9
CSE Department, LCIT Bilaspur
Step 1: Start
Step 4: If a > b
If a > c
Else
Else
If b > c
Else
Step 5: Stop
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 10
CSE Department, LCIT Bilaspur
Step 1: Start
factorial ← 1
i←1
5.2: i ← i+1
Step 7: Stop
1. Natural Language: - Here we express the Algorithm in natural English language. It is too
hard to understand the algorithm from it.
3. Pseudo Code: - Here we express the Algorithm in the form of annotations and informative
text written in plain English which is very much similar to the real code but as it has no
syntax like any of the programming language, it can’t be compiled or interpreted by the
computer. It is the best way to express an algorithm because it can be understood by even a
layman with some school level programming knowledge.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 11
CSE Department, LCIT Bilaspur
What is Flowchart?
A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be
defined as a diagrammatic representation of an algorithm, a step-by-step approach to solving a
task.
The flowchart shows the steps as boxes of various kinds, and their order by connecting the
boxes with arrows. This diagrammatic representation illustrates a solution model to a
given problem. Flowcharts are used in analyzing, designing, documenting or managing a
process or program in various fields.
Types of flowchart
Notice that every type of flowchart focuses on some kind of control, rather than on the
particular flow itself.
Building blocks
Common symbols
The American National Standards Institute (ANSI) set standards for flowcharts and their
symbols in the 1960s.[14] The International Organization for Standardization (ISO) adopted the
ANSI symbols in 1970. The current standard, ISO 5807, was revised in 1985. Generally,
flowcharts flow from top to bottom and left to right.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 12
CSE Department, LCIT Bilaspur
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 13
CSE Department, LCIT Bilaspur
Advantages of Flowchart
Disadvantages of Flowchart
Sample Problems
Question 1. Draw a flowchart to find the greatest number among the 2 numbers.
Solution:
Algorithm:
1. Start
5. Print b is greater
6. Stop
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 14
CSE Department, LCIT Bilaspur
Flow Chart:
Algorithm:
1. Start
2. Now initialize c = 1
3. Now we check the condition if c < 11, then go to step 4 otherwise go to step 6.
4. Print c
5. c = c + 1 then go to step 3
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 15
CSE Department, LCIT Bilaspur
Pseudo code, as the name suggests, is a false code or a representation of code which can be
understood by even a layman with some school level programming knowledge.
Pseudo code is a term which is often used in programming and algorithm based fields. It is a
methodology that allows the programmer to represent the implementation of an algorithm.
Simply, we can say that it’s the cooked up representation of an algorithm. Often at times,
algorithms are represented with the help of pseudo codes as they can be interpreted by
programmers no matter what their programming background or knowledge is.
Pseudo code, It’s simply an implementation of an algorithm in the form of annotations and
informative text written in plain English. It has no syntax like any of the programming
language and thus can’t be compiled or interpreted by the computer.
Advantages of Pseudocode
Improves the readability of any approach. It’s one of the best approaches to start
implementation of an algorithm.
Acts as a bridge between the program and the algorithm or flowchart. Also works as a
rough documentation, so the program of one developer can be understood easily when a
pseudo code is written out. In industries, the approach of documentation is essential. And
that’s where a pseudo-code proves vital.
The main goal of a pseudo code is to explain what exactly each line of a program should
do, hence making the code construction phase easier for the programmer.
This program will allow the user to check the number whether it's even or odd.
The way the if-else, for, while loops are indented in a program, indent the statements likewise,
as it helps to comprehend the decision control and execution mechanism. They also improve
the readability to a great extent.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 16
CSE Department, LCIT Bilaspur
Example:
if "1"
print response
if "2"
print response
3. Use appropriate naming conventions. The human tendency follows the approach to follow
what we see. If a programmer goes through a pseudo code, his approach will be the same
as per it, so the naming must be simple and distinct.
4. Use appropriate sentence casings, such as Camel Case for methods, upper case for
constants and lower case for variables.
5. Elaborate everything which is going to happen in the actual code. Don’t make the pseudo
code abstract.
6. Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we
use it in programming.
7. Check whether all the sections of a pseudo code is complete, finite and clear to understand
and comprehend.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 17
CSE Department, LCIT Bilaspur
The source code is often transformed by an assembler or compiler into binary machine code that
can be executed by the computer. The machine code is then available for execution at a later
time.
Most application software is distributed in a form that includes only executable files. If the
source code were included it would be useful to a user, programmer or a system administrator,
any of whom might wish to study or modify the program.
Alternatively, depending on the technology being used, source code may be interpreted and
executed directly.
Source code and object code are sometimes referred to as the before and after versions of a
compiled computer program. However, source code and object code do not apply to script (non-
compiled or interpreted) program languages, like JavaScript, since there is only one form of the
code.
Programmers can use a text editor, a visual programming tool or an integrated development
environment (IDE) such as a software development kit (SDK) to create source code. In large
program development environments, there are often management systems that help
programmers separate and keep track of different states and levels of source code files.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 18
CSE Department, LCIT Bilaspur
Source Code:
Source code refers to high level code or assembly code which is generated by
human/programmer. Source code is easy to read and modify. It is written by
programmer by using any High Level Language or Intermediate language which is
human-readable. Source code contains comments that programmer puts for better
understanding.
Source code is provided to language translator which converts it into machine
understandable code which is called machine code or object code. Computer can not
understand direct source code, computer understands machine code and executes it. It
is considered as fundamental component of computer. In simple we can say source
code is a set of instructions/commands and statements which is written by a
programmer by using a computer programming language like C, C++, Java, Python,
Assembly language etc. So statements written in any programming language is termed
as source code.
Object Code:
Object code refers to low level code which is understandable by machine. Object code
is generated from source code after going through compiler or other translator. It is in
executable machine code format. Object code contains a sequence of machine
understandable instructions to which Central Processing Unit understands and
executes.
Object file contains object code. It is considered as one more of machine code. Some
object file examples are common object file format (COFF), COM files and “.exe”
files. It is the output of a compiler or other translator. We can understand source code
but we cannot understand object code as it is not in plain text like source code rather it
is in binary formats.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 19
CSE Department, LCIT Bilaspur
1. Compiler:
It is a translator which takes input i.e., High-Level Language, and produces an output of low-
level language i.e. machine or assembly language.
A compiler is more intelligent than an assembler it checks all kinds of limits, ranges,
errors, etc.
But its program run time is more and occupies a larger part of memory. It has a slow speed
because a compiler goes through the entire program and then translates the entire program
into machine codes.
2. Interpreter:
An interpreter is a program that translates a programming language into a comprehensible
language.
Advantage The code execution time is They are fairly easy to use and execute,
comparatively less because the even for a beginner.
program code already gets translated
into machine code.
Disadvantage One can’t change a program without Only computers with the corresponding
getting back to the source code. Interpreter can run the interpreted programs.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 20
CSE Department, LCIT Bilaspur
Machine Code It stores the machine language on the It doesn’t save the machine language at all.
disk in the form of machine code.
Running Time The compiled codes run The interpreted codes run comparatively
comparatively faster. slower.
Model It works on the basis of the language- It works on the basis of the Interpretation
translation linking-loading model. method.
Execution One can separate the program Execution of the program is one of the steps
execution from the compilation. of the Interpretation process. So, you can
Thus, you can perform it only after perform it line by line.
completing the compilation of the
entire output.
Best Fitted For You cannot port the Compiler They work the best in web environments-
because it stays bound to the specific where the load time is very crucial.
target machine. The compilation Compiling takes a relatively long time, even
model is very common in with small codes that may not run multiple
programming languages like C and times due to the exhaustive analysis.
C++. Interpretations are better in such cases.
Optimization A compiler is capable of seeing the An interpreter sees a code line by line. The
of Code entire code upfront. Thus, it makes optimization is, thus, not very robust when
the codes run faster by performing compared to Compilers.
plenty of optimizations.
Dynamic Compilers are very difficult to The Interpreted language supports Dynamic
Typing implement because they can’t predict Typing.
anything that happens during the turn
time.
Use It works best for the Production It works the best for the programming and
Environment. development environment.
Execution of A Compiler displays every error and An Interpreter reads every statement, then
Error warning while compiling. So, you displays the errors, if any. A user must
can’t run this program unless you fix resolve these errors in order to interpret the
the errors. next line.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 21
CSE Department, LCIT Bilaspur
Output The Compilers generate intermediate The Interpreters never generate any
machine codes. intermediate machine codes.
Errors This translator displays all the errors It displays the errors of every single line
after compiling- together at the same one by one.
time.
Programming Java, Scala, C#, C, C++ use Perl, Ruby, PHP use Interpreters.
Languages Compilers.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 22
CSE Department, LCIT Bilaspur
C Programming Language
C language Tutorial with programming approach for beginners and professionals, helps you to
understand the C language tutorial easily. Our C tutorial explains each topic with programs.
The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.
C programming is considered as the base for other programming languages, that is why it is
known as mother language.
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language
1) C as a mother language
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of
the programming languages follow C syntax, for example, C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that are being
used in many languages like C++, Java, C#, etc.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedural language breaks the program into functions, data structures, etc.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 23
CSE Department, LCIT Bilaspur
In the C language, we break the program into parts using functions. It makes the program easier
to understand and modify.
A High-Level language is not specific to one machine, i.e., machine independent. It is easy to
understand.
Example:
#include <stdio.h>
int main()
{
printf("Hello C Programming\n");
return 0;
}
(OR)
#include <stdio.h>
#include <conio.h>
void main()
{
printf("Hello C Programming\n");
getch();
}
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 24
CSE Department, LCIT Bilaspur
History of C Language
History of C language is interesting to know. Here we are going to discuss
a brief history of the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, and etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.ay Video
Let's see the programming languages that were developed before C language.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 25
CSE Department, LCIT Bilaspur
Features of C Language
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.
Unlike assembly language, c programs can be executed on different machines with some
machine specific changes. Therefore, C is a machine independent language.
C is a structured programming language in the sense that we can break the program into
parts using functions. So, it is easy to understand and modify. Functions also provide code
reusability.
5) Rich Library
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated
memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions
and hence the lesser overhead.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 26
CSE Department, LCIT Bilaspur
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for every
function. Recursion enables us to use the approach of backtracking.
10) Extensible
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 27
CSE Department, LCIT Bilaspur
First C Program
Before starting the C language, you need to learn how to write, compile and run the first c
program.
To write the first c program, open the C console and write the following code:
1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }
#include <stdio.h> includes the standard input output library functions. The printf() function
is defined in stdio.h .
int main() The main() function is the entry point of every program in c language.
return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for
successful execution and 1 for unsuccessful execution.
There are 2 ways to compile and run the c program, by menu and by shortcut.
By menu
Now click on the compile menu then compile sub menu to compile the c program.
Then click on the run menu then run sub menu to run the c program.
By shortcut
Or, press ctrl+f9 keys compile and run the program directly.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 28
CSE Department, LCIT Bilaspur
You can view the user screen any time by pressing the alt+f5 keys.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 29
CSE Department, LCIT Bilaspur
Compilation process in c
What is a compilation?
The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural
errors, and if the source code is error-free, then it generates the object code.
The c compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.
The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the
directive and replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our program passes before being transformed into
an executable form:
o Preprocessor
o Compiler
o Assembler
o Linker
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 30
CSE Department, LCIT Bilaspur
Preprocessor
The source code is the code which is written in a text editor and the source code file is given an
extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the pre-
processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the object
file generated by the assembler is the same as the source file. The extension of the object file in
DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then
the name of the object file would be 'hello.obj'.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 31
CSE Department, LCIT Bilaspur
Linker
Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The
main working of the linker is to combine the object code of library files with the object code of
our program. Sometimes the situation arises when our program refers to the functions defined in
other files; then linker plays a very important role in this. It links the object code of these files to
our program. Therefore, we conclude that the job of the linker is to link the object code of our
program with the object code of the library files and other files. The output of the linker is the
executable file. The name of the executable file is the same as the source file but differs only in
their extensions. In DOS, the extension of the executable file is '.exe', and in UNIX, the
executable file can be named as 'a.out'. For example, if we are using printf() function in a
program, then the linker adds its associated code in an output file.
hello.c
1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello javaTpoint");
5. return 0;
6. }
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 32
CSE Department, LCIT Bilaspur
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 33
CSE Department, LCIT Bilaspur
In the above flow diagram, the following steps are taken to execute a program:
o Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor
converts the source code into expanded source code. The extension of the expanded
source code would be hello.i.
o The expanded source code is passed to the compiler, and the compiler converts this
expanded source code into assembly code. The extension of the assembly code would
be hello.s.
o This assembly code is then sent to the assembler, which converts the assembly code into
object code.
o After the creation of an object code, the linker creates the executable file. The loader
will then load the executable file for the execution.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 34
CSE Department, LCIT Bilaspur
printf() function
The printf() function is used for output. It prints the given statement to the console.
1. printf("format string",argument_list);
scanf() function
The scanf() function is used for input. It reads the input data from the console.
1. scanf("format string",argument_list);
Let's see a simple example of c language that gets input from the user and prints the cube of the
given number.
1. #include<stdio.h>
2. int main()
3. {
4. int number;
5. printf("enter a number:");
6. scanf("%d",&number);
7. printf("cube of number is:%d ",number*number*number);
8. return 0;
9. }
Output
enter a number:5
cube of number is:125
The scanf("%d",&number) statement reads integer number from the console and stores the
given value in number variable.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 35
CSE Department, LCIT Bilaspur
Let's see a simple example of input and output in C language that prints addition of 2 numbers.
1. #include<stdio.h>
2. int main()
3. {
4. int x=0,y=0,result=0;
5.
6. printf("enter first number:");
7. scanf("%d",&x);
8. printf("enter second number:");
9. scanf("%d",&y);
10.
11. result=x+y;
12. printf("sum of 2 numbers:%d ",result);
13.
14. return 0;
15. }
Output
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 36
CSE Department, LCIT Bilaspur
Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be changed,
and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
1. int a;
2. float b;
3. char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
1. int a;
2. int _ab;
3. int a30;
1. int 2;
2. int a b;
3. int long;
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 37
CSE Department, LCIT Bilaspur
Types of Variables in C
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable
A variable that is declared inside the function or block is called a local variable.
1. void function1(){
2. int x=10;//local variable
3. }
Global Variable
A variable that is declared outside the function or block is called a global variable. Any function
can change the value of the global variable. It is available to all the functions.
Static Variable
A variable that is declared with the static keyword is called static variable.
1. void function1()
2. {
3. int x=10;//local variable
4. static int y=10;//static variable
5. x=x+1;
6. y=y+1;
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 38
CSE Department, LCIT Bilaspur
7. printf("%d,%d",x,y);
8. }
If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented
value in each function call, e.g. 11, 12, 13 and so on.
Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. We can
explicitly declare an automatic variable using auto keyword.
1. void main()
2. {
3. int x=10;//local variable (also automatic)
4. auto int y=20;//automatic variable
5. }
External Variable
We can share a variable in multiple C source files by using an external variable. To declare an
external variable, you need to use extern keyword.
1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue()
4. {
5. printf("Global variable: %d", global_variable);
6. }
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 39
CSE Department, LCIT Bilaspur
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 40
CSE Department, LCIT Bilaspur
float 4 byte
double 8 byte
Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There
are only 32 reserved words (keywords) in the C language.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 41
CSE Department, LCIT Bilaspur
C Identifiers
C identifiers represent the name in the C program, for example, variables, functions, arrays,
structures, unions, labels, etc. An identifier can be composed of letters such as uppercase,
lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an
underscore. If the identifier is not used in the external linkage, then it is called as an internal
identifier. If the identifier is used in the external linkage, then it is called as an external
identifier.
We can say that an identifier is a collection of alphanumeric characters that begins either with
an alphabetical character or an underscore, which are used to represent various programming
elements such as variables, functions, arrays, structures, unions, labels, etc. There are 52
alphabetical characters (uppercase and lowercase), underscore character, and ten numerical
digits (0-9) that represent the identifiers. There is a total of 63 alphanumerical characters that
represent the identifiers.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 42
CSE Department, LCIT Bilaspur
Keyword Identifier
Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c compiler.
It does not contain the underscore character. It can contain the underscore character.
1. int main()
2. {
3. int a=10;
4. int A=20;
5. printf("Value of a is : %d",a);
6. printf("\nValue of A is :%d",A);
7. return 0;
8. }
Output
Value of a is : 10
Value of A is :20
The above output shows that the values of both the variables, 'a' and 'A' are different. Therefore,
we conclude that the identifiers are case sensitive.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 43
CSE Department, LCIT Bilaspur
C Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise, etc.
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
We will, in this chapter, look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds
10 and variable B holds 20 then −
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 44
CSE Department, LCIT Bilaspur
Show Examples
== Checks if the values of two operands are equal or not. If yes, then the (A == B)
condition becomes true. is not
true.
!= Checks if the values of two operands are equal or not. If the values are not (A != B)
equal, then the condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right operand. (A > B)
If yes, then the condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right operand. If (A < B)
yes, then the condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal to the value of (A >= B)
right operand. If yes, then the condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value of right (A <= B)
operand. If yes, then the condition becomes true. is true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
Show Examples
&& Called Logical AND operator. If both the operands are non-zero, then the (A &&
condition becomes true. B) is
false.
! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
operand. If a condition is true, then Logical NOT operator will make it false. B) is
true.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 45
CSE Department, LCIT Bilaspur
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^
is as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B)
= 12,
i.e., 0000
1100
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 46
CSE Department, LCIT Bilaspur
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B)
= 49,
i.e., 0011
0001
~ (~A ) =
Binary One's Complement Operator is unary and has the effect of 'flipping' ~(60),
bits. i.e,. -
0111101
<< Binary Left Shift Operator. The left operands value is moved left by the A << 2 =
number of bits specified by the right operand. 240 i.e.,
1111
0000
>> Binary Right Shift Operator. The left operands value is moved right by the A >> 2 =
number of bits specified by the right operand. 15 i.e.,
0000
1111
Assignment Operators
The following table lists the assignment operators supported by the C language −
Show Examples
= Simple assignment operator. Assigns values from right side operands to left C=A+
side operand B will
assign the
value of
A + B to
C
+= Add AND assignment operator. It adds the right operand to the left operand C += A is
and assign the result to the left operand. equivalent
to C = C
+A
-= Subtract AND assignment operator. It subtracts the right operand from the C -= A is
left operand and assigns the result to the left operand. equivalent
to C = C -
A
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 47
CSE Department, LCIT Bilaspur
*= Multiply AND assignment operator. It multiplies the right operand with the C *= A is
left operand and assigns the result to the left operand. equivalent
to C = C
*A
/= Divide AND assignment operator. It divides the left operand with the right C /= A is
operand and assigns the result to the left operand. equivalent
to C = C /
A
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 48
CSE Department, LCIT Bilaspur
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 49
CSE Department, LCIT Bilaspur
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 50
CSE Department, LCIT Bilaspur
C Format Specifier
The Format specifier is a string used in the formatted input and output functions. The format
string determines the format of the input and output. The format string always starts with a '%'
character.
Format Description
specifier
%d or %i It is used to print the signed integer value where signed integer means that the
variable can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned integer means
that the variable can hold only positive value.
%o It is used to print the octal unsigned integer where octal integer value always
starts with a 0 value.
%f It is used for printing the decimal floating-point values. By default, it prints the
6 values after '.'.
%g It is used to print the decimal floating-point values, and it uses the fixed
precision, i.e., the value after the decimal in input would be exactly the same
as the value in the output.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 51
CSE Department, LCIT Bilaspur
o %d
1. int main()
2. {
3. int b=6;
4. int c=8;
5. printf("Value of b is:%d", b);
6. printf("\nValue of c is:%d",c);
7.
8. return 0;
9. }
In the above code, we are printing the integer value of b and c by using the %d specifier.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 52
CSE Department, LCIT Bilaspur
Programming Errors in C
Errors are the problems or the faults that occur in the program, which makes the behavior of the
program abnormal, and experienced developers can also make these faults. Programming errors
are also known as the bugs or faults, and the process of removing these bugs is known
as debugging.
These errors are detected either during the time of compilation or execution. Thus, the errors
must be removed from the program for the successful execution of the program.
Syntax error
o Syntax errors are also known as the compilation errors as they occurred at the
compilation time, or we can say that the syntax errors are thrown by the compilers.
These errors are mainly occurred due to the mistakes while typing or do not follow the
syntax of the specified programming language. These mistakes are generally made by
beginners only because they are new to the language. These errors can be easily
debugged or corrected.
For example:
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 53
CSE Department, LCIT Bilaspur
1. #include <stdio.h>
2. int main()
3. {
4. a = 10;
5. printf("The value of a is : %d", a);
6. return 0;
7. }
Output
In the above output, we observe that the code throws the error that 'a' is undeclared. This error is
nothing but the syntax error only.
There can be another possibility in which the syntax error can exist, i.e., if we make mistakes in
the basic construct. Let's understand this scenario through an example.
1. #include <stdio.h>
2. int main()
3. {
4. int a=2;
5. if(.) // syntax error
6.
7. printf("a is greater than 1");
8. return 0;
9. }
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 54
CSE Department, LCIT Bilaspur
In the above code, we put the (.) instead of condition in 'if', so this generates the syntax error as
shown in the below screenshot.
Output
Run-time error
Sometimes the errors exist during the execution-time even after the successful compilation
known as run-time errors. When the program is running, and it is not able to perform the
operation is the main cause of the run-time error. The division by zero is the common example
of the run-time error. These errors are very difficult to find, as the compiler does not point to
these errors.
1. #include <stdio.h>
2. int main()
3. {
4. int a=2;
5. int b=2/0;
6. printf("The value of b is : %d", b);
7. return 0;
8. }
Output
In the above output, we observe that the code shows the run-time error, i.e., division by zero.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 55
CSE Department, LCIT Bilaspur
Linker error
Linker errors are mainly generated when the executable file of the program is not created. This
can be happened either due to the wrong function prototyping or usage of the wrong header file.
For example, the main.c file contains the sub() function whose declaration and definition is
done in some other file such as func.c. During the compilation, the compiler finds
the sub() function in func.c file, so it generates two object files, i.e., main.o and func.o. At the
execution time, if the definition of sub() function is not found in the func.o file, then the linker
error will be thrown. The most common linker error that occurs is that we use Main() instead
of main().
1. #include <stdio.h>
2. int Main()
3. {
4. int a=78;
5. printf("The value of a is : %d", a);
6. return 0;
7. }
Output
Logical error
The logical error is an error that leads to an undesired output. These errors produce the incorrect
output, but they are error-free, known as logical errors. These types of mistakes are mainly done
by beginners. The occurrence of these errors mainly depends upon the logical thinking of the
developer. If the programmers sound logically good, then there will be fewer chances of these
errors.
1. #include <stdio.h>
2. int main()
3. {
4. int sum=0; // variable initialization
5. int k=1;
6. for(int i=1;i<=10;i++); // logical error, as we put the semicolon after loop
7. {
8. sum=sum+k;
9. k++;
10. }
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 56
CSE Department, LCIT Bilaspur
Output
In the above code, we are trying to print the sum of 10 digits, but we got the wrong output as we
put the semicolon (;) after the for loop, so the inner statements of the for loop will not execute.
This produces the wrong output.
Semantic error
Semantic errors are the errors that occurred when the statements are not understandable by the
compiler.
1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. a=2;
6. b=3;
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 57
CSE Department, LCIT Bilaspur
7. c=1;
8. a+b=c; // semantic error
9. return 0;
10. }
In the above code, we use the statement a+b =c, which is incorrect as we cannot use the two
operands on the left-side.
Output
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 58
CSE Department, LCIT Bilaspur
C if else Statement
The if-else statement in C is used to perform the operations based on some specific condition.
The operations specified in if block are executed if and only if the given condition is true.
o If statement
o If-else statement
o If else-if ladder
o Nested if
If Statement
The if statement is used to check some given condition and perform some operations depending
upon the correctness of that condition. It is mostly used in the scenario where we need to
perform the different operations for the different conditions. The syntax of the if statement is
given below.
1. if(expression){
2. //code to be executed
3. }
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("Enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. return 0;
10. }
Output
Enter a number:4
4 is even number
enter a number:5
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 59
CSE Department, LCIT Bilaspur
1. #include <stdio.h>
2. int main()
3. {
4. int a, b, c;
5. printf("Enter three numbers?");
6. scanf("%d %d %d",&a,&b,&c);
7. if(a>b && a>c)
8. {
9. printf("%d is largest",a);
10. }
11. if(b>a && b > c)
12. {
13. printf("%d is largest",b);
14. }
15. if(c>a && c>b)
16. {
17. printf("%d is largest",c);
18. }
19. if(a == b && a == c)
20. {
21. printf("All are equal");
22. }
23. }
Output
If-else Statement
The if-else statement is used to perform two operations for a single condition. The if-else
statement is an extension to the if statement using which, we can perform two different
operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness
of the condition. Here, we must notice that if and else block cannot be executed simultaneously.
Using if-else statement is always preferable since it always invokes an otherwise case with
every if condition. The syntax of the if-else statement is given below.
1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 60
CSE Department, LCIT Bilaspur
5. }
Let's see the simple example to check whether a number is even or odd using if-else statement
in C language.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. else{
10. printf("%d is odd number",number);
11. }
12. return 0;
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 61
CSE Department, LCIT Bilaspur
13. }
Output
enter a number:4
4 is even number
enter a number:5
5 is odd number
1. #include <stdio.h>
2. int main()
3. {
4. int age;
5. printf("Enter your age?");
6. scanf("%d",&age);
7. if(age>=18)
8. {
9. printf("You are eligible to vote...");
10. }
11. else
12. {
13. printf("Sorry ... you can't vote");
14. }
15. }
Output
The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario
where there are multiple cases to be performed for different conditions. In if-else-if ladder
statement, if a condition is true then the statements defined in the if block will be executed,
otherwise if some other condition is true then the statements defined in the else-if block will be
executed, at the last if none of the condition is true then the statements defined in the else block
will be executed. There are multiple else-if blocks possible. It is similar to the switch case
statement where the default is executed instead of else block if none of the cases is matched.
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 62
CSE Department, LCIT Bilaspur
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number==10){
7. printf("number is equals to 10");
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 63
CSE Department, LCIT Bilaspur
8. }
9. else if(number==50){
10. printf("number is equal to 50");
11. }
12. else if(number==100){
13. printf("number is equal to 100");
14. }
15. else{
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
Program to calculate the grade of the student according to the specified marks.
1. #include <stdio.h>
2. int main()
3. {
4. int marks;
5. printf("Enter your marks?");
6. scanf("%d",&marks);
7. if(marks > 85 && marks <= 100)
8. {
9. printf("Congrats ! you scored grade A ...");
10. }
11. else if (marks > 60 && marks <= 85)
12. {
13. printf("You scored grade B + ...");
14. }
15. else if (marks > 40 && marks <= 60)
16. {
17. printf("You scored grade B ...");
18. }
19. else if (marks > 30 && marks <= 40)
20. {
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 64
CSE Department, LCIT Bilaspur
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 65
CSE Department, LCIT Bilaspur
C Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possible values of a single variable called switch
variable. Here, we can define various statements in the multiple cases for the different values of
a single variable.
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break statement
found in the case, all the cases will be executed present after the matched case. It is known
as fall through the state of C switch statement.
Let's try to understand it by the examples. We are assuming that there are following variables.
1. int x,y,z;
2. char a,b;
3. float f;
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 66
CSE Department, LCIT Bilaspur
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 67
CSE Department, LCIT Bilaspur
First, the integer expression specified in the switch statement is evaluated. This value is then
matched one by one with the constant values given in the different cases. If a match is found,
then all the statements specified in that case are executed along with the all the cases present
after that case including the default statement. No two cases can have similar values. If the
matched case contains a break statement, then all the cases present after that will be skipped,
and the control comes out of the switch. Otherwise, all the cases following the matched case
will be executed.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. switch(number){
7. case 10:
8. printf("number is equals to 10");
9. break;
10. case 50:
11. printf("number is equal to 50");
12. break;
13. case 100:
14. printf("number is equal to 100");
15. break;
16. default:
17. printf("number is not equal to 10, 50 or 100");
18. }
19. return 0;
20. }
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 68
CSE Department, LCIT Bilaspur
1. #include <stdio.h>
2. int main()
3. {
4. int x = 10, y = 5;
5. switch(x>y && x+y>0)
6. {
7. case 1:
8. printf("hi");
9. break;
10. case 0:
11. printf("bye");
12. break;
13. default:
14. printf(" Hello bye ");
15. }
16.
17. }
Output
hi
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 69
CSE Department, LCIT Bilaspur
If-else switch
Definition Depending on the condition in the The user will decide which statement
'if' statement, 'if' and 'else' blocks is to be executed.
are executed.
Sequence of First, the condition is checked. If It executes one case after another till
execution the condition is true then 'if' block the break keyword is not found, or the
is executed otherwise 'else' block default statement is executed.
Default If the condition is not true, then by If the value does not match with any
execution default, else block will be case, then by default, default
executed. statement is executed.
Editing Editing is not easy in the 'if-else' Cases in a switch statement are easy
statement. to maintain and modify. Therefore,
we can say that the removal or editing
of any case will not interrupt the
execution of other cases.
Speed If there are multiple choices If we have multiple choices then the
implemented through 'if-else', then switch statement is the best option as
the speed of the execution will be the speed of the execution will be
slow. much higher than 'if-else'.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 70
CSE Department, LCIT Bilaspur
C Loops
The looping can be defined as repeating the same process multiple times until a specific
condition satisfies. There are three types of loops used in the C language. In this part of the
tutorial, we are going to learn all the aspects of C loops.
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow
of the program so that instead of writing the same code again and again, we can repeat the same
code for a finite number of times. For example, if we need to print the first 10 natural numbers
then, instead of using the printf statement 10 times, we can print inside a loop which runs up to
10 iterations.
Advantage of loops in C
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked lists).
Types of C Loops
1. do while
2. while
3. for
do-while loop in C
The do-while loop continues until a given condition satisfies. It is also called post tested loop. It
is used when it is necessary to execute the loop at least once (mostly menu driven programs).
1. do{
2. //code to be executed
3. }while(condition);
while loop in C
The while loop in c is to be used in the scenario where we don't know the number of iterations
in advance. The block of statements is executed in the while loop until the condition specified in
the while loop is satisfied. It is also called a pre-tested loop.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 71
CSE Department, LCIT Bilaspur
1. while(condition){
2. //code to be executed
3. }
for loop in C
The for loop is used in the case where we need to execute some part of the code until the given
condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop
if the number of iteration is known in advance.
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 72
CSE Department, LCIT Bilaspur
while loop in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code
to be executed multiple times depending upon a given Boolean condition. It can be viewed as a
repeating if statement. The while loop is mostly used in the case where the number of iterations
is not known in advance.
1. while(condition){
2. //code to be executed
3. }
Let's see the simple program of while loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 73
CSE Department, LCIT Bilaspur
6. i++;
7. }
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
Program to print table for the given number using while loop in C
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0,b=9;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. while(i<=10){
7. printf("%d \n",(number*i));
8. i++;
9. }
10. return 0;
11. }
Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 74
CSE Department, LCIT Bilaspur
500
600
700
800
900
1000
Example 1
1. #include<stdio.h>
2. void main ()
3. {
4. int j = 1;
5. while(j+=2,j<=10)
6. {
7. printf("%d ",j);
8. }
9. printf("%d",j);
10. }
Output
3 5 7 9 11
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 75
CSE Department, LCIT Bilaspur
Example 2
1. #include<stdio.h>
2. void main ()
3. {
4. while()
5. {
6. printf("hello Javatpoint");
7. }
8. }
Output
Example 3
1. #include<stdio.h>
2. void main ()
3. {
4. int x = 10, y = 2;
5. while(x+y-1)
6. {
7. printf("%d %d",x--,y--);
8. }
9. }
Output
infinite loop
If the expression passed in while loop results in any non-zero value then the loop will run the
infinite number of times.
1. while(1){
2. //statement
3. }
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 76
CSE Department, LCIT Bilaspur
do while loop in C
The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of
several parts of the statements. The do-while loop is mainly used in the case where we need to
execute the loop at least once. The do-while loop is mostly used in menu-driven programs
where the termination condition depends upon the end user.
1. do{
2. //code to be executed
3. }while(condition);
Example 1
1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. char c;
6. int choice,dummy;
7. do{
8. printf("\n1. Print Hello\n2. Print world\n3. Exit\n");
9. scanf("%d",&choice);
10. switch(choice)
11. {
12. case 1 :
13. printf("Hello");
14. break;
15. case 2:
16. printf("World");
17. break;
18. case 3:
19. exit(0);
20. break;
21. default:
22. printf("please enter valid choice");
23. }
24. printf("do you want to enter more?");
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 77
CSE Department, LCIT Bilaspur
25. scanf("%d",&dummy);
26. scanf("%c",&c);
27. }while(c=='y');
28. }
do while example
There is given the simple program of c language do while loop where we are printing the table
of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. return 0;
9. }
Output
1
2
3
4
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 78
CSE Department, LCIT Bilaspur
5
6
7
8
9
10
Program to print table for the given number using do while loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. do{
7. printf("%d \n",(number*i));
8. i++;
9. }while(i<=10);
10. return 0;
11. }
Output
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 79
CSE Department, LCIT Bilaspur
The do-while loop will run infinite times if we pass any non-zero value as the conditional
expression.
1. do{
2. //statement
3. }while(1);
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 80
CSE Department, LCIT Bilaspur
for loop in C
The for loop in C language is used to iterate the statements or a part of the program several
times. It is frequently used to traverse the data structures like the array and linked list.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 81
CSE Department, LCIT Bilaspur
Let's see the simple program of for loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. for(i=1;i<=10;i++){
5. printf("%d \n",i);
6. }
7. return 0;
8. }
Output
1
2
3
4
5
6
7
8
9
10
C Program: Print table for the given number using C for loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. for(i=1;i<=10;i++){
7. printf("%d \n",(number*i));
8. }
9. return 0;
10. }
Output
Enter a number: 2
2
4
6
8
10
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 82
CSE Department, LCIT Bilaspur
12
14
16
18
20
Enter a number: 1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Properties of Expression 1
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. for(a=0,b=12,c=23;a<2;a++)
6. {
7. printf("%d ",a+b+c);
8. }
9. }
Output
35 36
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 83
CSE Department, LCIT Bilaspur
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int i=1;
5. for(;i<5;i++)
6. {
7. printf("%d ",i);
8. }
9. }
Output
1234
Properties of Expression 2
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int i;
5. for(i=0;i<=4;i++)
6. {
7. printf("%d ",i);
8. }
9. }
output
01234
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 84
CSE Department, LCIT Bilaspur
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int i,j,k;
5. for(i=0,j=0,k=0;i<4,k<8,j<10;i++)
6. {
7. printf("%d %d %d\n",i,j,k);
8. j+=2;
9. k+=3;
10. }
11. }
Output
000
123
246
369
4 8 12
Example 3
1. #include <stdio.h>
2. int main()
3. {
4. int i;
5. for(i=0;;i++)
6. {
7. printf("%d",i);
8. }
9. }
Output
infinite loop
Properties of Expression 3
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 85
CSE Department, LCIT Bilaspur
Example 1
1. #include<stdio.h>
2. void main ()
3. {
4. int i=0,j=2;
5. for(i = 0;i<5;i++,j=j+2)
6. {
7. printf("%d %d\n",i,j);
8. }
9. }
Output
02
14
26
38
4 10
Loop body
The braces {} are used to define the scope of the loop. However, if the loop contains only one
statement, then we don't need to use braces. A loop without a body is possible. The braces work
as a block separator, i.e., the value variable declared inside for loop is valid only for that block
and not outside. Consider the following example.
1. #include<stdio.h>
2. void main ()
3. {
4. int i;
5. for(i=0;i<10;i++)
6. {
7. int i = 20;
8. printf("%d ",i);
9. }
10. }
Output
20 20 20 20 20 20 20 20 20 20
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 86
CSE Department, LCIT Bilaspur
To make a for loop infinite, we need not give any expression in the syntax. Instead of that, we
need to provide two semicolons to validate the syntax of the for loop. This will work as an
infinite for loop.
1. #include<stdio.h>
2. void main ()
3. {
4. for(;;)
5. {
6. printf("welcome to LCIT Bilaspur");
7. }
8. }
If you run this program, you will see above statement infinite times.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 87
CSE Department, LCIT Bilaspur
Nested Loops in C
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of
statements inside another loop. Let's observe an example of nesting loops in C.
Any number of loops can be defined inside another loop, i.e., there is no restriction for defining
any number of loops. The nesting level can be defined at n times. You can define any type of
loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
1. Outer_loop
2. {
3. Inner_loop
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while'
loop.
The nested for loop means any type of loop which is defined inside the 'for' loop.
1. #include <stdio.h>
2. int main()
3. {
4. int n;// variable declaration
5. printf("Enter the value of n :");
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 88
CSE Department, LCIT Bilaspur
o First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
o The program control checks whether the condition 'i<=n' is true or not.
o If the condition is true, then the program control passes to the inner loop.
o The inner loop will get executed until the condition is true.
o After the execution of the inner loop, the control moves back to the update of the outer
loop, i.e., i++.
o After incrementing the value of the loop counter, the condition is checked again, i.e.,
i<=n.
o If the condition is true, then the inner loop will be executed again.
o This process will continue until the condition of the outer loop is true.
Output:
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 89
CSE Department, LCIT Bilaspur
The nested while loop means any type of loop which is defined inside the 'while' loop.
1. while(condition)
2. {
3. while(condition)
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
1. #include <stdio.h>
2. int main()
3. {
4. int rows; // variable declaration
5. int columns; // variable declaration
6. int k=1; // variable initialization
7. printf("Enter the number of rows :"); // input the number of rows.
8. scanf("%d",&rows);
9. printf("\nEnter the number of columns :"); // input the number of columns.
10. scanf("%d",&columns);
11. int a[rows][columns]; //2d array declaration
12. int i=1;
13. while(i<=rows) // outer loop
14. {
15. int j=1;
16. while(j<=columns) // inner loop
17. {
18. printf("%d\t",k); // printing the value of k.
19. k++; // increment counter
20. j++;
21. }
22. i++;
23. printf("\n");
24. }
25. }
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 90
CSE Department, LCIT Bilaspur
Output:
The nested do..while loop means any type of loop which is defined inside the 'do..while' loop.
1. do
2. {
3. do
4. {
5. // inner loop statements.
6. }while(condition);
7. // outer loop statements.
8. }while(condition);
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 91
CSE Department, LCIT Bilaspur
1. #include <stdio.h>
2. int main()
3. {
4. /*printing the pattern
5. ********
6. ********
7. ********
8. ******** */
9. int i=1;
10. do // outer loop
11. {
12. int j=1;
13. do // inner loop
14. {
15. printf("*");
16. j++;
17. }while(j<=8);
18. printf("\n");
19. i++;
20. }while(i<=4);
21. }
Output:
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 92
CSE Department, LCIT Bilaspur
C break statement
The break is a keyword in C which is used to bring the program control out of the loop. The
break statement is used inside loops or switch statement. The break statement breaks the loop
one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops. The break statement in C can be used in the following two scenarios:
Syntax:
Flowchart of break in c
Example
1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. int i;
6. for(i = 0; i<10; i++)
7. {
8. printf("%d ",i);
9. if(i == 5)
10. break;
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 93
CSE Department, LCIT Bilaspur
11. }
12. printf("came outside of loop i = %d",i);
13.
14. }
Output
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 94
CSE Department, LCIT Bilaspur
C continue statement
The continue statement in C language is used to bring the program control to the beginning of
the loop. The continue statement skips some lines of code inside the loop and continues with the
next iteration. It is mainly used for a condition so that we can skip some code for a particular
condition.
Syntax:
1. //loop statements
2. continue;
3. //some lines of the code which is to be skipped
Output
infinite loop
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 95
CSE Department, LCIT Bilaspur
12. }
Output
1
2
3
4
6
7
8
9
10
As you can see, 5 is not printed on the console because loop is continued at i==5.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 96
CSE Department, LCIT Bilaspur
C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is used to
transfer the program control to a predefined label. The goto statement can be used to repeat
some part of the code for a particular condition. It can also be used to break the multiple loops
which can't be done by using a single break statement. However, using goto is avoided these
days since it makes the program less readable and complicated.
Syntax:
1. label:
2. //some part of the code;
3. goto label;
goto example
1. #include <stdio.h>
2. int main()
3. {
4. int num,i=1;
5. printf("Enter the number whose table you want to print?");
6. scanf("%d",&num);
7. table:
8. printf("%d x %d = %d\n",num,i,num*i);
9. i++;
10. if(i<=10)
11. goto table;
12. }
The only condition in which using goto is preferable is when we need to break the multiple
loops using a single statement at the same time. Consider the following example.
1. #include <stdio.h>
2. int main()
3. {
4. int i, j, k;
5. for(i=0;i<10;i++)
6. {
7. for(j=0;j<5;j++)
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 97
CSE Department, LCIT Bilaspur
8. {
9. for(k=0;k<3;k++)
10. {
11. printf("%d %d %d\n",i,j,k);
12. if(j == 3)
13. {
14. goto out;
15. }
16. }
17. }
18. }
19. out:
20. printf("came out of the loop");
21. }
000
001
002
010
011
012
020
021
022
030
came out of the loop
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 98
CSE Department, LCIT Bilaspur
C Functions
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known as procedure
or subroutine in other programming languages.
Advantage of functions in C
There are the following advantages of C functions.
o By using functions, we can avoid rewriting same logic/code again and again in a program.
o We can call C functions any number of times in a program and from any place in a program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
Function Aspects
There are three aspects of a C function.
o Function declaration A function must be declared globally in a c program to tell the compiler
about the function name, function parameters, and return type.
o Function call Function can be called from anywhere in the program. The parameter list must not
differ in function calling and function declaration. We must pass the same number of functions
as it is declared in the function declaration.
o Function definition It contains the actual statements which are to be executed. It is the most
important aspect to which the control comes when the function is called. Here, we must notice
that only one value can be returned from the function.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 99
CSE Department, LCIT Bilaspur
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C header files such as scanf(),
printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so that
he/she can use it many times. It reduces the complexity of a big program and optimizes the code.
Return Value
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 100
CSE Department, LCIT Bilaspur
Let's see a simple example of C function that doesn't return any value from the function.
1. void hello(){
2. printf("hello c");
3. }
If you want to return any value from the function, you need to use any data type such as int,
long, char, etc. The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the function.
1. int get(){
2. return 10;
3. }
In the above example, we have to return 10 as a value, so the return type is int. If you want to
return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of
the method.
1. float get(){
2. return 10.2;
3. }
Now, you need to call the function, to get the value of the function.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 101
CSE Department, LCIT Bilaspur
1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("Javatpoint");
11. }
Output
Hello Javatpoint
Example 2
1. #include<stdio.h>
2. void sum();
3. void main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }
Output
The sum is 34
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 102
CSE Department, LCIT Bilaspur
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. int result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. result = sum();
8. printf("%d",result);
9. }
10. int sum()
11. {
12. int a,b;
13. printf("\nEnter two numbers");
14. scanf("%d %d",&a,&b);
15. return a+b;
16. }
Output
The sum is 34
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area);
8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 103
CSE Department, LCIT Bilaspur
13. scanf("%f",&side);
14. return side * side;
15. }
Output
1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }
Output
The sum is 34
1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 104
CSE Department, LCIT Bilaspur
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }
Output
1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }
Output
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 105
CSE Department, LCIT Bilaspur
1. #include<stdio.h>
2. int even_odd(int);
3. void main()
4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("%d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18. }
19. int even_odd(int n)
20. {
21. if(n%2 == 0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }
Output
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place
called the library. Such functions are used to perform some specific operations. For example,
printf is a library function used to print on the console. The library functions are created by the
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 106
CSE Department, LCIT Bilaspur
designers of compilers. All C standard library functions are defined inside the different header
files saved with the extension .h. We need to include these header files in our program to make
use of the library functions defined in such header files. For example, To use the library
functions such as printf/scanf we need to include stdio.h in our program which is a header file
that contains all the library functions regarding standard input/output.
The list of mostly used header files is given in the following table.
SN Header Description
file
1 stdio.h This is a standard input/output header file. It contains all the library functions
regarding standard input/output.
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(),
calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions like sqrt(),
pow(), etc.
9 signal.h All the signal handling functions are defined in this header file.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 107
CSE Department, LCIT Bilaspur
Let's understand call by value and call by reference in c language one by one.
Call by value in C
o In call by value method, the value of the actual parameters is copied into the formal parameters.
In other words, we can say that the value of the variable is used in the function call in the call by
value method.
o In call by value method, we can not modify the value of the actual parameter by the formal
parameter.
o In call by value, different memory is allocated for actual and formal parameters since the value
of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given below:
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 108
CSE Department, LCIT Bilaspur
Output
1. #include <stdio.h>
2. void swap(int , int); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in
main
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not
change by changing the formal parameters in call by value, a = 10, b = 20
10. }
11. void swap (int a, int b)
12. {
13. int temp;
14. temp = a;
15. a=b;
16. b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 10
18. }
Output
Call by reference in C
o In call by reference, the address of the variable is passed into the function call as the actual
parameter.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 109
CSE Department, LCIT Bilaspur
o The value of the actual parameters can be modified by changing the formal parameters since the
address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the address of
the actual parameters, and the modified value gets stored at the same address.
1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in
main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do c
hange in call by reference, a = 10, b = 20
10. }
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 110
CSE Department, LCIT Bilaspur
Output
1 A copy of the value is passed into the An address of value is passed into the function
function
2 Changes made inside the function is Changes made inside the function validate
limited to the function only. The values outside of the function also. The values of the
of the actual parameters do not change actual parameters do change by changing the
by changing the formal parameters. formal parameters.
3 Actual and formal arguments are created Actual and formal arguments are created at the
at the different memory location same memory location
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 111
CSE Department, LCIT Bilaspur
C Array
An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc. It also has the capability to store the
collection of derived data types, such as pointers, structure, etc. The array is the simplest data
structure where each data element can be randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to store the
marks of a student in 6 subjects, then we don't need to define different variables for the marks in
the different subject. Instead of that, we can define an array which can store the marks in each
subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are required to
access the elements of the array.
Properties of Array
o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element is stored
at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
Advantage of C Array
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed
the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.
Declaration of C Array
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 112
CSE Department, LCIT Bilaspur
1. data_type array_name[array_size];
1. int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index. Consider the following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 113
CSE Department, LCIT Bilaspur
Output
80
60
70
85
75
We can initialize the c array at the time of declaration. Let's see the code.
1. int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the
following code.
1. int marks[]={20,30,40,50,60};
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output
20
30
40
50
60
In the following program, we are using bubble sort method to sort the array in ascending order.
1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 114
CSE Department, LCIT Bilaspur
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }
Program to print the largest and second largest element of the array.
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 115
CSE Department, LCIT Bilaspur
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28. }
data_type array_name[rows][columns];
int twodimen[4][3];
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization
are being done simultaneously. However, this will not work with 2D arrays. We will have to
define at least the second dimension of the array. The two-dimensional array can be declared
and defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 116
CSE Department, LCIT Bilaspur
Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and
such function calls are called recursive calls. Recursion involves several numbers of recursive
calls. However, it is important to impose a termination condition of recursion. Recursion code is
shorter than iterative code however it is difficult to understand.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting,
searching, and traversal problems.
Generally, iterative solutions are more efficient than recursion since function call is always
overhead. Any problem that can be solved recursively, can also be solved iteratively. However,
some problems are best suited to be solved by the recursion, for example, tower of Hanoi,
Fibonacci series, factorial finding, etc.
1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 1;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 117
CSE Department, LCIT Bilaspur
22. {
23. return n*fact(n-1);
24. }
25. }
Output
We can understand the above program of the recursive method call by the figure given below:
Recursive Function
A recursive function performs the tasks by dividing it into the subtasks. There is a termination
condition defined in the function which is satisfied by some specific subtask. After this, the
recursion stops and the final result is returned from the function.
The case at which the function doesn't recur is called the base case whereas the instances where
the function keeps calling itself to perform a subtask, is called the recursive case. All the
recursive functions can be written using this format.
1. if (test_for_base)
2. {
3. return some_value;
4. }
5. else if (test_for_another_base)
6. {
7. return some_another_value;
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 118
CSE Department, LCIT Bilaspur
8. }
9. else
10. {
11. // Statements;
12. recursive call;
13. }
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25. }
Output
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 119
CSE Department, LCIT Bilaspur
C Pointers
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. The size of the pointer
depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.
1. int n = 10;
2. int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
Pointer Example
An example of using pointers to print the address and value is given below.
As you can see in the above figure, pointer variable stores the address of number variable, i.e.,
fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Let's see the pointer example as explained for the above figure.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;
5. p=&number;//stores the address of number variable
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 120
CSE Department, LCIT Bilaspur
6. printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printing p giv
es the address of number.
7. printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer therefore i
f we print *p, we will get the value stored at the address contained by p.
8. return 0;
9. }
Output
Pointer to array
1. int arr[10];
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array arr.
Pointer to a function
Pointer to structure
1. struct st {
2. int i;
3. float f;
4. }ref;
5. struct st *p = &ref;
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings,
trees, etc. and used with arrays, structures, and functions.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 121
CSE Department, LCIT Bilaspur
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
the pointer is used.
Pointers in c language are widely used in arrays, functions, and structures. It reduces the code
and improves the performance.
The address of operator '&' returns the address of a variable. But, we need to use %u to display
the address of a variable.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. printf("value of number is %d, address of number is %u",number,&number);
5. return 0;
6. }
Output
NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't
have any address to be specified in the pointer at the time of declaration, you can assign NULL
value. It will provide a better approach.
int *p=NULL;
Pointer Program to swap two numbers without using the 3rd variable.
1. #include<stdio.h>
2. int main(){
3. int a=10,b=20,*p1=&a,*p2=&b;
4.
5. printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
6. *p1=*p1+*p2;
7. *p2=*p1-*p2;
8. *p1=*p1-*p2;
9. printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
10.
11. return 0;
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 122
CSE Department, LCIT Bilaspur
12. }
Output
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 123
CSE Department, LCIT Bilaspur
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.
Memory can't be increased while executing Memory can be increased while executing
program. program.
Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() function in C
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 124
CSE Department, LCIT Bilaspur
ptr=(cast-type*)malloc(byte-size)
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
Output
calloc() function in C
The calloc() function allocates multiple block of requested memory.
ptr=(cast-type*)calloc(number, byte-size)
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 125
CSE Department, LCIT Bilaspur
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main()
4. {
5. int n,i,*ptr,sum=0;
6. printf("Enter number of elements: ");
7. scanf("%d",&n);
8. ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
9. if(ptr==NULL)
10. {
11. printf("Sorry! unable to allocate memory");
12. exit(0);
13. }
14. printf("Enter elements of array: ");
15. for(i=0;i<n;++i)
16. {
17. scanf("%d",ptr+i);
18. sum+=*(ptr+i);
19. }
20. printf("Sum=%d",sum);
21. free(ptr);
22. return 0;
23. }
Output
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.
ptr=realloc(ptr, new-size)
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 126
CSE Department, LCIT Bilaspur
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until program exit.
free(ptr)
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 127
CSE Department, LCIT Bilaspur
C Strings
The string can be defined as the one-dimensional array of characters terminated by a null ('\0').
The character array or the string is used to manipulate text such as word or sentences. Each
character in the array occupies one byte of memory, and the last character must always be 0.
The termination character ('\0') is important in a string since it is the only way to identify where
the string ends. When we define a string as char s[10], the character s[10] is implicitly
initialized with the null in the memory.
1. By char array
2. By string literal
char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given below.
While declaring string, size is not mandatory. So we can write the above code as given below:
1. char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
We can also define the string by the string literal in C language. For example:
1. char ch[]="javatpoint";
In such case, '\0' will be appended at the end of the string by the compiler.
o We need to add the null character '\0' at the end of the array by ourself whereas, it is appended
internally by the compiler in the case of the character array.
o The string literal cannot be reassigned to another set of characters whereas, we can reassign the
characters of the array.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 128
CSE Department, LCIT Bilaspur
String Example in C
Let's see a simple example where a string is declared and being printed. The '%s' is used as a
format specifier for the string in c language.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[11]="javatpoint";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10. }
Output
Traversing String
Traversing the string is one of the most important aspects in any of the programming languages.
We may need to manipulate a very large text which can be done by traversing the text.
Traversing string is somewhat different from the traversing an integer array. We need to know
the length of the array to traverse an integer array, whereas we may use the null character in the
case of string to identify the end the string and terminate the loop.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "javatpoint";
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 129
CSE Department, LCIT Bilaspur
5. int i = 0;
6. int count = 0;
7. while(i<11)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }
Output
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "javatpoint";
5. int i = 0;
6. int count = 0;
7. while(s[i] != NULL)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }
Output
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 130
CSE Department, LCIT Bilaspur
Till now, we have used scanf to accept the input from the user. However, it can also be used in
the case of strings but with a different scenario. Consider the below code which stores the string
while space is encountered.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[20];
5. printf("Enter the string?");
6. scanf("%s",s);
7. printf("You entered %s",s);
8. }
Output
It is clear from the output that, the above code will not work for space separated strings. To
make this code working for the space separated strings, the minor changed required in the scanf
function, i.e., instead of writing scanf("%s",s), we must write: scanf("%[^\n]s",s) which
instructs the compiler to store the string s while the new line (\n) is encountered. Let's consider
the following example to store the space-separated strings.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[20];
5. printf("Enter the string?");
6. scanf("%[^\n]s",s);
7. printf("You entered %s",s);
8. }
Output
Here we must also notice that we do not need to use address of (&) operator in scanf to store a
string since string s is an array of characters and the name of the array, i.e., s indicates the base
address of the string (character array) therefore we need not use & with it.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 131
CSE Department, LCIT Bilaspur
o The compiler doesn't perform bounds checking on the character array. Hence, there can be a case
where the length of the string can exceed the dimension of the character array which may always
overwrite some important data.
o Instead of using scanf, we may use gets() which is an inbuilt function defined in a header file
string.h. The gets() is capable of receiving only one string at a time.
We have used pointers with the array, functions, and primitive data types so far. However,
pointers can be used to point to the strings. There are various advantages of using pointers to
point strings. Let us consider the following example to access the string via the pointer.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "world";
5. char *p = s; // pointer p is pointing to string s.
6. printf("%s",p); // the string javatpoint is printed if we print p.
7. }
Output
world
1. #include<stdio.h>
2. void main ()
3. {
4. char *p = "hello javatpoint";
5. printf("String p: %s\n",p);
6. char *q;
7. printf("copying the content of p into q...\n");
8. q = p;
9. printf("String q: %s\n",q);
10. }
Once a string is defined, it cannot be reassigned to another set of characters. However, using
pointers, we can assign the set of characters to the string. Consider the following example.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 132
CSE Department, LCIT Bilaspur
1. #include<stdio.h>
2. void main ()
3. {
4. char *p = "hello javatpoint";
5. printf("Before assigning: %s\n",p);
6. p = "hello";
7. printf("After assigning: %s\n",p);
8. }
C String Functions
There are many important string functions defined in "string.h" library.
3) strcat(first_string, concats or joins first string with second string. The result of the
second_string) string is stored in first string.
4) strcmp(first_string, compares the first string with second string. If both strings are
second_string) same, it returns 0.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 133
CSE Department, LCIT Bilaspur
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[20];
6. strcpy(ch2,ch);
7. printf("Value of second string is: %s",ch2);
8. return 0;
9. }
Output:
The strcat(first_string, second_string) function concatenates two strings and result is returned to
first_string.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }
Output:
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 134
CSE Department, LCIT Bilaspur
The strcmp(first_string, second_string) function compares two string and returns 0 if both
strings are equal.
Here, we are using gets() function which reads string from the console.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10. }
Output:
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 135
CSE Department, LCIT Bilaspur
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main()
4. {
5. char str[20];
6. printf("Enter string: ");
7. gets(str);//reads string from console
8. printf("String is: %s",str);
9. printf("\nUpper String is: %s",strupr(str));
10. return 0;
11. }
Output:
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 136
CSE Department, LCIT Bilaspur
C String strstr()
The strstr() function returns pointer to the first occurrence of the matched string in the given
string. It is used to return substring from first match till the last character.
Syntax:
Output:
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 137
CSE Department, LCIT Bilaspur
C Math
C Programming allows us to perform mathematical operations through the functions defined in
<math.h> header file. The <math.h> header file contains various methods for performing
mathematical operations such as sqrt(), pow(), ceil(), floor() etc.
C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h
header file are given below.
1) ceil(number) rounds up the given number. It returns the integer value which is greater
than or equal to given number.
2) floor(number) rounds down the given number. It returns the integer value which is less
than or equal to given number.
C Math Example
Let's see a simple example of math functions found in math.h header file.
1. #include<stdio.h>
2. #include <math.h>
3. int main(){
4. printf("\n%f",ceil(3.6));
5. printf("\n%f",ceil(3.3));
6. printf("\n%f",floor(3.6));
7. printf("\n%f",floor(3.2));
8. printf("\n%f",sqrt(16));
9. printf("\n%f",sqrt(7));
10. printf("\n%f",pow(2,4));
11. printf("\n%f",pow(3,3));
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 138
CSE Department, LCIT Bilaspur
12. printf("\n%d",abs(-12));
13. return 0;
14. }
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 139
CSE Department, LCIT Bilaspur
C Structure
Why use structure?
In C, there are cases where we need to store multiple attributes of an entity. It is not necessary
that an entity has all the information of one type only. It can have different attributes of different
data types. For example, an entity Student may have its name (string), roll number (int), marks
(float). To store such type of information regarding an entity student, we have the following
approaches:
o Construct individual arrays for storing names, roll numbers, and marks.
o Use a special data structure to store the collection of different data types.
1. #include<stdio.h>
2. void main ()
3. {
4. char names[2][10],dummy; // 2-
dimensioanal character array names is used to store the names of the students
5. int roll_numbers[2],i;
6. float marks[2];
7. for (i=0;i<3;i++)
8. {
9.
10. printf("Enter the name, roll number, and marks of the student %d",i+1);
11. scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]);
12. scanf("%c",&dummy); // enter will be stored into dummy character at each iteration
13. }
14. printf("Printing the Student details ...\n");
15. for (i=0;i<3;i++)
16. {
17. printf("%s %d %f\n",names[i],roll_numbers[i],marks[i]);
18. }
19. }
Output
Enter the name, roll number, and marks of the student 1Arun 90 91
Enter the name, roll number, and marks of the student 2Varun 91 56
Enter the name, roll number, and marks of the student 3Sham 89 69
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 140
CSE Department, LCIT Bilaspur
Varun 91 56.000000
Sham 89 69.000000
The above program may fulfill our requirement of storing the information of an entity student.
However, the program is very complex, and the complexity increase with the amount of the
input. The elements of each of the array are stored contiguously, but all the arrays may not be
stored contiguously in the memory. C provides you with an additional and simpler approach
where you can use a special data structure, i.e., structure, in which, you can group all the
information of different data type regarding an entity.
What is Structure
Structure in c is a user-defined data type that enables us to store the collection of different data
types. Each element of a structure is called a member. Structures ca; simulate the use of classes
and templates as it can store various information
The ,struct keyword is used to define the structure. Let's see the syntax to define the structure in
c.
1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
1. struct employee
2. { int id;
3. char name[20];
4. float salary;
5. };
The following image shows the memory allocation of the structure employee that is defined in
the above example.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 141
CSE Department, LCIT Bilaspur
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are
the members or fields of the structure. Let's understand it by the diagram given below:
We can declare a variable for the structure so that we can access the member of the structure
easily. There are two ways to declare structure variable:
1st way:
Let's see the example to declare the structure variable by struct keyword. It should be declared
within the main function.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 142
CSE Department, LCIT Bilaspur
5. };
The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2
can be treated in the same way as the objects in C++ and Java.
2nd way:
Let's see another way to declare variable at the time of defining the structure.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. }e1,e2;
If number of variables are not fixed, use the 1st approach. It provides you the flexibility to
declare the structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in main()
function.
Let's see the code to access the id member of p1 variable by. (member) operator.
1. p1.id
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 143
CSE Department, LCIT Bilaspur
C Structure example
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for structure
7. int main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
Let's see another example of the structure in C language to store many employees information.
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. float salary;
7. }e1,e2; //declaring e1 and e2 variables for structure
8. int main( )
9. {
10. //store first employee information
11. e1.id=101;
12. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
13. e1.salary=56000;
14.
15. //store second employee information
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 144
CSE Department, LCIT Bilaspur
16. e2.id=102;
17. strcpy(e2.name, "James Bond");
18. e2.salary=126000;
19.
20. //printing first employee information
21. printf( "employee 1 id : %d\n", e1.id);
22. printf( "employee 1 name : %s\n", e1.name);
23. printf( "employee 1 salary : %f\n", e1.salary);
24.
25. //printing second employee information
26. printf( "employee 2 id : %d\n", e2.id);
27. printf( "employee 2 name : %s\n", e2.name);
28. printf( "employee 2 salary : %f\n", e2.salary);
29. return 0;
30. }
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000
C Array of Structures
Why use an array of structures?
Consider a case, where we need to store the data of 5 students. We can store it by using the
structure as given below.
1. #include<stdio.h>
2. struct student
3. {
4. char name[20];
5. int id;
6. float marks;
7. };
8. void main()
9. {
10. struct student s1,s2,s3;
11. int dummy;
12. printf("Enter the name, id, and marks of student 1 ");
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 145
CSE Department, LCIT Bilaspur
Output
In the above program, we have stored data of 3 students in the structure. However, the
complexity of the program will be increased if there are 20 students. In that case, we will have
to declare 20 different structure variables and store them one by one. This will always be tough
since we will have to declare a variable every time we add a student. Remembering the name of
all the variables is also a very tricky task. However, c enables us to declare an array of
structures by using which, we can avoid declaring the different structure variables; instead we
can make a collection containing all the structures that store the information of different entities.
Array of Structures in C
An array of structres in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities. The array of structures in C are used
to store information about multiple entities of different data types. The array of structures is also
known as the collection of structures.
mation about multiple entities of different data types. The array of structures is also known as
the collection of structures.Play Video
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 146
CSE Department, LCIT Bilaspur
Let's see an example of an array of structures that stores information of 5 students and prints it.
1. #include<stdio.h>
2. #include <string.h>
3. struct student{
4. int rollno;
5. char name[10];
6. };
7. int main(){
8. int i;
9. struct student st[5];
10. printf("Enter Records of 5 students");
11. for(i=0;i<5;i++){
12. printf("\nEnter Rollno:");
13. scanf("%d",&st[i].rollno);
14. printf("\nEnter Name:");
15. scanf("%s",&st[i].name);
16. }
17. printf("\nStudent Information List:");
18. for(i=0;i<5;i++){
19. printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
20. }
21. return 0;
22. }
Output:
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 147
CSE Department, LCIT Bilaspur
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Union in C
Union can be defined as a user-defined data type which is a collection of different variables of
different data types in the same memory location. The union can also be defined as many
members, but only one member can contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory location.
1. struct abc
2. {
3. int a;
4. char b;
5. }
The above code is the user-defined structure that consists of two members, i.e., 'a' of
type int and 'b' of type character. When we check the addresses of 'a' and 'b', we found that
their addresses are different. Therefore, we conclude that the members in the structure do not
share the same memory location.
When we define the union, then we found that union is defined in the same way as the structure is
defined but the difference is that union keyword is used for defining the union data type, whereas the
struct keyword is used for defining the structure. The union contains the data members, i.e., 'a' and 'b',
when we check the addresses of both the variables then we found that both have the same addresses. It
means that the union members share the same memory location.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 148
CSE Department, LCIT Bilaspur
File Handling in C
In programming, we may require some specific input data to be generated several numbers of
times. Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on the console,
and since the memory is volatile, it is impossible to recover the programmatically generated
data again and again. However, if we need to do so, we may store it onto the local file system
which is volatile and can be accessed every time. Here, comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.
There are many functions in the C library to open, read, write, search and close the file. A list of
file functions are given below:
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 149
CSE Department, LCIT Bilaspur
We must open a file before it can be read, write, or update. The fopen() function is used to open
a file. The syntax of the fopen() is given below.
o The file name (string). If the file is stored at some specific location, then we must mention the
path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.
Mode Description
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 150
CSE Department, LCIT Bilaspur
1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
11. break ;
12. printf("%c",ch) ;
13. }
14. fclose (fp ) ;
15. }
Output
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 151
CSE Department, LCIT Bilaspur
#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:
Types of Files
There are two types of files in C language which are as follows −
Text file
Binary File
Text File
It contains alphabets and numbers which are easily understood by human beings.
An error in a text file can be eliminated when seen.
In text file, the text and characters will store one char per byte.
For example, the integer value 4567 will occupy 2 bytes in memory, but, it will occupy 5
bytes in text file.
The data format is usually line-oriented. Here, each line is a separate command.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 152
CSE Department, LCIT Bilaspur
Binary file
It contains 1’s and 0’s, which are easily understood by computers.
The error in a binary file corrupts the file and is not easy to detect.
In binary file, the integer value 1245 will occupy 2 bytes in memory and in file.
A binary file always needs a matching software to read or write it.
For example, an MP3 file can be produced by a sound recorder or audio editor, and it can
be played in a music player.
MP3 file will not play in an image viewer or a database software.
Prepared by: Mr. Bharat Choudhary, Asst. Prof. CSE Dept. Page 153