Introduction To Programming Notes
Introduction To Programming Notes
UNIT 1
Q 1. Definition of Computer?
• Computer is any device which aids humans in performing various kinds of computations or Calculations
Earliest Computer
• Originally calculations were computed by humans, whose job title was computers.
• These human computers were typically engaged in the calculation of a mathematical expression.
• The calculations of this period were specialized and expensive, requiring years of training in mathematics.
• The first use of the word "computer" was recorded in 1613, referring to a person who carried out calculations, or
computations, and the word continued to be used in that sense until the middle of the 20th century.
Tally Sticks A tally stick was an ancient memory aid device to record and document numbers, quantities, or
even messages.
Abacus
• The abacus in the form we are most familiar with was first used in China in around 500 B.C.
Napier’s Bones
• Allowed the operator to multiply, divide and calculate square and cube roots by moving the rods around
and placing them in specially constructed boards.
Slide Rule
– multiplication
– division
– roots
– logarithms
– Trigonometry
• Not normally used for addition or subtraction.
Pascaline
• It is too expensive.
Arithmometer
• In 1840, Augusta Ada Byron suggests to Babbage that he use the binary system.
ENIAC
• Completed in 1946.
UNIVAC 1
• The UNIVAC I (UNIVersal Automatic Computer 1) was the first commercial computer.
3
EDVAC
• The first computers used vacuum tubes for circuitry and magnetic drums for memory, and were often enormous,
taking up entire rooms.
• They were very expensive to operate and in addition to using a great deal of electricity, generated a lot of heat,
which was often the cause of malfunctions.
• First generation computers relied on machine language, the lowest-level programming language understood by
computers, to perform operations, and they could only solve one problem at a time.
• Input was based on punched cards and paper tape, and output was displayed on printouts.
• Transistors replaced vacuum tubes and ushered in the second generation of computers.
• Allowing computers to become smaller, faster, cheaper, more energy-efficient and more reliable.
4
• Still generated a great deal of heat that can damage the computer.
• Second-generation computers moved from cryptic binary machine language to symbolic, or assembly, languages,
which allowed programmers to specify instructions in words.
• Second-generation computers still relied on punched cards for input and printouts for output.
• These were also the first computers that stored their instructions in their memory, which moved from a magnetic
drum to magnetic core technology.
• The development of the integrated circuit was the hallmark of the third generation of computers.
• Transistors were miniaturized and placed on silicon chips, called semiconductors, which drastically increased the
speed and efficiency of computers.
• Users interacted with third generation computers through keyboards and monitors and interfaced with an
operating system, which allowed the device to run many different applications at one time with a central program
that monitored the memory.
• Computers for the first time became accessible to a mass audience because they were smaller and cheaper than
their predecessors.
• The microprocessor brought the fourth generation of computers, as thousands of integrated circuits
• As these small computers became more powerful, they could be linked together to form networks, which
• Fourth generation computers also saw the development of GUIs, the mouse and handheld devices.
5
A computer can be defined as a fast electronic calculating machine that accepts the (data) digitized input information
process it as per the list of internally stored instructions and produces the resulting information.
List of instructions are called programs & internal storage is called computer memory.
1. Personal computers: - This is the most common type found in homes, schools, Business offices etc., It is
the most common type of desk top computers with processing and storage units along with various input and
output devices.
3. Work stations: - These have high resolution input/output (I/O) graphics capability, but with same
dimensions as that of desktop computer. These are used in engineering applications of interactive design
work.
4. Enterprise systems: - These are used for business data processing in medium to large corporations that
require much more computing power and storage capacity than work stations. Internet associated with
servers have become a dominant worldwide source of all types of information.
5. Super computers: - These are used for large scale numerical calculations required in the applications like
weather forecasting etc.,
A computer consists of five functionally independent main parts input, memory, arithmetic logic unit (ALU), output
and control unit.
ALU stands for arithmetic logic unit. It is responsible for performing all arithmetic and logical operations, such as
addition, subtraction, multiplication, division, AND, OR, and NOT.
Input-output units allow the computer to communicate with the outside world. They include devices such as the
keyboard, mouse, monitor, printer, and speakers.
Memory is where the computer stores data and instructions.
It is divided into two main types:
1. Random Access Memory (RAM) And
2. Read-Only Memory (ROM).
➢ RAM is used to store data and instructions that are currently being used by the CPU.
➢ ROM is used to store permanent data, such as the computer's startup instructions.
Program counter is a register that keeps track of the address of the next instruction to be executed by the CPU.
These four components work together to execute computer programs. The CPU first fetches the next instruction from
memory using the program counter. It then decodes the instruction and determines what operation needs to be
6
performed. The ALU then performs the operation and stores the result in memory. Finally, the program counter is
incremented to point to the next instruction.
Here is a simplified example of how the ALU, input-output units, memory, and program counter work together to
execute a simple program:
Program:
1. ADD 1 to A
2. PRINT A
Execution:
1. The CPU fetches the first instruction from memory (ADD 1 to A).
2. The CPU decodes the instruction and determines that it needs to perform an addition operation.
3. The CPU loads the operand A from memory.
4. The ALU adds 1 to A and stores the result back in memory.
5. The program counter is incremented to point to the next instruction.
6. The CPU fetches the next instruction from memory (PRINT A).
7. The CPU decodes the instruction and determines that it needs to print the value of A to the console.
8. The CPU loads the value of A from memory.
9. The CPU writes the value of A to the console.
10. The program counter is incremented to point to the next instruction, which is the end of the program.
➢ A programming language is a set of symbols, grammars and rules with the help of which one is able to translate
algorithms to programs that will be executed by the computer.
➢ The programmer communicates with a machine using programming languages.
➢ Most of the programs have a highly structured set of rules.
1. Machine Languages
2. Assembly Languages
3. High level Languages.
Machine Language
➔ Machine language is a collection of binary digits or bits that the computer reads and interprets.
➔ Machine language is the only language a computer is capable of understanding.
➔ Machine level language is a language that supports the machine side of the programming or does not provide
human side of the programming.
➔ It consists of (binary) zeros and ones.
➔ Each instruction in a program is represented by a numeric code, and numerical addresses are used
throughout the program to refer to memory locations in the computer’s memory.
➔ Microcode allows for the expression of some of the more powerful machine level instructions in terms of a
set of basic machine instructions.
Assembly language
➔ High level language is a language that supports the human and the application sides of the programming.
➔ A language is a machine independent way to specify the sequence of operations necessary to accomplish a
task.
➔ A line in a high level language can execute powerful operations, and correspond to tens, or hundreds, of
instructions at the machine level.
➔ Consequently, more programming is now done in high level languages.
➔ Examples of high level languages are BASIC, FORTRAN etc
Algorithm:
OR
A procedure for solving a mathematical problem in a finite number of steps that frequently involves recursive
operations
Properties of Algorithm:
5. Effectiveness: Every step must be basic and easy to convert into program.
Example:
Algorithm:
Step-1: Start
Step-6: Stop
Q 9. What is FlowChart?
Q 10. Define flowchart. List the different symbols used to draw a flowchart ?
OR
9
➔ The pseudocode in C is an informal way of writing a program for better human understanding.
➔ It is written in simple English, making the complex program easier to understand.
➔ Pseudocode cannot be compiled or interpreted.
➔ It doesn't follow the programming language's syntax;
➔ It is thus written in pseudocode so that any programmers or non-programmers can easily understand it.
1. Start
2. Input two numbers
3. Calculate the sum of the two numbers
4. Divide the sum by 2 to get the average
5. Display the average
6. End
➔ The compiler program translates the instructions of a high level language to a machine level language.
➔ A separate compiler is required for every high level language.
➔ High level language is simply a programmer’s convenience and cannot be executed in their source.
➔ The actual high - level program is called a source program.
➔ It is compiled (translated) to machine level language program called object program for that machine by the
compiler.
➔ Such compilers are called self-resident compilers.
➔ Compiler compiles the full program and reports the errors at the end
Compilation Process
Preprocessing Using a Preprocessor program to convert C source code in expanded source code. "#include"
and "#define" statements will be processed and replaced actually source codes in this step.
Compilation Using a Compiler program to convert C expanded source to assembly source code.
Assembly Using a Assembler program to convert assembly source code to object code.
Linking Using a Linker program to convert object code to executable code. Multiple units of object codes are
linked to together in this step.
Loading Using a Loader program to load the executable code into CPU for execution. Compilation
LINKING
➔ After all of the files are compiled, they must be "merged together" to produce a single executable file that the
user use to run the program.
➔ In C, most compiled programs produce results only with the help of some standard programs, known as library
files that reside in the computer.
➔ This process is called linking. The result obtained after linking is called the executable file.
➔ The linker′s primary function is to bind symbolic names to memory addresses.
➔ To do this, it first scans the files and concatenates the related file sections to form one large file.
➔ Then, it makes a second pass on the resulting file to bind symbol names to real memory addresses.
➔ Loading is loading the executable into memory prior to execution.
➔ There are two types of linking: Static linking. Dynamic linking.
o Static linking occurs at compilation time; hence it occurs prior to loading a program.
o With static linking the external symbols that are used by the program (e.g. function names) are resolved
at compile time.
o Dynamic linking occurs at run time, so it occurs after or at the time of the loading of a program.
o With dynamic linking the symbols are resolved either at loading time, or at run time when the symbol
is accessed (lazy binding).
LOADING
➔ After the files are compiled and linked the executable file is loaded in the computer′s memory for executing by
the loader. This process is called Loading.
➔ Program loading is basically copying a program from secondary storage into main memory so it ′s ready to run.
➔ In some cases, loading us just not copying the data from disk to memory, but also setting protection bits, or
arranging for virtual memory map virtual addresses to disk pages.
11
➔ The file which contains c program instructions in a high-level language is said to be source code.
➔ Every c program source file is saved with .c extension, for example, Sample.c.
➔ Whenever we press compilation button the source file is submitted to the compiler.
➔ Compiler checks for the errors, if there are any errors, it returns a list of errors, otherwise generates object
code in a file with name Sample.obj and submit it to the linker.
➔ The linker combines the code from specified header file into an object file and generates executable file as
Sample.exe.
➔ With this compilation process completes. Now, we need to run the executable file (Sample.exe).
➔ To run a program, we press run button.
➔ When we press run button the executable file is submitted to the CPU.
➔ Then CPU performs the task according to the instructions written in that program and place the result into
User Screen.
➢ C is a structured programming language. Every C program and its statements must be in a particular structure.
➢ Every C program has the following general structure.
12
1. Documentation Section:
➢ This section is used to provide a small description of the program.
➢ The comment lines are simply ignored by the compiler, that means they are not executed.
➢ In C, there are two types of comments.
1. Single Line Comments: Single line comment begins with // symbol. We can write any number of single line
comments.
2. Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends with */. We can write
any number of multiple lines comments in a program.
All the comment lines in a C program just provide the guidelines to understand the program and its code.
2. Pre-processing Commands:
➢ Pre-processing commands are used to include header files and to define constants.
➢ Pre-processing commands are beginning with # symbol.
➢ C Pre-processing commands are: #include, #define, #if, #else etc…,
3. Global Declarations:
➢ The global declaration is used to define the global variables, which are common for all the functions after
its declaration.
➢ We also use the global declaration to declare functions.
4. Main Function:
➢ Every C program must contain this main function.
➢ Here, main ( ) is a user-defined function which tells the compiler that this is the starting point of the
program execution.
➢ The open brace ( { ) indicates the beginning of the main function.
➢ Local declaration contains local variables which are used with in main ( ) function.
➢ Executable statements perform tasks like reading data, displaying the result, calculations, etc.,
➢ Closing Brace ( } )indicates the end of the main ( ) function.
➢ The statement return 0 returns a value zero to the Operating System after completing the main ( )
execution.
➢ If we don't want to return any value, we can use it as void.
➢ A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
➢ There are the following data types in C language.
13
1. Integer:
2. Floating Point:
➢ Floating-point data types are a set of numbers with the decimal value.
➢ We use the keyword "float" to represent floating-point data type and "double" to represent double data type
in C.
➢ The following table provides complete details about floating-point data types.
3. Character:
Variable:
Declaration:
Declaration of a variable tells the compiler to allocate the required amount of memory with the specified
variable name and allows only specified datatype values into that memory location.
Syntax:
Example:
int number;
The above declaration tells to the compiler that allocates 2 bytes of memory with the name number and allows only
integer values into that memory location.
Initialization:
2. A variable can start with a letter or an underscore ( _ ), but not with a digit.
Variable_1 is Valid
16
4. Special symbols like !, @, #, $, % etc. are not allowed in variables except one special symbol underscore ( _ ).
Example:
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
2. Type Casting:
Example:
int totalMarks = 450, maxMarks = 600 ;
float average ;
average = (float) totalMarks / maxMarks * 100 ;
Explaination:
In the above example code, both totalMarks and maxMarks are integer data values. When we perform
totalMarks / maxMarks the result is a float value, but the destination (average) datatype is a float. So we use
type casting to convert totalMarks and maxMarks into float data type.
19
Drawbacks
➢ The top-down approach is that it may have redundancy since every part of the code is developed separately.
➢ Also, there is less interaction and communication between the modules in this approach.
➢ Bottom-Up Approach is one in which the smaller problems are solved, and then these solved problems are
integrated to find the solution to a bigger problem.
➢ Therefore, it uses composition approach.
➢ It requires a significant amount of communication among different modules.
➢ It is generally used with object oriented programming paradigm such as C++, Java, and Python.
➢ Data encapsulation and data hiding is also implemented in this approach.
➢ The bottom-up approach is generally used in testing modules.
20
In this approach, the problem is broken down into In this approach, the smaller problems are solved.
1.
smaller parts.
It does not require communication between It requires relatively more communication between
4.
modules. modules.
The implementation depends on the programming Data encapsulation and data hiding is implemented
7.
language and platform. in this approach.
➢ Time complexity refers to the amount of time an algorithm takes to run as a function of the size of its input.
➢ It is usually expressed in terms of "big O" notation, which gives an upper bound on the growth rate of the
algorithm's running time.
➢ For example, an algorithm with a time complexity of O(n) means that its running time grows linearly with the
size of the input.
21
➢ Space complexity, on the other hand, refers to the amount of memory an algorithm requires to run as a
function of the size of its input.
➢ It is also expressed in terms of big O notation.
➢ For example, an algorithm with a space complexity of O(n) means that it requires a linear amount of memory
to run as the size of the input grows.
It's important to consider both time and space complexity when analyzing algorithms, as they can have a
significant impact on the performance and efficiency of the algorithm. Generally, we want algorithms with lower time
and space complexities, as they will be faster and require less memory to run.
Important Questions
9. Write a C Program
UNIT - II
Control Structures
Null statement means it executes nothing in the program that means it performs no operation.
Example:
; → it is a null statement
Importance:
It is useful when the syntax of the language calls for a statement but no expression evaluation.
1. Simple if
2. if-else statement
1. Simple if:
In simple if, if the condition is true, then True block statements are executed. Simple if does not concentrate on the
False condition.
23
Explanation: In the above program user need to entered integer value 20 is stored in variable “n” using if condition
modulo operation 20%5 then remainder is “0”. The given condition is True the if block statement is executed...
2. if-else statement:
In if-else-if statement, if the condition is true then True block statements are executed otherwise False block
statements are executed.
24
It is used in the scenario where there are multiple cases to be performed for different conditions.
In if-else-if ladder statement, if a condition is true then the statements defined in the if block will be executed,
otherwise if some other condition is true then the statements defined in the else-if block will be executed, at the last
if none of the condition is true then the statements defined in the else block will be executed.
25
26
Nested-if statement:
Output:
27
Switch statement:
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations
for the different possible values of a single variable called switch variable.
Here, we can define various statements in the multiple cases for the different values of a single variable.
The looping statements are used to execute a single statement or block of statements repeatedly until the given
condition is FALSE.
1. do-while
2. while
3. for
1. do-while statement:
The do-while statement is used to execute a single statement or block of statements repeatedly until given condition
is False.
The do-while statement is also known as the Exit control looping statement.
2. while statement:
The while statement is used to execute a single statement or block of statements repeatedly until given condition is
False.
The while statement is also known as the Exit control looping statement.
30
3. for statement:
The for statement is used to execute a single statement or block of statements repeatedly until given condition is
False.
31
2. break statement is also used to terminate looping statements like while, dowhile and for.
32
➢ The continue statement is used to move the program execution control to the beginning of the looping
statement.
➢ The continue statement can be used with looping statements like while, do-while and for.
➢ When we use continue statement with while and do-while statements the execution control directly jumps to
the condition.
➢ When we use continue statement with for statement the execution control directly jumps to the modification
portion (increment/decrement/any modification) of the for loop.
➢ The continue statement execution is as shown in the following figure.
33
Program:
Output:
34
Important Question
1. Define null statement.
2. Write syntax and flow chart for if-else statement.
3. Define conditional statements.
4. Define looping statements.
5. Write syntax for do-while statement.
6. Write differences between while and do-while
7. Write a C program to print 1 to 10 natural number using for loop?
8. Write a C program to print given pattern using while loop?
*
**
***
****
9. Write a C program to print 10 to 1 natural number using do…while loop?
10. Write a C program to find greatest among two numbers using if-else condition?
11. Write a C program to print whether even or odd number using if-else condition?
12. Write a C program to print multiplication table using for loop?
5*1=5
5*2=10..
35
Unit III
Arrays and Strings
Initialization of Array:
Syntax for creating an array with size and initial values.
datatype arrayName [ size ] = {value1, value2, ...} ;
Example
int a[5] = {1, 2, 3, 4, 5};
Here, an array ‘a’ stores 5 values.
Syntax for creating an array without size and with initial values
datatype arrayName [ ] = {value1, value2, ...} ;
Example
int a[ ] = {1, 2, 3, 4, 5};
Here, an array ‘a’ stores 5 values.
36
1. Text Segment:
➔ A text segment, also known as a code segment or simply as text, is one of the sections of a program
in an object file or in memory, which contains executable instructions.
➔ As a memory region, a text segment may be placed below the heap or stack in order to prevent
heaps and stack overflows from overwriting it.
➔ Usually, the text segment is sharable so that only a single copy needs to be in memory for frequently
executed programs, such as text editors, the C compiler, the shells, and so on. Also, the text segment
is often read-only, to prevent a program from accidentally modifying its instructions.
➔ Uninitialized data segment often called the “bss” segment, named after an ancient assembler
operator that stood for “block started by symbol.”
➔ Data in this segment is initialized by the kernel to arithmetic 0 before the program starts executing
uninitialized data starts at the end of the data segment and contains all global variables and static
variables that are initialized to zero or do not have explicit initialization in source code.
➔ For instance, a variable declared static int i; would be contained in the BSS segment.
➔ For instance, a global variable declared int j; would be contained in the BSS segment.
38
4. Stack:
➔ The stack area traditionally adjoined the heap area and grew in the opposite direction; when the
stack pointer met the heap pointer, free memory was exhausted. (With modern large address
spaces and virtual memory techniques they may be placed almost anywhere, but they still typically
grow in opposite directions.)
➔ The stack area contains the program stack, a LIFO structure, typically located in the higher parts of
memory. On the standard PC x86 computer architecture, it grows toward address zero; on some
other architectures, it grows in the opposite direction.
➔ A “stack pointer” register tracks the top of the stack; it is adjusted each time a value is “pushed”
onto the stack.
➔ The set of values pushed for one function call is termed a “stack frame”;
➔ A stack frame consists at minimum of a return address.
Stack, where automatic variables are stored, along with information that is saved each time a
function is called.
➔ Each time a function is called, the address of where to return to and certain information about the
caller’s environment, such as some of the machine registers, are saved on the stack.
➔ The newly called function then allocates room on the stack for its automatic variables.
➔ This is how recursive functions in C can work.
➔ Each time a recursive function calls itself, a new stack frame is used, so one set of variables doesn’t
interfere with the variables from another instance of the function.
5. Heap:
➔ Heap is the segment where dynamic memory allocation usually takes place.
➔ The heap area begins at the end of the BSS segment and grows to larger addresses from there.
➔ The Heap area is managed by malloc, realloc, and free, which may use the brk and sbrk system calls
to adjust its size (note that the use of brk/sbrk and a single “heap area” is not required to fulfill the
contract of malloc/realloc/free; they may also be implemented using mmap to reserve potentially
non-contiguous regions of virtual memory into the process’ virtual address space).
➔ The Heap area is shared by all shared libraries and dynamically loaded modules in a process.
39
Program:
#include <stdio.h>
int main()
{
int arr[N];
int i, N;
printf("Enter size of array: ");
scanf("%d", &N);
printf("Enter %d elements in the array : ", N);
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
printf("\nElements in array are: ");
for(i=0; i<N; i++)
{
printf("%d, ", arr[i]);
}
return 0;
}
Output:
Program:
#include <stdio.h>
int main()
{
int arr[N];
int i, N;
printf("Enter size of the array : ");
scanf("%d", &N);
printf("Enter elements in array : ");
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
printf("\nAll negative elements in array are : ");
for(i=0; i<N; i++)
{
if(arr[i] < 0)
{
printf("%d\t", arr[i]);
}
}
return 0;
}
Output:
Program:
#include <stdio.h>
# define SIZE 20
int main()
{
int size, i;
int arr[SIZE],max1, max2;
printf("Enter size of the array (1-1000): ");
scanf("%d", &size);
printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
max1 = max2 = arr[0];
for(i=0; i<size; i++)
{
if(arr[i] > max1)
{
max2 = max1;
max1 = arr[i];
}
else if(arr[i] > max2 && arr[i] < max1)
{
max2 = arr[i];
}
}
printf("First largest = %d\n", max1);
printf("Second largest = %d", max2);
return 0;
}
Output:
Program:
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE], freq[MAX_SIZE];
int size, i, j, count;
printf("Enter size of array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
freq[i] = -1;
}
for(i=0; i<size; i++)
{
count = 1;
for(j=i+1; j<size; j++)
{
if(arr[i] == arr[j])
{
count++;
freq[j] = 0;
}
}
if(freq[i] != 0)
{
freq[i] = count;
}
}
printf("\nUnique elements in the array are: ");
for(i=0; i<size; i++)
{
if(freq[i] == 1)
{
printf("%d ", arr[i]);
}
}
43
return 0;
}
Output:
Program:
#include <stdio.h>
#define MAX_SIZE 100 // Defines maximum size of array
int main()
{
int arr[MAX_SIZE];
int size, i;
printf("Enter size of the array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
printf("\nArray in reverse order: ");
for(i = size-1; i>=0; i--)
{
printf("%d\t", arr[i]);
}
return 0;
}
Output:
We use the following general syntax for declaring a single dimensional array
Example
The above declaration of single dimensional array reserves 60 continuous memory locations of 2 bytes each
with the name rollNumbers and tells the compiler to allow only integer values into those memory locations.
We use the following general syntax for declaring and initializing a single dimensional array with size and
initial values.
The above declaration of single dimensional array reserves 6 contiguous memory locations of 2 bytes each
with the name marks and initializes with value 89 in first memory location, 90 in second memory location,
76 in third memory location, 78 in fourth memory location, 98 in fifth memory location and 86 in sixth
memory location.
➔ We can also use the following general syntax to intialize a single dimensional array without
specifying size and with initial values.
➔ The array must be initialized if it is created without specifying any size. In this case, the size of the
array is decided based on the number of values initialized.
Example:
In the above example declaration, size of the array 'marks' is 6 and the size of the array 'studentName' is 16.
This is because in case of character array, compiler stores one extra character called \0 (NULL) at the end
2. Multi-Dimensional Array:
➢ If an array contains more than one subscript is known as multi-dimensional array.
➢ Multi-dimensional array can be of two dimensional array or three dimensional array or four
dimensional array or more.
➢ Most popular and commonly used multi-dimensional array is two dimensional array.
➢ The 2-D arrays are used to store data in the form of table.
➢ We also use 2-D arrays to create mathematical matrices.
➔ We use the following general syntax for declaring a two dimensional array.
Example
int matrix_A [2][3] ;
The above declaration of two dimensional array reserves 6 continuous memory locations of 2 bytes each in
the form of 2 rows and 3 columns.
➔ We use the following general syntax for declaring and initializing a two dimensional array with
specific number of rows and coloumns with initial values.
Example
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;
The above declaration of two-dimensional array reserves 6 contiguous memory locations of 2 bytes each in
the form of 2 rows and 3 columns. And the first row is initialized with values 1, 2 & 3 and second row is
initialized with values 4, 5 & 6.
46
Example
{1, 2, 3},
{4, 5, 6}
};
➢ To access elements of a two-dimensional array we use array name followed by row index value and
column index value of the element that to be accessed.
➢ Here the row and column index values must be enclosed in separate square braces.
➔ We use the following general syntax to access the individual elements of a two-dimensional array...
Example
matrix_A [0][1] = 10 ;
In the above statement, the element with row index 0 and column index 1 of matrix_A array is assinged
with value 10.
String:
Creating a String:
2. char str2[20];
➢ gets() function is used to read a string from standard input device and puts is used to display a string on
standard output device.
➢ gets() and puts() functions are defined in stdio.h header file
Example:
#include<stdio.h>
int main()
{
char s[20];
printf("Enter a String: ");
gets(s);
printf("Your String is: ");
puts(s);
return 0;
}
Output:
Example Programs :
14. Write a C Program to Concatenate two strings without built-in functions
Source Code:
#include<stdio.h
void main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}
Output:
#include <stdio.h>
#include <string.h>
int main()
{
char str[50]; // size of char string
int i, len, temp;
printf (" Enter the string: ");
gets(str); // use gets() function to take string
printf(" \n Before reversing the string: %s \n", str);
len = strlen(str); // use strlen() to get the length of str string
for (i = 0; i < len/2; i++)
{
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
printf (" After reversing the string: %s", str);
}
Output:
Output:
Unit IV
Pointer:
A pointer is a variable which holds memory address of another variable. Pointers are powerful tools that allow direct
memory access and manipulation.
Declaring Pointer:
Declaration of pointer variable is similar to the creation of normal variable but the name is prefixed with *
symbol.
Syntax:
datatype *pointerName ;
Example:
int *ptr ;
In the above example declaration, the variable "ptr" is a pointer variable that can be used to store any integer
variable address.
Initializing a Pointer:
To assign address to a pointer variable we use assignment operator with the following syntax.
Example:
ptr = &a ;
➢ We use the symbol "*" in front of pointer variable name to access the value of variable to which the pointer
is pointing.
Syntax:
*pointerVariableName
Example Code
#include<stdio.h>
int main()
{
int a = 10, *ptr ;
ptr = &a ;
printf("Address of variable a = %u\n", ptr) ;
printf("Value of variable a = %d\n", *ptr) ;
printf("Address of variable ptr = %u\n", &ptr) ;
return 0;
}
Output:
Value of variable a = 10
➢ In c language, we use the reference operator "&" to access the address of variable.
➢ For example, to access the address of a variable "marks" we use "&marks".
➢ We use the following printf statement to display memory location address of variable "marks".
➢ Example:
printf("Address : %u", &marks) ;
➢ In the above example statement %u is used to display address of marks variable.
➢ Address of any memory location is unsigned integer value.
➢ A pointer variable to store the address of another pointer variable is called a pointer to pointer variable.
➢ Sometimes we also call it a double pointer.
Syntax:
datatype **pointerName ;
Example:
int a;
p1 = &a;
p2 = &p1;
p3 = &p2
Note:
2. To store the address of single pointer variable we use double pointer variable
3. To store the address of double pointer variable we use triple pointer variable
➢ A void pointer is a pointer variable used to store the address of a variable of any datatype.
➢ That means single void pointer can be used to store the address of integer variable, float variable, character
variable, double variable or any structure variable
➢ We use the keyword "void" to create void pointer.
Syntax:
void *pointerName ;
Example:
int a;
float b;
void *p1, *p2;
p1 = &a;
p2 = &b;
55
2. Subtraction:
➢ When a pointer is subtracted with an integer value, the value is first multiplied by the size of the data type
and then subtracted from the pointer similar to addition.
➢ The subtraction operation on pointer variables is calculated using the following formula:
AddressAtPointer - ( NumberToBeAdd * Datatype_Size )
For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as an address.
If we subtract integer 5 from it using the expression, ptr = ptr – 5, then,
the final address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.
56
3. Increment:
➢ Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually
increments by the number equal to the size of the data type for which it is a pointer.
➢ The increment operation on pointer variable is calculated as follows:
AddressAtPointer + Datatype_size
For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of an int), and the new
address will point to 1004. While if a float type pointer is incremented then it will increment by 4(size of a float) and
the new address will be 1004.
4. Decrement
➢ It is a condition that also comes under subtraction. When a pointer is decremented, it actually decrements by
the number equal to the size of the data type for which it is a pointer.
➢ The decrement operation on pointer variable is calculated as follows:
AddressAtPointer - NumberOfBytesRequiresByDatatype
For Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size of an int), and the new
address will point to 996. While if a float type pointer is decremented then it will decrement by 4(size of a float) and
the new address will be 996.
5. Comparison
➢ We can compare the two pointers by using the comparison operators in C.
➢ We can implement this by using all operators in C >, >=, <, <=, ==, !=.
➢ It returns true for the valid condition and returns false for the unsatisfied condition.
➢ The comparison operation is performing between the pointers of same datatype only.
➢ In c programming language, we can use all comparison operators (relational operators) with pointers.
57
✓ Pointers and Array representations are very much related to each other and can be interchangeably used in
the right context.
✓ An array name is generally treated as a pointer to the first element of the array and if we store the base
address of the array in another pointer variable, then we can easily manipulate the array using pointer
arithmetic in a C Program.
Syntax
*(arr + i)
we denote array elements as arr[i], where i is the index value. Below is a similar syntax in terms of pointers of how we
can represent the array elements using the dereferencing operator (*) on the array name i.e. using the pointers
property of the array.
➔ * is a dereferencing operator used to extract the value from the address (arr + i).
➔ *(arr + i) is the same as arr[i] in a C Program.
➔ arr represents the array name and i represents the index value.
Example
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = {2, 4, 6, 8, 10}, i;
for(i = 0; i < 5; i++)
{
// printing the elements address and value at
// arr[i] using *(arr + i) syntax
printf("[index %d] Address : %u, Value : %d\n", i, (arr + i), *(arr + i));
}
return 0;
}
Output :
[index 0] Address : 2364420656, Value : 2
[index 1] Address : 2364420660, Value : 4
[index 2] Address : 2364420664, Value : 6
[index 3] Address : 2364420668, Value : 8
[index 4] Address : 2364420672, Value : 10
Explanation :
✓ (arr + i) represents the address of the value at index i, so *(arr + i) will give the value at ith index (address(arr + i)
= address(arr[i])), it is used to print the addresses of the array elements as the value of i changes from 0-4
✓ * is a dereferencing operator used for printing the value at the provided address. *(arr + i) will print the values of
the array at consecutive addresses as the value of i changes from 0-4.
Q 8. Define static memory allocation. What are its limitations.
Limitations:
➢ When we create an array, we must specify the size at the time of the declaration itself and it cannot be
changed during the program execution.
➢ This is a major problem when we do not know the number of values to be stored in an array.
➢ Allocation of memory during the program execution is called dynamic memory allocation.
➢ We use pre-defined functions to allocate memory dynamically.
➢ There are FOUR pre-defined functions that are defined in the header file known as "stdlib.h".
1. malloc()
2. calloc()
3. realloc()
4. free()
1. malloc():
➢ malloc() is the pre-defined function used to allocate a memory block of specified number of bytes and
returns void pointer.
➢ The void pointer can be casted to any datatype. If malloc() function unable to allocate memory due to any
reason it returns NULL pointer.
Syntax:
void* malloc(size_in_bytes)
Example:
char *title;
title = (char *) malloc(15);
59
2. calloc():
➢ calloc() is the pre-defined function used to allocate multiple memory blocks of the specified number of bytes
and initializes them to ZERO.
➢ calloc() function returns void pointer.
➢ If calloc() function unable to allocate memory due to any reason it returns a NULL pointer.
➢ Generally, calloc() is used to allocate memory for array and structure.
o calloc() function takes two arguments and they are
o The number of blocks to be allocated
➢ Size of each block in bytes
Syntax:
void* calloc(number_of_blocks, size_of_each_block_in_bytes)
Example:
int *ptr;
ptr = (int*)calloc(5, sizeof(int));
3. realloc():
➢ realloc() is the pre-defined function used to modify the size of memory blocks that were previously allocated
using malloc() or calloc().
➢ realloc() function returns void pointer.
➢ If realloc() function unable to allocate memory due to any reason it returns NULL pointer.
Syntax
void* realloc(*pointer, new_size_of_each_block_in_bytes)
Example:
char *title;
title = (char *) malloc(15);
title = (char*) realloc(title, 30);
4. free():
➢ free() is the pre-defined function used to deallocate memory block that was previously allocated using
malloc() or calloc().
Syntax
void free(*pointer)
Example:
char *title;
title = (char *) malloc(15);
free(title);
60
{
//store first employee information
e1.id=101;
e1.name = "Ajay");
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Ajay
#include<stdio.h>
struct student
{
int rollno;
62
char name[10];
};
int main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
63
Q 14. Define union. Explain creation of union and accessing union members.
Union:
Union is a collection of different datatype elements which can be referred under a single name.
Creating Union:
To create union, we use the keyword called “union”.
Syntax:
union union_name
{
// Union members
data_type member1;
data_type member2, member3;
….
};
union union_name union_varaibles;
Example:
union Student
{
// union members
64
char stud_name[30];
int roll_number;
float percentage;
};
// union variables
union Student s1,s2;
Accessing Union Members:
We use union variables to access structure members with dot(.) operator.
Syntax:
Union_varaible . Union_member
Example:
s1.stud_name
s1.roll_number
s1.percentage
Q 15 How much memory is allocated for a Union?
➢ The memory is allocated when we create the variable of a particular union.
➢ The size of memory allocated is equal to the maximum memory required by an individual member among all
members of that union.
Unit V
3. Function Call:
➢ The function call tells the compiler when to execute the function definition. When a function call is executed,
the execution control jumps to the function definition where the actual code gets executed and returns to
the same functions call once the execution completes.
➢ The function call is performed inside the main function or any other function or inside the function itself.
Syntax
functionName(parameters);
Example:
add(15, 20);
Q 2. define parameter. What are its types.
➢ Parameters are the data values that are passed from calling function to called function.
➢ Parameters are also called as arguments.
➢ In C, there are two types of parameters and they are as follows...
o Actual Parameter
o Formal Parameters
➢ The actual parameters are the parameters that are specified in calling function.
➢ The formal parameters are the parameters that are declared at called function.
➢ When a function gets executed, the copy of actual parameter values are copied into formal parameters.
#include<stdio.h>
int addition(int,int) ; // function declaration
int main()
{
int num1, num2,
result ;
printf("Enter any two integer numbers : ");
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("SUM = %d", result);
return 0;
}
int addition(int a, int b) // function definition
{
return a + b ;
}
Output:
Enter any two integer numbers : 23 54
SUM = 77
In the above example addition() is user defined function.
Q 5. Explain different types of functions based on parameters and return values?
Based on parameters and return types, functions are classified into 4 types:
1. Function without parameters and without return values
2. Function with parameters and without return values
3. Function without parameters and with return values
4. Function with parameters and with return values
69
Example Program
#include<stdio.h>
void addition(int, int) ; // function declaration
int main()
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
return 0;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
70
#include<stdio.h>
int addition() ; // function declaration
int main()
{
int result ;
result = addition() ; // function call
printf("Sum = %d", result) ;
return 0;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
4. Function with parameters and with return values:
These types of functions contain both parameters and return values.
Example Program
#include<stdio.h>
int main()
{
int num1, num2, result ;
int addition(int, int) ; // function declaration
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
return 0;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50
71
Example Program
#include<stdio.h>
void swap(int*, int*) ; // function declaration
int main()
{
int num1, num2 ;
printf("Enter two numbers: ");
scanf("%d%d",&num1,&num2);
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
return 0;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Output:
Enter two numbers: 10 20
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10
Q 7 Explain the Pass arrays to a function in C
➢ In C programming, you can pass an entire array to functions.
➢ To pass array to a function, only the name of the array is passed to the function (similar to one-dimensional
arrays).
Example Program:
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float num[]);
int main()
{
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
73
sum += num[i];
}
return sum;
}
Output:
Result = 162.50
Explanation:
To pass an entire array to a function, only the name of the array is passed as an argument.
result = calculateSum(num);
However, notice the use of [] in the function definition.
float calculateSum(float num[])
{
... ..
}
This informs the compiler that you are passing a one-dimensional array to the function.
Q 8. Explain Pass Multidimensional Arrays to a Function in C.
➢ To pass multidimensional arrays to a function, only the name of the array is passed to the function (similar to
one-dimensional arrays).
Example Program:
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
// pass multi-dimensional array to a function
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2]) {
printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
74
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
Explanation:
➢ Note the parameter int num[2][2] in the function prototype and function definition:
// function prototype
void displayNumbers(int num[2][2]);
➢ This signifies that the function takes a two-dimensional array as an argument. We can also pass arrays with
more than 2 dimensions as a function argument.
➢ When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array.
However, the number of columns should always be specified.
For example,
void displayNumbers(int num[][2])
{
// code
}
Q 9. Explain the Scope of Variables in C?
➢ The availability of a variable in a program or function is referred to as the scope of variable in C language.
➢ A variable, for example, may be accessed only within a single function/block of code (your apartment key) or
throughout the whole C program (the shared access key).
➢ We can associate the room keys with the local variables in C language because they only work in that single
room. The term global variables refers to variables (keys) that are accessible to the whole program
(apartment complex).
Q 10. Define local and global variables.
Local Variable:
➢ Local variable is declared inside a function.
➢ Local variables are created when the function has started execution and is lost when the function terminates.
➢ If a value of local variable is updated, it will effect within that function only.
Example:
#include <stdio.h>
int main()
{
int x = 30;
75
Q 12. Define storage class. What are the storage classes in C. Explain with example?
➢ Storage classes are used to define storage location (whether RAM or Register), scope, lifetime and the default
value of a variable.
➢ In C language, there are FOUR storage classes and they are as follows:
1. auto storage class
2. static storage class
3. register storage class
4. extern storage class
1. auto storage class:
➔ The default storage class of all local variables (variables declared inside block or function) is auto storage
class.
➔ Variable of auto storage class has the following properties:
77
➔ The static storage class is used to create variables that hold value beyond its scope until the end of the
program.
➔ The static variable allows to initialize only once and can be modified any number of times.
➔ Variable of static storage class has the following properties:
78
➔ The register storage class is used to specify the memory of the variable that has to be allocated in CPU
Registers.
➔ The register variables enable faster accessibility compared to other storage class variables.
➔ As the number of registers inside the CPU is very less we can use very less number of register variables.
➔ Variable of register storage class has the following properties:
79
➔ The default storage class of all global varibles (variables declared outside function) is external storage class.
➔ Variable of external storage class has the following properties:
80
➔ File handing in C is the process in which we create, open, read, write, and close operations on a file.
➔ C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform
input, output, and many different C file operations in our program.
➔ The operations using the C program are done on a prompt/terminal which is not stored anywhere.
➔ The output is deleted when the program is closed. But in the software industry, most programs are written to
store the information fetched from the program.
➔ The use of file handling is exactly what the situation calls for.
➔ In order to understand why file handling is important, a few features of using files:
Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and anytime providing high
reusability.
Portability: Without losing any data, files can be transferred to another in the computer system. The risk of flawed
coding is minimized with this feature.
Efficient: A large amount of input may be required for some programs. File handling allows you to easily access a part
of a file using few instructions which saves a lot of time and reduces the chance of errors.
Storage Capacity: Files allow you to store a large amount of data without having to worry about storing everything
simultaneously in a program.
A file can be classified into two types based on the way the file stores the data. They are as follows:
1. Text Files
2. Binary Files
1. Text Files
A text file contains data in the form of ASCII characters and is generally used to store a stream of characters.
• Each line in a text file ends with a new line character (‘\n’).
• It can be read or written by any text editor.
• They are generally stored with .txt file extension.
• Text files can also be used to store the source code.
81
2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They contain data that is stored
in a similar manner to how it is stored in the main memory.
• The binary files can be created only from within a program and their contents can only be read by a program.
• More secure as they are not easily readable.
• They are generally stored with .bin file extension.
The different possible operations that we can perform on a file in C such as:
➔ Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
➔ Opening an existing file – fopen()
➔ Reading from file – fscanf() or fgets()
➔ Writing to a file – fprintf() or fputs()
➔ Moving to a specific location in a file – fseek(), rewind()
➔ Closing a file – fclose()
82
A file pointer is a reference to a particular position in the opened file. It is used in file handling to perform all file
operations such as read, write, close, etc. We use the FILE macro to declare the file pointer variable. The FILE macro is
defined inside <stdio.h> header file.
FILE* pointer_name;
Q 18. Explain how to open a file and File opening modes in C language.
The fopen() function is used with the filename or file path along with the required access modes.
Syntax of fopen()
Parameters
file_name: name of the file when present in the same directory as the source file. Otherwise, full path.
Return Value
File opening modes or access modes specify the allowed operations on the file to be opened. They are passed as an
argument to the fopen() function. Some of the commonly used file access modes are listed below:
Opening
Modes Description
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
r
points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
Open for writing in text mode. If the file exists, its contents are overwritten. If the file doesn’t exist, a new
w
file is created. Returns NULL, if unable to open the file.
Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it
wb
will be created.
83
Opening
Modes Description
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
a points to the last character in it. It opens only in the append mode. If the file doesn’t exist, a new file is
created. Returns NULL, if unable to open the file.
Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be
ab
created.
Searches file. It is opened successfully fopen( ) loads it into memory and sets up a pointer that points to
r+
the first character in it. Returns NULL, if unable to open the file.
rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL.
Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created.
w+
Returns NULL, if unable to open the file.
Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file
wb+
does not exist, it will be created.
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that
a+ points to the last character in it. It opens the file in both reading and append mode. If the file doesn’t exist,
a new file is created. Returns NULL, if unable to open the file.
ab+ Open for both reading and appending in binary mode. If the file does not exist, it will be created.
There are many functions in the C library to open, read, write, search and close the file. A list of file functions are
given