Pps Notes (4 Files Merged)
Pps Notes (4 Files Merged)
Pps Notes (4 Files Merged)
A computer is an electronic device that accepts data, performs operations, displays results, and stores the
data or results as needed. It is a combination of hardware and software resources that integrate together
and provides various functionalities to the user. Hardware is the physical components of a computer like a
processor, memory devices, monitor, keyboard, etc., while software is a set of programs or instructions
that are required by the hardware resources to function properly.
Components of a Computer
There are basically three important components of a computer:
1. Input Unit
2. Central Processing Unit(CPU)
3. Output Unit
1. Input Unit:
The input unit consists of input devices that are attached to the computer. These devices take input and
convert it into binary language that the computer understands. Some of the common input devices are
keyboard, mouse, joystick, scanner etc.
The Input Unit is formed by attaching one or more input devices to a computer.
A user input data and instructions through input devices such as a keyboard, mouse, etc.
The input unit is used to provide data to the processor for further processing.
B. Control Unit: The Control unit coordinates and controls the data flow in and out of the CPU, and also
controls all the operations of ALU, memory registers and also input/output units. It is also responsible for
carrying out all the instructions stored in the program. It decodes the fetched instruction, interprets it and
sends control signals to input/output devices until the required operation is done properly by ALU and
memory.
The Control Unit is a component of the central processing unit of a computer that directs the
operation of the processor.
It instructs the computer’s memory, arithmetic and logic unit, and input and output devices on
how to respond to the processor’s instructions.
In order to execute the instructions, the components of a computer receive signals from the
control unit.
It is also called the central nervous system or brain of the computer.
C. Memory Registers: A register is a temporary unit of memory in the CPU. These are used to store the
data, which is directly used by the processor. Registers can be of different sizes(16 bit, 32 bit, 64 bit and
so on) and each register inside the CPU has a specific function, like storing data, storing an instruction,
storing address of a location in memory etc. The user registers can be used by an assembly language
programmer for storing operands, intermediate results etc. Accumulator (ACC) is the main register in the
ALU and contains one of the operands of an operation to be performed in the ALU.
Memory attached to the CPU is used for the storage of data and instructions, and is called internal
memory The internal memory is divided into many storage locations, each of which can store data or
instructions. Each memory location is of the same size and has an address. With the help of the address,
the computer can read any memory location easily without having to search the entire memory. When a
program is executed, its data is copied to the internal memory and stored in the memory till the end of the
execution. The internal memory is also called the Primary memory or Main memory. This memory is also
called RAM, i.e., Random Access Memory. The time of access of data is independent of its location in
memory, therefore, this memory is also called Random Access memory (RAM).
Memory Unit is the primary storage of the computer.
It stores both data and instructions.
Data and instructions are stored permanently in this unit so that they are available whenever
required.
3. Output Unit :
The output unit consists of output devices that are attached to the computer. It converts the binary data
coming from the CPU to human understandable form. The common output devices are monitor, printer,
plotter, etc.
The output unit displays or prints the processed data in a user-friendly format.
The output unit is formed by attaching the output devices of a computer.
The output unit accepts the information from the CPU and displays it in a user-readable form.
Characteristics of a Computer
1. Speed: Computers can perform millions of calculations per second. The computation speed is
extremely fast.
2. Accuracy: Because computers operate on pre-programmed software, there is no space for human error.
3. Diligence: They can perform complex and long calculations at the same time and with the same
accuracy.
4. Versatile: Computers are designed to be versatile. They can carry out multiple operations at the same
time.
5. Storage: Computers can store a large amount of data/ instructions in its memory, which can be
retrieved at any point of time.
Computer Memory
A memory is just like a human brain. It is used to store data and instructions. Computer memory is the
storage space in the computer, where data is to be processed and instructions required for processing are
stored. The memory is divided into large number of small parts called cells. Each location or cell has a
unique address, which varies from zero to memory size minus one. For example, if the computer has 64k
words, then this memory unit has 64 * 1024 = 65536 memory locations. The address of these locations
varies from 0 to 65535.
Memory is primarily of three types −
Cache Memory
Primary Memory/Main Memory
Secondary Memory
Cache Memory
Cache memory is a very high speed semiconductor memory which can speed up the CPU. It acts as a
buffer between the CPU and the main memory. It is used to hold those parts of data and program which
are most frequently used by the CPU. The parts of data and programs are transferred from the disk to
cache memory by the operating system, from where the CPU can access them.
Advantages
The advantages of cache memory are as follows −
Secondary Memory
This type of memory is also known as external memory or non-volatile. It is slower than the main
memory. These are used for storing data/information permanently. CPU directly does not access these
memories, instead they are accessed via input-output routines. The contents of secondary memories are
first transferred to the main memory, and then the CPU can access it. For example, disk, CD-ROM, DVD,
etc.
Characteristics of Secondary Memory
These are magnetic and optical memories.
It is known as the backup memory.
It is a non-volatile memory.
Data is permanently stored even if power is switched off.
It is used for storage of data in a computer.
Computer may run without the secondary memory.
Slower than primary memories.
What is an Algorithm?
In computer programming terms, an algorithm is a set of well-defined instructions to solve a particular
problem. It takes a set of input(s) and produces the desired output. For example,
Algorithms should be most effective among many different ways to solve a problem.
An algorithm shouldn't include computer code. Instead, the algorithm should be written in such a
way that it can be used in different programming languages.
Algorithm Examples
Step 1: Start
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 6: Stop
Algorithm 2: Find the largest number among three numbers
Step 1: Start
Step 4: If a > b
If a > c
Else
Else
If b > c
Else
Step 5: Stop
Flowchart In Programming
A flowchart is a diagrammatic representation of an algorithm. A flowchart can be helpful for both writing
programs and explaining the program to others.
2. Find the largest among three different numbers entered by the user.
Flowchart to find the largest among three numbers.
Types of Errors in C
There are five different types of errors in C.
1. Syntax Error
2. Run Time Error
3. Logical Error
4. Semantic Error
5. Linker Error
1. Syntax Error
Syntax errors occur when a programmer makes mistakes in typing the code's syntax correctly or
makes typos. In other words, syntax errors occur when a programmer does not follow the set of
rules defined for the syntax of C language.
Syntax errors are sometimes also called compilation errors because they are always detected by
the compiler. Generally, these errors can be easily identified and rectified by programmers.
#include <stdio.h>
void main() {
var = 5; // we did not declare the data type of variable
Output:
If the user assigns any value to a variable without defining the data type of the variable, the
compiler throws a syntax error.
#include <stdio.h>
void main() {
Output:
A for loop needs 3 arguments to run. Since we entered only one argument, the compiler threw a
syntax error.
2. Runtime Error
Errors that occur during the execution (or running) of a program are called RunTime Errors.
These errors occur after the program has been compiled successfully. When a program is
running, and it is not able to perform any particular operation, it means that we have encountered
a run time error. For example, while a certain program is running, if it encounters the square root
of -1 in the code, the program will not be able to generate an output because calculating the
square root of -1 is not possible. Hence, the program will produce an error.
Runtime errors can be a little tricky to identify because the compiler can not detect these errors.
They can only be identified once the program is running. Some of the most common run time
errors are: number not divisible by zero, array index out of bounds, string index out of bounds,
etc.
Runtime errors can occur because of various reasons. Some of the reasons are:
1. Mistakes in the Code: Let us say during the execution of a while loop, the programmer forgets
to enter a break statement. This will lead the program to run infinite times, hence resulting in a
run time error.
2. Memory Leaks: If a programmer creates an array in the heap but forgets to delete the array's
data, the program might start leaking memory, resulting in a run time error.
3. Mathematically Incorrect Operations: Dividing a number by zero, or calculating the square root
of -1 will also result in a run time error.
4. Undefined Variables: If a programmer forgets to define a variable in the code, the program will
generate a run time error.
Example 1:
int main() {
for (int i = 4; i >= -2; i--) {
printf("%f", sqrt(i));
printf("\n");
}
return 0;
}
Output:
2.000000
1.732051
1.414214
1.000000
0.000000
-1.#IND00
-1.#IND00
2.000000
1.732051
1.414214
1.000000
0.000000
-nan
-nan
In the above example, we used a for loop to calculate the square root of six integers. But because
we also tried calculating the square root of two negative numbers, the program generated two
errors (the IND written above stands for "Indeterminate"). These errors are the run time errors. -
nan is similar to IND.
Example 2:
#include<stdio.h>
void main() {
int var = 2147483649;
printf("%d", var);
}
Output:
-2147483647
This is an integer overflow error. The maximum value an integer can hold in C is 2147483647.
Since in the above example, we assigned 2147483649 to the variable var, the variable overflows,
and we get -2147483647 as the output (because of the circular property).
3. Logical Error
Sometimes, we do not get the output we expected after the compilation and execution of a
program. Even though the code seems error free, the output generated is different from the
expected one. These types of errors are called Logical Errors. Logical errors are those errors in
which we think that our code is correct, the code compiles without any error and gives no error
while it is running, but the output we get is different from the output we expected.
In 1999, NASA lost a spacecraft due to a logical error. This happened because of some
miscalculations between the English and the American Units. The software was coded to work
for one system but was used with the other.
For Example:
#include <stdio.h>
void main() {
float a = 10;
float b = 5;
if (b = 0) { // we wrote = instead of ==
printf("Division by zero is not possible");
} else {
printf("The output is: %f", a/b);
}
}
Output:
INF signifies a division by zero error. In the above example, at line 8, we wanted to check
whether the variable b was equal to zero. But instead of using the equal to comparison
operator (==), we use the assignment operator (=). Because of this, the if statement became false
and the value of b became 0. Finally, the else clause got executed.
4. Semantic Error
Errors that occur because the compiler is unable to understand the written code are called
Semantic Errors. A semantic error will be generated if the code makes no sense to the compiler,
even though it is syntactically correct. It is like using the wrong word in the wrong place in the
English language. For example, adding a string to an integer will generate a semantic error.
Semantic errors are different from syntax errors, as syntax errors signify that the structure of a
program is incorrect without considering its meaning. On the other hand, semantic errors signify
the incorrect implementation of a program by considering the meaning of the program.
The most commonly occurring semantic errors are: use of un-initialized variables, type
compatibility, and array index out of bounds.
Example 1:
#include <stdio.h>
void main() {
int a, b, c;
a * b = c;
// This will generate a semantic error
}
Output:
When we have an expression on the left-hand side of an assignment operator (=), the program
generates a semantic error. Even though the code is syntactically correct, the compiler does not
understand the code.
Example 2:
#include <stdio.h>
void main() {
int arr[5] = {5, 10, 15, 20, 25};
Output:
5
10
15
20
25
32764
In the above example, we printed six elements while the array arr only had five. Because we
tried to access the sixth element of the array, we got a semantic error and hence, the program
generated a garbage value.
5. Linker Error
Linker is a program that takes the object files generated by the compiler and combines them into
a single executable file. Linker errors are the errors encountered when the executable file of the
code can not be generated even though the code gets compiled successfully. This error is
generated when a different object file is unable to link with the main object file. We can run into
a linked error if we have imported an incorrect header file in the code, we have a wrong function
declaration, etc.
For Example:
#include <stdio.h>
void Main() {
int var = 10;
printf("%d", var);
}
Output:
In the above code, as we wrote Main() instead of main(), the program generated a linker error.
This happens because every file in the C language must have a main() function. As in the above
program, we did not have a main() function, the program was unable to run the code, and we got
an error. This is one of the most common type of linker error.
Both compilers and interpreters are the language processors used to convert software codes written in
high-level language into machine language codes. Compilers and interpreters are types of system
software. They are required because a computer cannot process a code written in high-level
programming language like C, C++, Java, etc. Therefore, we convert a HLL code into machine code for
execution.
What is a Compiler?
A compiler is a translator that produces an output of low-level language (like an
assembly or machine language) by taking an input of high-level language. It is basically
a computer program used to transform codes written in a programming language into
machine code (human-readable code to a binary 0 and 1 bits language for a computer
processor to understand). The computer then processes the machine code for
performing the corresponding tasks.
Compilers check all types of errors, limits, and ranges. Thus, it’s more intelligent.
The run time of its program is longer, and it occupies more memory.
What Is an Interpreter?
It is a program that functions for the translation of a programming language into a
comprehensible one. It is a computer program used for converting high-level program
statements into machine codes. It includes pre-compiled code, source code, and
scripts.
Advantage The code execution time is They are fairly easy to use and execute, even
comparatively less because the 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.
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 comparatively The interpreted codes run comparatively slower.
faster.
Model It works on the basis of the language- It works on the basis of the Interpretation
translation linking-loading model. method.
Generation of It generates an output program in the It doesn’t generate an output program. Meaning,
Program exe format. A user can run it it evaluates the source program every time
independently from the originally during individual execution.
intended program.
Execution One can separate the program Execution of the program is one of the steps of
execution from the compilation. Thus, the Interpretation process. So, you can perform
you can perform it only after it line by line.
completing the compilation of the
entire output.
Memory Target programs execute Interpreter originally exists in the memory at the
Requirement independently. They don’t require the time of interpretation.
Compiler in the memory.
Best Fitted For You cannot port the Compiler because They work the best in web environments- where
it stays bound to the specific target the load time is very crucial. Compiling takes a
machine. The compilation model is relatively long time, even with small codes that
very common in programming may not run multiple times due to the exhaustive
languages like C and C++. analysis. Interpretations are better in such
cases.
Optimization of A compiler is capable of seeing the An interpreter sees a code line by line. The
Code entire code upfront. Thus, it makes the optimization is, thus, not very robust when
codes run faster by performing plenty compared to Compilers.
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 can’t displays the errors, if any. A user must resolve
run this program unless you fix the these errors in order to interpret the next line.
errors.
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 one by
after compiling- together at the same one.
time.
Programming Java, Scala, C#, C, C++ use Perl, Ruby, PHP use Interpreters.
Languages Compilers.
We need a system which can act as an intermediary and manage all the processes and
resources present in the system.
Windows, Linux, and Android are examples of operating systems that enable the user to
use programs like MS Office, Notepad, and games on the computer or mobile phone. It
is necessary to have at least one operating system installed in the computer to run
basic programs like browsers.
Shell
Kernel
Executable Code
Executable Code is the end translated machine understandable code of a program.All .exe
files and .o files are executable codes.Each programming language generates an executable
code but in different ways.A normal C,C++ program when compiled is first translated into
Assembly Language and then to Machine Language and that Machine Language code is
stored in an .exe file which is abbreviated as executable code .To understand well,use Dev-
CPP compiler which creates an exe file for every program compiled or executed.
Furthermore, if the programmer does any modifications to the source code, it is necessary to
compile the program to make those changes appear in the object code.
What is Executable Code
Executable code is a file or a program that indicates tasks according to encoded instructions. The
CPU can directly execute an executable file to defined tasks. In other words, it is machine code
instructions for a physical CPU. As a CPU can directly execute an object code, we can also
consider the object code as an executable code. Furthermore, it is sometimes possible to
consider a bytecode or scripting language instructions as an executable code.
Difference Between Object Code and Executable Code
Definition
Object code is a sequence of statements in binary that is generated after compiling the source
program. In contrast, an executable code is a file or a program that indicates tasks according to
encoded instructions which are directly executed by the CPU.
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.
2) C as a system programming language
A system programming language is used to create system software. C language is a
system programming language because it can be used to do low-level programming
(for example driver and kernel). It is generally used to create hardware devices, OS,
drivers, kernels, etc. For example, Linux kernel is written in C.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.
A procedural language breaks the program into functions, data structures, etc.
In the C language, we break the program into parts using functions. It makes the
program easier to understand and modify.
C Program
In this tutorial, all C programs are given with C compiler so that you can quickly change
the C program code.
File: main.c
1. #include <stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5. }
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Let's see the programming languages that were developed before C language.
Features of C Language
C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
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.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
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.
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
C language is extensible because it can easily adopt new features.
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. type variable_list;
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;
Types of Variables in C
There are many 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.
1. void function1(){
2. int x=10;//local variable
3. static int y=10;//static variable
4. x=x+1;
5. y=y+1;
6. printf("%d,%d",x,y);
7. }
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. int x=10;//local variable (also automatic)
3. auto int y=20;//automatic variable
4. }
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.
myfile.h
1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
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.
float 4 byte
double 8 byte
Int:
Integers are entire numbers without any fractional or decimal parts, and the int data
type is used to represent them.
It is frequently applied to variables that include values, such as counts, indices, or other
numerical numbers. The int data type may represent both positive and negative
numbers because it is signed by default.
An int takes up 4 bytes of memory on most devices, allowing it to store values between
around -2 billion and +2 billion.
Char:
Individual characters are represented by the char data type. Typically used to
hold ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols,
or commas. There are 256 characters that can be represented by a single char, which
takes up one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in
single quotes.
Float:
To represent integers, use the floating data type. Floating numbers can be used to
represent fractional units or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not
be very precise. It can store values with an accuracy of about 6 decimal places and a
range of about 3.4 x 1038 in 4 bytes of memory.
Double:
Use two data types to represent two floating integers. When additional precision is
needed, such as in scientific calculations or financial applications, it provides greater
accuracy compared to float.
Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal
places, yields larger values. C treats floating point numbers as doubles by default if no
explicit type is supplied.
In the example above, we declare four variables: an int variable for the person's age,
a char variable for the student's grade, a float variable for the temperature reading,
and two variables for the number pi.
Array:
An array, a derived data type, lets you store a sequence of fixed-size elements of the
same type. It provides a mechanism for joining multiple targets of the same data under
the same name.
The index is used to access the elements of the array, with a 0 index for the first entry.
The size of the array is fixed at declaration time and cannot be changed during program
execution. The array components are placed in adjacent memory regions.
Here is an example of declaring and utilizing an array:
1. #include <stdio.h>
2.
3. int main() {
4. int numbers[5]; // Declares an integer array with a size of 5 elements
5.
6. // Assign values to the array elements
7. numbers[0] = 10;
8. numbers[1] = 20;
9. numbers[2] = 30;
10. numbers[3] = 40;
11. numbers[4] = 50;
12.
13. // Display the values stored in the array
14. printf("Values in the array: ");
15. for (int i = 0; i < 5; i++) {
16. printf("%d ", numbers[i]);
17. }
18. printf("\n");
19.
20. return 0;
21. }
Output:
Pointer:
A pointer is a derived data type that keeps track of another data type's memory
address. When a pointer is declared, the data type it refers to is stated first, and then
the variable name is preceded by an asterisk (*).
You can have incorrect access and change the value of variable using pointers by
specifying the memory address of the variable. Pointers are commonly used
in tasks such as function pointers, data structures, and dynamic memory allocation.
Here is an example of declaring and employing a pointer:
1. #include <stdio.h>
2.
3. int main() {
4. int num = 42; // An integer variable
5. int *ptr; // Declares a pointer to an integer
6.
7. ptr = # // Assigns the address of 'num' to the pointer
8.
9. // Accessing the value of 'num' using the pointer
10. printf("Value of num: %d\n", *ptr);
11.
12. return 0;
13. }
Output:
Value of num: 42
Structure:
A structure is a derived data type that enables the creation of composite data types by
allowing the grouping of many data types under a single name. It gives you the ability
to create your own unique data structures by fusing together variables of various sorts.
1. A structure's members or fields are used to refer to each variable within it.
2. Any data type, including different structures, can be a member of a structure.
3. A structure's members can be accessed by using the dot (.) operator.
1. #include <stdio.h>
2. #include <string.h>
3. // Define a structure representing a person
4. struct Person {
5. char name[50];
6. int age;
7. float height;
8. };
9.
10. int main() {
11. // Declare a variable of type struct Person
12. struct Person person1;
13.
14. // Assign values to the structure members
15. strcpy(person1.name, "John Doe");
16. person1.age = 30;
17. person1.height = 1.8;
18.
19. // Accessing the structure members
20. printf("Name: %s\n", person1.name);
21. printf("Age: %d\n", person1.age);
22. printf("Height: %.2f\n", person1.height);
23.
24. return 0;
25. }
Output:
Union:
A derived data type called a union enables you to store various data types in the same
memory address. In contrast to structures, where each member has a separate memory
space, members of a union all share a single memory space. A value can only be held by
one member of a union at any given moment. When you need to represent many data
types interchangeably, unions come in handy. Like structures, you can access the
members of a union by using the dot (.) operator.
Output:
Integer Value: 42
Float Value: 3.14
1. #include <stdio.h>
2.
3. // Define an enumeration for days of the week
4. enum DaysOfWeek {
5. Monday,
6. Tuesday,
7. Wednesday,
8. Thursday,
9. Friday,
10. Saturday,
11. Sunday
12. };
13.
14. int main() {
15. // Declare a variable of type enum DaysOfWeek
16. enum DaysOfWeek today;
17.
18. // Assign a value from the enumeration
19. today = Wednesday;
20.
21. // Accessing the enumeration value
22. printf("Today is %d\n", today);
23.
24. return 0;
25. }
Output:
Today is 2
Example:
Function Parameters:
The parameter void can be used to indicate that a function accepts no arguments.
Example:
Pointers:
Any address can be stored in a pointer of type void*, making it a universal pointer. It
offers a method for working with pointers to ambiguous or atypical types.
Example:
1. void* dataPtr;
The void data type is helpful for defining functions that don't accept any arguments
when working with generic pointers or when you wish to signal that a function doesn't
return a value. It is significant to note that while void* can be used to build generic
pointers, void itself cannot be declared as a variable type.
Here is a sample of code that shows how to utilize void in various situations:
1. #include <stdio.h>
2. // Function with void return type
3. void printHello() {
4. printf("Hello, world!\n");
5. }
6. // Function with void parameter
7. void processInput(void) {
8. printf("Processing input...\n");
9. }
10.
11. int main() {
12. // Calling a void function
13. printHello();
14.
15. // Calling a function with void parameter
16. processInput();
17.
18. // Using a void pointer
19. int number = 10;
20. void* dataPtr = &number;
21. printf("Value of number: %d\n", *(int*)dataPtr);
22.
23. return 0;
24. }
Output:
Hello, world!
Processing input...
Value of number: 10
Conclusion:
As a result, data types are essential in the C programming language because they
define the kinds of information that variables can hold. They provide the data's size and
format, enabling the compiler to allot memory and carry out the necessary actions. Data
types supported by C include void, enumeration, derived, and basic types. In addition
to floating-point types like float and double, basic data types in C also include integer-
based kinds like int, char, and short. These forms can be signed or unsigned, and they
fluctuate in size and range. To create dependable and efficient code, it is crucial to
comprehend the memory size and scope of these types.
A few examples of derived data types are unions, pointers, structures, and arrays.
Multiple elements of the same kind can be stored together in contiguous memory due
to arrays. Pointers keep track of memory addresses, allowing for fast data structure
operations and dynamic memory allocation. While unions allow numerous variables to
share the same memory space, structures group relevant variables together.
Code becomes more legible and maintainable when named constants are defined using
enumeration data types. Enumerations give named constants integer values to enable
the meaningful representation of related data. The void data type indicates the lack of a
particular type. It is used as a return type for both functions and function
parameters that don't take any arguments and don't return a value. The void*
pointer also functions as a general pointer that can store addresses of various types.
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.
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.
Types of identifiers
o Internal identifier
o External identifier
Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal
identifier. The internal identifiers can be local variables.
External Identifier
If the identifier is used in the external linkage, then it is known as an external identifier.
The external identifiers can be function names, global variables.
Keyword Identifier
Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c com
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.
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.
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next.
The associativity specifies the operator direction to be evaluated; it may be left to right
or right to left.
1. int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated
before + (additive operator).
Postfix () [] -> . ++ - -
Multiplicative */%
Additive +-
Equality == !=
Bitwise XOR ^
Bitwise OR |
Logical OR ||
Conditional ?:
Comma ,
C Programming Operators
An operator is a symbol that operates on a value or a variable. For
example: + is an operator to perform addition.
C has a wide range of operators to perform various operations.
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc on numerical values (constants and
variables).
* multiplication
/ division
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Run Code
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
The modulo operator % computes the remainder. When a=9 is divided by b=4 ,
a/d = 2.5
c/b = 2.5
c/d = 2
return 0;
}
Run Code
Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Here, the operators ++ and -- are used as prefixes. These two operators can
also be used as postfixes like a++ and a-- . Visit this page to learn more about
how increment and decrement operators work when used as postfix.
C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
Operator Example Same as
%= a %= b a = a%b
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
Run Code
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
C Relational Operators
== Equal to 5 == 3 is evaluated to 0
return 0;
}
Run Code
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
C Logical Operators
&& Logical AND. True only if all operands If c = 5 and d = 2 then, expression ((c==5) &&
Operator Meaning Example
Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c==5) ||
||
operand is true (d>5)) equals to 1.
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
}
Run Code
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
C Bitwise Operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof operator
The sizeof is a unary operator that returns the size of data (constants,
variables, array, structure, etc).
Example 6: sizeof Operator
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}
Run Code
Output
Bitwise Operators in C
Programming
In the arithmetic-logic unit (which is within the CPU), mathematical operations
like: addition, subtraction, multiplication and division are done in bit-level. To
perform bit-level operations in C programming, bitwise operators are used.
Operators Meaning of operators
| Bitwise OR
^ Bitwise XOR
~ Bitwise complement
Shift left
int main() {
return 0;
}
Run Code
Output
Output = 8
Bitwise OR Operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands
is 1. In C Programming, bitwise OR operator is denoted by | .
int main() {
return 0;
}
Run Code
Output
Output = 29
int main() {
int a = 12, b = 25;
printf("Output = %d", a ^ b);
return 0;
}
Run Code
Output
Output = 21
int main() {
return 0;
}
Run Code
Output
Output = -36
Output = 11
Shift Operators in C programming
There are two shift operators in C programming:
Right shift operator shifts all bits towards right by certain number of specified
bits. It is denoted by >> .
Left shift operator shifts all bits towards left by a certain number of specified
bits. The bit positions that have been vacated by the left shift operator are
filled with 0. The symbol of the left shift operator is << .
int main() {
int num=212, i;
}
printf("\n");
return 0;
}
Run Code
Conditional statements
Goto statements in C
Simple if statement
If-else statements
else-if ladder
Simple if Statement
Simple if statements are carried out to perform some operation when the condition is
only true. If the condition of the if statement is true then the statements under the if
block is executed else the control is transferred to the statements outside the if block.
Syntax of the if statement is as given below:
Flow Chart:
Example:
Output:
If-else Statement
In some situations, you may have to execute statements based on true or false under
certain conditions, therefore; you use if-else statements. If the condition is true, then if
block will be executed otherwise the else block is executed.
Example:
Output:
The nested if-else statements consist of another if or else. Therefore; if the condition of
“if” is true (i.e., an outer if) then outer if’s if block is executed which contains another if
(that is inner if) and if the condition of if block is true, statements under if block will be
executed else the statements of inner if’s “else” block will be executed.
If the outer “if” condition is not true then the outer if’s “else” block is executed which
consists of another if. The outer else’s inner if the condition is true then the statement
under outer else’s inner if is executed else the outer else’s else block is executed.
Syntax of the nested if-else statement is as given below:
Flow Chart:
Example:
Output:
Suppose the “if” condition is true, statements under “if” will be executed else the other
“if” condition is tested, and if that condition is true statements under that particular “if”
will be executed. This process will repeat as long as the else-if’s are present in the
program.
Flow Chart:
Example:
Output:
So far, you have looked at the decision-making control statements in C. Now, go ahead
and take the next step and learn conditional statements in C.
Depending on the expression, the control is transferred to that particular case label and
executed the statements under it. If none of the cases are matched with the switch
expression, then the default statement is executed.
Flow Chart:
Example:
Output:
Goto Statements in C
The goto statements are used to transfer the flow of control in a program, goto
statement is also known as a jump control statement because it is used to jump to the
specified part of the program. The label in goto statement is a name used to direct the
branch to a specified point in the program.
While Loop
A while loop is also known as an entry loop because in a while loop the condition is
tested first then the statements underbody of the while loop will be executed.
If the while loop condition is false for the first time itself then the statements under the
while loop will not be executed even once.
Flow Chart:
Example:
Output:
do-while Loop
The do-while is also known as an exit loop because in the do-while loop, the statements
will be executed first and then the condition is checked.
If the condition of the while loop is true then the body of the loop will be executed again
and again until the condition is false. Once the condition is false, the control will transfer
outside the do-while loop and execute statements followed soon after the do-while loop.
Flow Chart:
Example:
Output:
For Loop
The for loop is also known as a pre-test loop. From the following syntax, expression1 is
an initialization, expression2 is the conditional expression and expression3 is an
updation. The variables can be initialized in for the statement itself.
Flow Chart:
Example:
Output:
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 possibles 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;
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
Output
hi
In C language, the switch statement is fall through; it means if you don't use a break
statement in the switch case, all the cases after the matching case will be executed.
Let's try to understand the fall through state of switch statement by the example given
below.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4.
5. printf("enter a number:");
6. scanf("%d",&number);
7.
8. switch(number){
9. case 10:
10. printf("number is equal to 10\n");
11. case 50:
12. printf("number is equal to 50\n");
13. case 100:
14. printf("number is equal to 100\n");
15. default:
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
Output
enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100
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:
1. //loop or switch case
2. break;
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;
11. }
12. printf("came outside of loop i = %d",i);
13.
14. }
Output
1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. printf("%d &d\n",i,j);
7. if(i==2 && j==2){
8. break;//will break loop of j only
9. }
10. }//end of for loop
11. return 0;
12. }
Output
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
As you can see the output on the console, 2 3 is not printed because there is a break
statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 are printed because the
break statement is used to break the inner loop only.
Output
1. #include<stdio.h>
2. void main ()
3. {
4. int n=2,i,choice;
5. do
6. {
7. i=1;
8. while(i<=10)
9. {
10. printf("%d X %d = %d\n",n,i,n*i);
11. i++;
12. }
13. printf("do you want to continue with the table of %d , enter any non-
zero value to continue.",n+1);
14. scanf("%d",&choice);
15. if(choice == 0)
16. {
17. break;
18. }
19. n++;
20. }while(1);
21. }
Output
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
do you want to continue with the table of 3 , enter any non-zero value to
continue.1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
do you want to continue with the table of 4 , enter any non-zero value to
continue.0
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
1. #include<stdio.h>
2. void main ()
3. {
4. int i = 0;
5. while(i!=10)
6. {
7. printf("%d", i);
8. continue;
9. i++;
10. }
11. }
Output
infinite loop
1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. if(i==5){//if value of i is equal to 5, it will continue the loop
7. continue;
8. }
9. printf("%d \n",i);
10. }//end of for loop
11. return 0;
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.
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 statment 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
complecated.
Syntax:
1. label:
2. //some part of the code;
3. goto label;
goto example
Let's see a simple example to use goto statement in C language.
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. }
Output:
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++)
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. }
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
0 3 0
came out of the loop
Unit – III
Arrays
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
The array contains the following properties.
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
1) Code Optimization: Less code to the access the data.
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
We can declare an array in the c language in the following way.
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. }
Output
80
60
70
85
75
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
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++)
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)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28. }
1. data_type array_name[rows][columns];
1. 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.
1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
56 10 30
34 21 34
45 56 78
Syntax
There are many syntaxes for creating a character array in c. The most basic syntax is,
char name[size];
The name depicts the name of the character array and size is the length of the character array.
The size can be greater than the length of the string but can not be lesser. If it is lesser then the
full string can't be stored and if it is greater the remaining spaces are just left unused.
Example
Before seeing the example, let us understand the method of dynamic memory allocation which is used to
create the dynamic array.
The malloc function returns a void pointer which is cast (converted) to the required data type.
The sizeof() function gives the size of data types and has the syntax,
sizeof(datatype)
Now, let us see the example of how we can create a dynamic single-dimension character array by getting
input from the user.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n, i;
char *arr;
arr = (char*)malloc(n*sizeof(char));
printf("Enter the string: ");
for(i=0; i < n; i++)
{
scanf(" %c",arr+i);
}
printf("\nThe string entered is: \n\n");
Output:
c h a r a c t e r
The elements at index 2: a
C Programming Strings
In C programming, a string is a sequence of characters terminated with a null character \0 . For
example:
When the compiler encounters a sequence of characters enclosed in the double quotation marks, it
appends a null character \0 at the end by default.
Memory Diagram
char s[5];
String Declaration in C
String Initialization in C
Here, we are trying to assign 6 characters (the last character is '\0' ) to a char array having 5
characters. This is bad and you should never do this.
char c[100];
c = "C programming"; // Error! array type is not assignable.
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output
Even though Dennis Ritchie was entered in the above program, only "Dennis" was stored in
the name string. It's because there was a space after Dennis .
Also notice that we have used the code name instead of &name with scanf() .
scanf("%s", name);
This is because name is a char array, and we know that array names decay to pointers in C.
Thus, the name in scanf() already points to the address of the first element in the string, which is why
we don't need to use & .
You can use the fgets() function to read a line of string. And, you can use puts() to display the string.
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Output
Here, we have used fgets() function to read a string from the user.
fgets(name, sizeof(name), stdlin); // read string
The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the
size of the name string.
To print the string, we have used puts(name); .
Note: The gets() function can also be to take input from the user. However, it is removed from the C
standard.
It's because gets() allows you to input any length of characters. Hence, there might be a buffer
overflow.
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
#include <stdio.h>
int main(void) {
char name[] = "Harry Potter";
char *namePtr;
namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
}
Commonly Used String Functions
#include <string.h>
Note: You have to include the code below to run string handling functions.
gets() and puts()
Functions gets() and puts() are two string functions to take string input from the user and display it
respectively as mentioned in the previous chapter.
#include<stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
Note: Though, gets() and puts() function handle strings, both these functions are defined
in "stdio.h" header file.
Output
Here, using a for loop, we have iterated over characters of the string from i = 0 to
until '\0' (null character) is encountered. In each iteration, the value of i is increased
by 1.
When the loop ends, the length of the string will be stored in the i variable.
Note: Here, the array s[] has 19 elements. The last element s[18] is the null
character '\0'. But our loop does not count this character as it terminates upon
encountering it.
Concatenate Two Strings Without Using strcat()
#include <stdio.h>
int main() {
char s1[100] = "programming ", s2[] = "is awesome";
int length, j;
// concatenate s2 to s1
for (j = 0; s2[j] != '\0'; ++j, ++length) {
s1[length] = s2[j];
}
return 0;
}
Output
Here, two strings s1 and s2 and concatenated and the result is stored in s1.
It's important to note that the length of s1 should be sufficient to hold the string after
concatenation. If not, you may get unexpected output.
Unit – IV
Linear Search in C
Linear search in C is a searching method/algorithm. In the linear search algorithm, we traverse through the data structure from any
one point and traverse until the data item is found in the data structure.
These data structures could be array, string, Linked-List, Stack, Queue, or any other data structure.
Array:
24 56 -1 90 4 12 34 89 37
0 1 2 3 4 5 6 7 8
Solution:
7 89
8 37
Because 6 is the index of our element (34), our answer is 6 for 0-based indexing arrays and 7 for 1-based indexing arrays. This is how
linear search works in an array.
Problem Description
Write a C Program which finds the position of an element in an array using Linear Search Algorithm. We have
to take an array and a value to be searched in the array as input from the user, and then find the position of that
element in array by using linear search algorithm.
Problem Solution
1. We will create an array of numbers by taking input from user. We will also read the element to be searched
by the user.
2. In order to look for that element in the array, we’ll go sequentially in increasing index values. If we
encounter the element requested by the user we will return the position of that element in array, but if it is not
there we will return -1 which indicates the absence of element which was searched.
Program/Source Code
Here is source code of the C Program to find the position of an element requested by the user using Linear
Search Algorithm. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on
Windows 10. The program output is also shown below.
1. /*
2. * C program to input N numbers and store them in an array.
3. * Do a linear search for a given key and report success or failure.
4. */
5.
6. #include <stdio.h>
7.
8. void main()
9. { int num;
10.
11. int i, keynum, found = 0;
12.
13. printf("Enter the number of elements ");
14. scanf("%d", &num);
15. int array[num];
16. printf("Enter the elements one by one \n");
17. for (i = 0; i < num; i++)
18. {
19. scanf("%d", &array[i]);
20. }
21.
22. printf("Enter the element to be searched ");
23. scanf("%d", &keynum);
24.
25. /* Linear search begins */
26. for (i = 0; i < num ; i++)
27. {
28. if (keynum == array[i] )
29. {
30. found = 1;
31. break;
32. }
33. }
34. if (found == 1)
35. printf("Element is present in the array at position
%d",i+1);
36. else
37. printf("Element is not present in the array\n");
38. }
Program Explanation
1. In Linear search, we search an element or value in a given array by traversing the array from the starting, till
the desired element or value is found.
2. The array is searched sequentially and the position is returned if the key element to be searched is available
in the array, otherwise -1 is returned.
3. Here in this C Program we have not made any function specifically for linear search, rather we can look for
presence of element in an array in the main function itself.
4. We traverse the array from the 0th index in increasing order of index, if we find the element we break the
loop there itself and print the position of the element in the array, but if the element requested is not there in
array, we simply print that “Element is not present in the array”.
5. If we’d have created a separate function for linear search and the element could not be found in the array, we
would have returned -1 in that case denoting absence of the element.
Time Complexity:
Average & Worst Case: O(n)
As the name suggests it is a linear search and we used a loop to iterate over the array from start to end, hence
we can affirm that it is of O(n) complexity.
Best Case: O(1)
The best-case complexity will be found if you find the element at the first index from the start *(according to
the approach we used). It can be denoted as O(1)
Space Complexity: O(n + k)
space complexity of the linear search algorithm is O(n + k), where n = size of the array and k = auxiliary
variables.
Binary Search
Binary Search is a searching algorithm for finding an element's position in a sorted array.
In this approach, the element is always searched in the middle of a portion of an array.
Binary search can be implemented only on a sorted list of items. If the elements are not sorted
already, we need to sort them first.
1. Iterative Method
2. Recursive Method
3. Find the middle element mid of the array ie. arr[(low + high)/2] =
6. Mid element
4. If x == mid, then return mid.Else, compare the element to be searched with m.
5. If x > mid , compare x with the middle element of the elements on the right side of mid . This is
done by setting low to low = mid + 1 .
6. Else, compare x with the middle element of the elements on the left side of mid . This is done
8. x = 4 is found. Found
if (x == arr[mid])
return mid
low = mid + 1
high = mid - 1
Recursive Method
return False
else
if x == arr[mid]
return mid
1. /*
2. * C program to implement Binary search with window
3. */
4. #include <stdio.h>
5. #include <conio.h>
6.
7. /* Function for Binary search */
8. void binary_search(int array[], int first, int last, int n)
9. {
10. int i ,middle;
11. middle = (first + last) / 2;
12.
13. while (first <= last) {
14. if (array[middle] < n)
15. first = middle + 1;
16. else if (array[middle] == n) {
17. printf("%d found at location %d.\n", n, middle+1);
18. break;
19. }
20. else
21. last = middle - 1;
22.
23. middle = (first + last) / 2;
24. }
25. if ( first > last )
26. printf("Not found! %d is not present in the list.\n", n);
27. }
28. /* End of binary_search() */
29.
30. /* Function to search for the window */
31. search(int arr[], int size, int data)
32. {
33. int p = (size - 1) / 2, low, high, a1 = 0, a2 = 1, i = 1;
34. low = p + a1;
35. high = p + a2;
36. while(i)
37. {
38. if(data >= arr[low] && data <= arr[high])
39. {
40. binary_search(arr, low, high, data);
41. break;
42. }
43. else if(data < arr[low])
44. {
45. binary_search(arr, 0, low, data);
46. break;
47. }
48. else
49. {
50. a2 = a2 * 2;
51. low = high;
52. high = p + a2;
53. }
54. }
55. }
56. /* End of search() */
57.
58. /* The main() begins */
59. int main()
60.
61. {
62. int a[200], i, j, n, size;
63. printf("Enter the size of the list:");
64. scanf("%d", &size);
65. printf("Enter %d Integers in ascending order\n", size);
66. for (i = 0; i < size; i++)
67. scanf("%d", &a[i]);
68. printf("Enter value to find\n");
69. scanf("%d", &n);
70. search(a, size, n );
71. return 0;
72. }
The function has two loops. The outer loop runs from the first element to the second-last
element of the array. The inner loop runs from the first element to the second-last element of
the unsorted part of the array. The condition of the inner loop is n - i - 1 because the last i
elements of the array are already sorted.
In each iteration of the inner loop, we compare adjacent elements. If the left element is greater
than the right element, we swap them. After the inner loop completes, the largest element is
guaranteed to be at the end of the unsorted part of the array.
Now, we can write the main function to test our bubble sort implementation. Here is the main
function along with the previous part:
C Program:
Program/Source Code
Here is the source code of the C program to sort integers using Bubble Sort technique. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.
1. /*
2. * C Program to sort an array using Bubble Sort technique
3. */
4.
5. #include <stdio.h>
6. void bubblesort(int arr[], int size)
7. {
8. int i, j;
9. for (i = 0; i < size; i++)
10. {
11. for (j = 0; j < size - i; j++)
12. {
13. if (arr[j] > arr[j+1])
14. swap(&arr[j], &arr[j+1]);
15.
16. }
17. }
18. }
19. void swap(int *a, int *b)
20. {
21. int temp;
22. temp = *a;
23. *a = *b;
24. *b = temp;
25. }
26. int main()
27. {
28. int array[100], i, size;
29. printf("How many numbers you want to sort: ");
30. scanf("%d", &size);
31. printf("\nEnter %d numbers : ", size);
32. for (i = 0; i < size; i++)
33. scanf("%d", &array[i]);
34. bubblesort(array, size);
35. printf("\nSorted array is ");
36.
37. for (i = 0; i < size; i++)
38. printf(" %d ", array[i]);
39. return 0;
40. }
Time Complexity: O(n2)
In the worst case, it should have to swap the n elements if the array is reverse sorted. The size of the list is n.
Space Complexity: O(1)
There is no need to use an extra space that depends on the size of the array. Hence the space completixty of
bubble sort program is constant.
Characteristics:
o Bubble sort is a simple sorting algorithm.
o It works by repeatedly swapping adjacent elements if they are in the wrong order.
o The algorithm sorts the array in ascending or descending order.
2
o It has a time complexity of O(n ) in the worst case, where n is the size of the array.
Usage:
o Bubble sort is useful for educational purposes and small data sets.
o It is not suitable for large data sets because of its time complexity.
Advantages:
o Bubble sort is easy to understand and implement.
o It requires minimal additional memory space to perform the sorting.
Disadvantages:
o It is not efficient for large data sets because of its time complexity.
o It has poor performance compared to other sorting algorithms, such as quicksort and mergesort.
Conclusion:
Bubble sort is a simple and intuitive sorting algorithm that is useful for educational purposes and small data sets.
However, its time complexity makes it inefficient for large data sets. Therefore, it is not commonly used in real-world
applications. Other sorting algorithms, such as quicksort and mergesort, are more efficient for large data sets.
In selection sort, the smallest value among the unsorted elements of the array is selected in
every pass and inserted to its appropriate position into the array. It is also the simplest
algorithm. It is an in-place comparison sorting algorithm. In this algorithm, the array is divided
into two parts, first is sorted part, and another one is the unsorted part. Initially, the sorted part
of the array is empty, and unsorted part is the given array. Sorted part is placed at the left, while
the unsorted part is placed at the right.
In selection sort, the first smallest element is selected from the unsorted array and placed at the
first position. After that second smallest element is selected and placed in the second position.
The process continues until the array is entirely sorted.
The average and worst-case complexity of selection sort is O(n2), where n is the number of
items. Due to this, it is not suitable for large data sets.
PauseNext
Unmute
Duration 18:10
Loaded: 8.81%
Fullscreen
Algorithm
1. SELECTION SORT(arr, n)
2.
3. Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
4. Step 2: CALL SMALLEST(arr, i, n, pos)
5. Step 3: SWAP arr[i] with arr[pos]
6. [END OF LOOP]
7. Step 4: EXIT
8.
9. SMALLEST (arr, i, n, pos)
10. Step 1: [INITIALIZE] SET SMALL = arr[i]
11. Step 2: [INITIALIZE] SET pos = i
12. Step 3: Repeat for j = i+1 to n
13. if (SMALL > arr[j])
14. SET SMALL = arr[j]
15. SET pos = j
16. [END OF if]
17. [END OF LOOP]
18. Step 4: RETURN pos
Now, for the first position in the sorted array, the entire array is to be scanned sequentially.
At present, 12 is stored at the first position, after searching the entire array, it is found that 8 is
the smallest value.
So, swap 12 with 8. After the first iteration, 8 will appear at the first position in the sorted array.
For the second position, where 29 is stored presently, we again sequentially scan the rest of the
items of unsorted array. After scanning, we find that 12 is the second lowest element in the array
that should be appeared at second position.
Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in the
sorted array. So, after two iterations, the two smallest values are placed at the beginning in a
sorted way.
The same process is applied to the rest of the array elements. Now, we are showing a pictorial
representation of the entire sorting process.
Now, the array is completely sorted.
1. Time Complexity
Case Time Complexity
o Best Case Complexity - It occurs when there is no sorting required, i.e. the array is
already sorted. The best-case time complexity of selection sort is O(n2).
o Average Case Complexity - It occurs when the array elements are in jumbled order that
is not properly ascending and not properly descending. The average case time
complexity of selection sort is O(n2).
o Worst Case Complexity - It occurs when the array elements are required to be sorted in
reverse order. That means suppose you have to sort the array elements in ascending
order, but its elements are in descending order. The worst-case time complexity of
selection sort is O(n2).
2. Space Complexity
Space Complexity O(1)
Stable YES
o The space complexity of selection sort is O(1). It is because, in selection sort, an extra
variable is required for swapping.
Here is source code of the C program to implement selection sort method using functions. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.
1. /*
2. * C program for SELECTION sort which uses following functions
3. * a) To find maximum of elements
4. * b) To swap two elements
5. */
6. #include <stdio.h>
7.
8. int findmax(int b[10], int k);
9. void exchang(int b[10], int k);
10. void main()
11. {
12. int array[10];
13. int i, j, n, temp;
14.
15. printf("Enter the value of n \n");
16. scanf("%d", &n);
17. printf("Enter the elements one by one \n");
18. for (i = 0; i < n; i++)
19. {
20. scanf("%d", &array[i]);
21. }
22. printf("Input array elements \n");
23. for (i = 0; i < n ; i++)
24. {
25. printf("%d\n", array[i]);
26. }
27. /* Selection sorting begins */
28. exchang(array, n);
29. printf("Sorted array is...\n");
30. for (i = 0; i < n; i++)
31. {
32. printf("%d\n", array[i]);
33. }
34. }
35. /* function to find the maximum value */
36. int findmax(int b[10], int k)
37. {
38. int max = 0, j;
39. for (j = 1; j <= k; j++)
40. {
41. if (b[j] > b[max])
42. {
43. max = j;
44. }
45. }
46. return(max);
47. }
48. void exchang(int b[10], int k)
49. {
50. int temp, big, j;
51. for (j = k - 1; j >= 1; j--)
52. {
53. big = findmax(b, j);
54. temp = b[big];
55. b[big] = b[j];
56. b[j] = temp;
57. }
58. return;
59. }
We assume that the first card is already sorted then, we select an unsorted card. If the unsorted card
is greater than the card in hand, it is placed on the right otherwise, to the left. In the same way, other
unsorted cards are taken and put in their right place.
Initial array
1. The first element in the array is assumed to be sorted. Take the second element and store it
separately in key .
Compare key with the first element. If the first element is greater than key , then key is placed in front
Take the third element and compare it with the elements on the left of it. Placed it just behind the
element smaller than it. If there is no element smaller than it, then place it at the beginning of the
insertionSort(array)
mark first element as sorted
for each unsorted element X
'extract' the element X
for j <- lastSortedIndex down to 0
if current element j > X
move sorted element to the right by 1
break loop and insert X here
end insertionSort
Insertion Sort in C
// Insertion sort in C
#include <stdio.h>
// Compare key with each element on the left of it until an element smaller than
// it is found.
// For descending order, change key<array[j] to key>array[j].
while (key < array[j] && j >= 0) {
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
// Driver code
int main() {
int data[] = {9, 5, 1, 4, 3};
int size = sizeof(data) / sizeof(data[0]);
insertionSort(data, size);
printf("Sorted array in ascending order:\n");
printArray(data, size);
}
Best O(n)
Worst O(n2)
Average O(n2)
Space Complexity O(1)
Stability Yes
Let's implements the above steps in a C program to find the roots of the quadratic equation.
Output:
Unit – 5
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 procedureor subroutinein 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.
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.
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.
Example 1
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
Example 1
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: ");
13. scanf("%f",&side);
14. return side * side;
15. }
Output
Example 1
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:");
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
Example 1
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
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 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.
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);
10. change(x);//passing value 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 valu
e 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 par
ameters 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.
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 valu
e 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 p
arameters do change in call by reference, 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 paramete
rs, a = 20, b = 10
18. }
Output
1 A copy of the value is passed into the function An address of value is passed into the function
2 Changes made inside the function is limited to the Changes made inside the function validate out
function only. The values of the actual parameters do the function also. The values of the actual para
not change by changing the formal parameters. do change by changing the formal parameters.
3 Actual and formal arguments are created at the Actual and formal arguments are created at the
different memory location memory location
As we know that the array_name contains the address of the first element. Here, we must notice
that we need to pass only the name of the array in the function which is intended to accept an
array. The array defined as the formal parameter will automatically refer to the array specified by
the array name defined as an actual parameter.
1. functionname(arrayname);//passing array
PlayNext
Unmute
/
Duration 18:10
Loaded: 3.67%
Fullscreen
First way:
Second way:
Third way:
You can also use the concept of a pointer. In pointer chapter, we will learn about it.
ADVERTISING
Output
minimum number is 3
Output
Returning an array is similar to passing the array into the function. The name of the array is
returned from the function. To make a function returning an array, the following syntax is used.
1. int * Function_name() {
2. //some statements;
3. return array_type;
4. }
To store the array returned from the function, we can define a pointer which points to that array.
We can traverse the array by increasing that pointer since pointer initially points to the base
address of the array. Consider the following example that contains a function returning the
sorted array.
1. #include<stdio.h>
2. int* Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. int *p = Bubble_Sort(arr), i;
7. printf("printing sorted elements ...\n");
8. for(i=0;i<10;i++)
9. {
10. printf("%d\n",*(p+i));
11. }
12. }
13. int* Bubble_Sort(int a[]) //array a[] points to arr.
14. {
15. int i, j,temp;
16. for(i = 0; i<10; i++)
17. {
18. for(j = i+1; j<10; j++)
19. {
20. if(a[j] < a[i])
21. {
22. temp = a[i];
23. a[i] = a[j];
24. a[j] = temp;
25. }
26. }
27. }
28. return a;
29. }
Output
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.
PlayNext
Unmute
Duration 18:10
Loaded: 3.30%
Â
Fullscreen
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 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }
Output
Fibonacci Series in C
Fibonacci Series in C: In case of fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1,
2, 3, 5, 8, 13, 21 etc. The first two numbers of fibonacci series are 0 and 1.
1. #include<stdio.h>
2. int main()
3. {
4. int n1=0,n2=1,n3,i,number;
5. printf("Enter the number of elements:");
6. scanf("%d",&number);
7. printf("\n%d %d",n1,n2);//printing 0 and 1
8. for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
9. {
10. n3=n1+n2;
11. printf(" %d",n3);
12. n1=n2;
13. n2=n3;
14. }
15. return 0;
16. }
Output:
1. #include<stdio.h>
2. void printFibonacci(int n){
3. static int n1=0,n2=1,n3;
4. if(n>0){
5. n3 = n1 + n2;
6. n1 = n2;
7. n2 = n3;
8. printf("%d ",n3);
9. printFibonacci(n-1);
10. }
11. }
12. int main(){
13. int n;
14. printf("Enter the number of elements: ");
15. scanf("%d",&n);
16. printf("Fibonacci Series: ");
17. printf("%d %d ",0,1);
18. printFibonacci(n-2);//n-2 because 2 numbers are already printed
19. return 0;
20. }
Output:
Quick Sort in C
Quick sort is a commonly used sorting algorithm that is often preferred over other sorting algorithms due to its
efficiency and effectiveness. It proceeds by splitting an array into two parts, one with elements smaller than a selected
pivot element and the other with elements bigger than the pivot. The algorithm then applies this procedure
recursively to each partition until the complete array is sorted.
Quick sort can be used in any scenario where sorting is required, such as in database applications, scientific
computing, and web applications. It is frequently utilized when a large dataset must be rapidly and effectively sorted.
Some specific use cases where quick sort is commonly used include:
Overall, quick sort is a versatile and widely used algorithm that can be applied in a variety of domains where sorting is
required. Its low average-case time complexity and simplicity of execution make it an appealing choice for efficiently
sorting large datasets.
C Programming Language:
1. #include <stdio.h>
2.
3. // Function to swap two elements
4. void swap(int* a, int* b) {
5. int t = *a;
6. *a = *b;
7. *b = t;
8. }
9. int partition(int arr[], int low, int high) {
10. int pivot = arr[high];
11. int i = (low - 1);
12.
13. for (int j = low; j <= high - 1; j++) {
14. if (arr[j] < pivot) {
15. i++;
16. swap(&arr[i], &arr[j]);
17. }
18. }
19. swap(&arr[i + 1], &arr[high]);
20. return (i + 1);
21. }
22. void quickSort(int arr[], int low, int high) {
23. if (low < high) {
24. int pi = partition(arr, low, high);
25. quickSort(arr, low, pi - 1);
26. quickSort(arr, pi + 1, high);
27. }
28. }
29.
30. // Function to print the array
31. void printArray(int arr[], int size) {
32. int i;
33. for (i = 0; i < size; i++)
34. printf("%d ", arr[i]);
35. printf("\n");
36. }
37.
38. int main() {
39. int arr[] = { 12, 17, 6, 25, 1, 5 };
40. int n = sizeof(arr) / sizeof(arr[0]);
41. quickSort(arr, 0, n - 1);
42. printf("Sorted array: \n");
43. printArray(arr, n);
44. return 0;
45. }
Output
Sorted array:
1 5 6 12 17 25
o The quick_sort function takes an array arr, and the indices of the first and last elements of the subarray to be
sorted, low and high. If low is less than high, the function selects a pivot element using the partition function,
and recursively applies the quick_sort function to the two subarrays to the left and right of the pivot.
o The partition function takes the same arguments as quick_sort, and returns the index of the pivot element
after partitioning the subarray. It begins by selecting the pivot as the last element of the subarray, and
initializes an index i to the left of the subarray. It then iterates through the subarray, swapping any element
less than the pivot with the element at arr[i] and incrementing i. The centre is then switched for the element
at arr[i+1] before returning i+1.
o The swap method changes the values of two pointers to integers.
o To use this implementation of quick sort, you can simply call quick_sort(arr, 0, n-1), where arr is the array to
be sorted and n is its length.
o Take note that the pivot in this implementation is the final member of the subarray. This is a simple and
commonly used method, but it can lead to poor performance in certain cases, such as when the array is
already sorted or nearly sorted. In these situations, efficiency can be enhanced by utilising more
sophisticated pivot selection techniques. Additionally, this implementation uses recursion, which can be a
source of performance overhead in certain cases. Iterative implementations of quick sort are also possible.
Characteristics:
o Quick sort divides an array into two sections according to a pivot element, usually the last element in the
array.
o All elements smaller than the pivot are put in one partition, and all elements larger than the pivot are placed
in the other, dividing the array into two partitions.
o The algorithm repeats this procedure for each division until the array as a whole is sorted.
o If the data is already ordered or the pivot element is not carefully chosen, quick sort has a worst-case time
complexity of O(n2).
Advantages:
o Quick sort has a fast average-case time complexity of O(nlogn), making it efficient for large datasets.
o It is a simple and easy-to-implement algorithm that can be implemented in a few lines of code.
o Quick sort can be easily parallelized, making it suitable for use on multicore and distributed systems.
o It is an in-place sorting algorithm, which means that it does not require additional memory to store
temporary variables or data structures.
Disadvantages:
o Quick sort has a worst-case time complexity of O(n^2) if the pivot element is chosen poorly or the data is
already sorted.
o It is not a stable sorting algorithm, which means that it does not guarantee the relative order of equal
elements in the sorted array.
o Quick sort is not suitable for sorting large datasets that do not fit in memory, as it requires multiple passes
over the data.
Conclusion:
Quick sort is a popular and efficient sorting algorithm that works by splitting an array into two parts and applying the
procedure to each partition recursively until the complete array is sorted. It has an average and best case time
2
complexity of O(nlogn) and a worst-case time complexity of O(n ). Quick sort is frequently favoured over other sorting
algorithms due to its simplicity, performance, and ease of implementation, despite its worst-case time complexity.
The merge sort variant is treated as a 3-way merge sort that splits the array into three parts
instead of splitting it into two parts. Merge sort recursively splits an array into half-sized
subarrays. Similarly, a three-way merge sort decomposes an array into subarrays of one-third
the size.
In merge sort, the array is recursively split into two parts, sorted, and finally merged. A variant of
merge sort is called 3-way merge sort, where instead of splitting the array into two parts, he
splits it into three parts.
Examples of the merge sort: The example of merge sort is given below -
PlayNext
Unmute
Current Time 0:00
Duration 18:10
Loaded: 2.94%
Â
Fullscreen
1. Input: 4, 8, -4, -9, 10, 55, 46, 70, -56, 78, 90, 67, 85, 20, 29
2. Output: -56 -9 -4 4 8 10 20 29 46 55 67 70 78 85 90
3. Input: 98, -67
4. Output: -67 98
Example 1: Here, we give an example of 3 way to merge sort in c. The example is given below -
1. #include <bits/stdc++.h>
2. usingnamespacestd;
3. voidmerge1(intgArr1[], intlow1, intmid1,intmid2, inthigh1, intdestArr1[])
4. {
5. inti = low1, a = mid1, b = mid2, c = low1;
6. while((i < mid1) && (a < mid2) && (b < high1))
7. {
8. if(gArr1[i] < gArr1[j])
9. {
10. if(gArr1[i] < gArr1[b])
11. {
12. destArr1[c++] = gArr1[i++];
13. }
14. else {
15. destArr1[c++] = gArr1[b++];
16. }
17. }
18. else{
19. if(gArr1[j] < gArr1[b]){
20. destArr1[c++] = gArr1[a++];
21. }
22. else{
23. destArr1[c++] = gArr1[b++];
24. }
25. }
26. }
27. while((i < mid1) && (a < mid2)){
28. if(gArr1[i] < gArr1[a]){
29. destArr1[c++] = gArr1[i++];
30. }
31. else{
32.
33. destArr1[c++] = gArr1[a++];
34. }
35. }
36. while((a < mid2) && (b < high1)){
37. if(gArr1[a] < gArr1[b]){
38. destArr1[c++] = gArr1[a++];
39. }
40. else{
41. destArr1[c++] = gArr1[b++];
42. }
43. }
44. while((i < mid1) && (b < high1))
45. {
46. if(gArr1[i] < gArr1[b])
47. {
48. destArr1[c++] = gArr1[i++];
49. }
50. else{
51. destArr1[c++] = gArr1[b++];
52. }
53. }
54. while(i < mid1)
55. destArr1[c++] = gArr1[i++];
56. while(a < mid2)
57. destArr1[c++] = gArr1[b++];
58. while(b < high)
59. destArr1[c++] = gArr1[b++];
60. }
61. voidmergeSort3WayRec(intgArr1[], intlow1, inthigh1, intdestArr1[])
62. {
63. if(high1 - low1 < 2)
64. return;
65. intmid1 = low1 + ((high1 - low1) / 3);
66. intmid2 = low1 + 2 * ((high1 - low1) / 3) + 1;
67. mergeSort3WayRec(destArr1, low1, mid1, gArr1);
68. mergeSort3WayRec(destArr1, mid1, mid2, gArr1);
69. mergeSort3WayRec(destArr1, mid2, high1, gArr1);
70. merge(destArr1, low1, mid1, mid2, high1, gArr1);
71. }
72. voidmergeSort3Way(intgArr1[], intn1){
73. if(n1 == 0)
74. return;
75. intfArr1[n];
76. for(inti = 0; i < n1; i++)
77. fArr1[i] = gArr1[i];
78. mergeSort3WayRec(fArray1, 0, n, gArray1);
79. for(inti = 0; i < n1; i++)
80. gArr1[i] = fArr1[i];
81. }
82. int main(){
83. intdata1[] = {4, 8, -4, -9, 10, 55, 46, 70, -56, 78, 90, 67, 85, 20, 29};
84. mergeSort3Way(data1,10);
85. cout<< "The result after the three way of merge sort is: ";
86. for(inti = 0; i < 10; i++)
87. {
88. cout<< data1[i] << " ";
89. }
90. return0;
91. }
Result: Now we compile the above program, and after successful compilation, we run it. Then
the result is given below -
The result after the three way of merge sort is: -56 -9 -4 4 8 10 20 29 46 55
67 70 78 85 90
Solving with the master method, its complexity is O(n log 3n).
Time complexity appears less than a two-way merge sort, but the more comparisons in the
merge function, the more time it might take in practice.
So, in this article, we briefly discuss 3 ways to merge sort in c. The merge sort variant is treated
as a 3-way merge sort that splits the array into three parts instead of splitting it into two parts.
We also give an example that is related to this topic.
2 Comments
Write a C Program to implement Ackermann function using recursion. Here’s simple Program to implement
Ackermann’s function using recursion in C Programming Language.
Recursion : :
Recursion is the process of repeating items in a self-similar way. In programming languages, if a
program allows you to call a function inside the same function, then it is called a recursive call of the
function.
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function, otherwise it will
go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the
factorial of a number, generating Fibonacci series, etc.
Ackermann Function
The Ackermann function is the simplest example of a well-defined total function which is computable but not
primitive recursive, providing a counterexample to the belief in the early 1900’s that every computable function
was also primitive recursive . It grows faster than an exponential function, or even a multiple exponential
function.
Below is the source code for C Program to implement Ackermann function using recursion which is
successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
#include<stdio.h>
main()
{
int m,n;
scanf("%d%d",&m,&n);
printf("\nOUTPUT :: %d\n",A(m,n));
if(m==0)
return n+1;
else if(n==0)
return A(m-1,1);
else
return A(m-1,A(m,n-1));
OUTPUT : :
OUTPUT :: 2
OUTPUT :: 6
ARAVALI COLLEGE OF ENGINEERING & MANAGEMENT
1st Sessional October -2023
st
B.Tech (CSE) 1 Semester
Subject Name: PPS Subject Code: ESC-103
Time: 2hrs M.Marks:50
General instruction:
1: Part- A is compulsory. 2: Attempt any 4 questions from Part- B.
………………………………………………………………………………………………………………………………………
Part- A
Q1 Answer the Following Questions (1*10)
a) Algorithm
b) Flowchart
c) Compiler
d) Interpreter
e) Computer
f) Operating System
g) Variable
h) Data type
i) Expression
j) Decision making statement
Part- B
Q2 What are various data types in C? Explain each with an example. (10)
Q4 What are various operators available in C? Explain each with an example. (10)