Programming For Problem Solving Notes
Programming For Problem Solving Notes
COMPONENTS OF A COMPUTER
Computer is a combination of hardware and software. Hardware is the physical component of a
computer like motherboard, memory devices, monitor, keyboard etc., while software is the set of
programs or instructions. Both hardware and software together make the computer system.
1. Input Unit
Input unit is used to feed any form of data to the computer, which can be stored in the memory
unit for further processing. Example: Keyboard, mouse, light pen, joy stick etc.
2 Central Processing Unit
CPU is the major component which interprets and executes software instructions. It also control
the operation of all other components such as memory, input and output units. It accepts binary
data as input, process the data according to the instructions and provide the result as output. The
CPU has three components which are Control unit, Arithmetic and logic unit (ALU) and Memory
unit.
2.1 Arithmetic and Logic Unit
FUNDAMENTALS OF C
C programming is a general-purpose, procedural, imperative computer programming language
developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX
operating system. Dennis Ritchie is known as the founder of the C language.
____________________________________________________________________________
COMPILATION PROCESS IN C
Compilation is a process of converting the source code into object code.
The compilation process in C can be divided into four steps, i.e., Pre-processing, Compiling,
Assembling, and Linking.
1. Preprocessing
The source code is the code which is written using a text editor by a programmer. The source
code file is saved with an extension ".c". This source code file is first passed to the preprocessor.
Preprocessor removes all the comments from the source code. Then the preprocessor takes the
preprocessor directive and interprets it. For example, if #include <stdio.h> directive is available
in the program, preprocessor replace this directive with the content of the 'stdio.h' file. Thus the
code is expanded and is passed to the next step. The extension of the expanded file is ‘.i’
2. Compiling
The code which is expanded by the preprocessor is passed to the compiler. The compiler converts
this code into assembly code which contains mnemonics. The extension of the assembly file is
‘.s’
Example
Compilation process of hello.c source code file
o Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor
converts the source code into expanded source code file hello.i.
o The expanded source code is passed to the compiler, and the compiler converts this
expanded source code into assembly code file hello.s.
____________________________________________________________________________
TOKENS
The smallest individual units in a program are known as tokens.
Classification of tokens in C
2) C #define preprocessor
Syntax:
#define value
Data types that are derived from fundamental data types are derived types.
Example: arrays, pointers, structures, unions etc.
3. User Defined Datatypes
Users can define new datatypes. This new datatype can then be used to declare variables. The
main advantage of user defined data type is that it increases the program’s readability.
There are two methods
1. By using typedef
Example
typedef int numbers;
4. void datatype
void is an incomplete type. It means "nothing" or "no type". For example, if a function is not
returning anything, its return type should be void. Variables of void datatype cannot be created.
-----------------------------------------------------------------------------------------------------------------
ALGORITHM
Definition:
1. Identification of input
3. Identification of output
Example
Algorithm to find the area of the square
Step 1 : Start
Step 2: Read the side of the square a.
Step 3: Area = a*a
B.E (II Semester) Programming for Problem Solving 12
Step 4: Output the Area
Step 5: Stop.
________________________________________________________________________
FLOWCHART
Definition:
Description:
Flowchart shows the process involved in solving a problem and the flow of control in a
visual manner. There are three types of control flow.
1. Sequential - Statements are executed one after another in the same order as they
are in the program.
Flow charts are drawn using certain special symbols such as Rectangles, Diamonds, Ovals and
small circles. These symbols are connected by arrows called flow lines.
Pentagon
Uses of Flowchart
PSEUDOCODE
It doesn’t follow the syntax rules of any programming language. But it follows the structural
conventions of a normal programming language.
It is intended for human reading rather than machine reading. It omits the details that are essential
for machine understanding such as variable declaration, header file inclusion etc.
It is easy to write programs from pseudocode rather than flowchart. Pseudo Code is more
commonly used by experienced programmers while Flowchart is by beginners.
We can write Pseudo Code freely as long as it is easy to understand for other persons. But it is
suggested to use commonly used keywords from programs (i.e. if, then, else, while, do, repeat,
for and etc.) and follow certain programming style (i.e. c, Pascal, C++, etc.).
getchar is a simple function to read a single character from the input device.
varname=getchar();
putchar is a simple function to output a single character on the output device.
putchar(varname);
getchar() and putchar() is used only for one input and is not formatted. For formatted input and
output scanf and printf statements are used. . Both functions are library functions, defined in
stdio.h (header file).
Scanf statement
Syntax
scanf("format specifier", &v1, &v2,...&vn);
Format specifier specifies the format in which data is to be entered.
v1,v2 are the variables
Example
scanf("%d%d",&a,&b);
%d used for integers
%f used for floats
%l used for long
%c used for character
%s used for string
printf Statement
Syntax
printf("format specifier ", v1, v2,...vn);
Syntax Error
Each programming language has its own set of rules or syntax to write the program.
Programmer should write the program according to the correct syntax. If not, it will cause an
error. This error type is known as a syntax error. This error occurs at the time of compilation.
It is easy to identify and remove syntax errors because the compiler displays the location
and type of error. Most frequent syntax errors are:
• missing semicolons
• missing curly braces
• undeclared variables
• misspelled keywords or identifiers.
The program will not get compiled until the syntax error is fixed.
Logic Error
Errors which provide incorrect output but appears to be error free are called logical
errors. These errors occur due to faults in algorithm . A program with logical error will not cause
the program to terminate the execution but the generated output is wrong. When a syntax error
occurred, it is easy to detect the error because the compiler specifies about error type and the line
that the error occurs. But identifying a logical error is hard because there is no compiler message.
Therefore, the programmer should read each statement and identify the error on his own. One
example of logical error is the wrong use of operators. If the programmer used division (/)
operator instead of multiplication (*), then it is a logical error.
________________________________________________________________________
B.E (II Semester) Programming for Problem Solving 17
UNIT II
OPERATORS
An operator is a symbol used to perform mathematical, logical and relational operations.
C operators can be classified as
1. Unary Operators
2. Arithmetic operators
3. Relational operators
4. Logical operators
5. Assignment operator
6. Equality operator
7. Conditional operator
8. Bitwise operators
9. Special operators
1. UNARY OPERATORS:
The following table shows all the unary operators supported by the C language. Assume
variable A holds 10 and variable B holds 20
Y = A-- ; y =10
2. ARITHMETIC OPERATORS :
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by denominator. B/A=2
% Modulus Operator and remainder of after an integer B%A=0
division.
3. RELATIONAL OPERATORS :
B.E (II Semester) Programming for Problem Solving 18
The following table shows all the relational operators supported by C. Assume variable A holds
10 and variable B holds 20.
Operator Description Example
> Checks if the value of left operand is greater than the value of (A > B) is
right operand. If yes, then the condition becomes true. not true.
< Checks if the value of left operand i less than the value of right (A < B) is
operand. If yes, then the condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to the (A >= B) is
value of right operand. If yes, then the condition becomes true. not true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand. If yes, then the condition becomes true. true.
4. LOGICAL OPERATORS :
This combines two or more relational expressions. Following table shows all the logical
operators supported by C language. Assume variable A holds 1 and variable B holds 0
5. EQUALITY OPERATORS
7. BITWISE OPERATORS : The following table lists the bitwise operators supported by C for
manipulation of data at bit level. They are not applied to float or double.
8. SPECIAL OPERATORS :
These are the operators which do not fit in any of the above classification.
_________________________________________________________________________________________
OPERATOR PRECEDENCE
Operator Precedence determines the order in which different operations are carried out in an
expression with more than one operators
For example 10 + 20 * 30 is calculated as 10+ (20 * 30) and not as (10 + 20) * 30.
Associativity specifies the direction of evaluating an expression with more than one operators of
same priority. It may be left to right or right to left.
________________________________________________________________
1. if statement
2. switch … case statement
1. If Statement
There are different forms of if statements. They are
• Simple If statement
• If-else statement
• Nested if
• If else-if ladder
i) Simple if statement
This statement is used to check some given condition and perform some operations depending
upon the correctness of that condition.
Syntax
if (expression)
{
//Statement block1 ;
}
Statement2;
Description
If the expression returns true, then statement block1 will be executed, otherwise these statements
are skipped.
Flow Chart
Example:
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
Syntax
if (expression)
{
//statement block1;
}
else
{
// statement block2;
}
Description
If the expression is true, the statement-block1 is executed, else statement-block2 is executed.
Flow Chart
Example:
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
Output
y is greater than x
Example:
#include <stdio.h>
void main( )
{
int a, b, c;
printf("Enter 3 numbers...");
scanf("%d%d%d",&a, &b, &c);
The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario
where there are multiple 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 corresponding 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. It is similar
to the switch case statement where the default is executed instead of else block if none of the
cases is matched.
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
The expression in switch is evaluated and then compared to the values present in different cases.
It executes the block of code which matches the case value. If there is no match, then default
block is executed(if present).
Flowchart
Example :
#include
<stdio.h>
void main()
{
int num;
printf("\n\nEnter a number between 0 - 3
"); scanf("%d",&num);
switch(num)
{
Points to remember
1. The expression (after switch keyword) must yield an integer value not a float value
2. The case values must be unique and must end with a colon(:)
3. break statement is used to exit the switch block. If it is not used, then all the
consecutive blocks of code will get executed after the matching block.
4. default case is executed when none of the case values matches the value of switch
expression.
• if statements can evaluate float conditions. switch statements cannot evaluate float
conditions.
• if statement can evaluate relational operators. switch statement cannot evaluate relational
operators.
[Note: No curly braces are required if there is a single statement inside if part and else part ]
____________________________________________________________________________
Description
The process of execution involves the following steps
Step1: First the index variable gets initialized.
Step 2: The condition is checked, where the index variable is tested for the given condition. If
the condition returns true then the C statements inside the body of for loop gets executed. If the
condition returns false then the for loop gets terminated and the control comes out of the loop.
Step 3: After successful execution of statements inside the body of loop, the index variable is
altered depending on the operation (++ or –).
Flow Chart
printf(“%d”,i)
}
Output
1
2
3
4
5
2. while statement
It is an entry controlled loop. The condition is evaluated and if it is true then body of loop is
executed. After execution of body the condition is once again evaluated and if is true body is
executed once again. This goes on until test condition becomes false.
Syntax
while(condition)
{
// body of the loop
}
Example
/* printing n numbers */
#include<stdio.h>
void main()
{
int n,i = 1;
while(count<=5)
{
printf(“%d”,i);
++i;
}
}
Output
1
2
3
4
5
3. do while statement
do while is an exit controlled loop and its body is executed at least once.
syntax
do
{
//body of the loop
}
while(condition);
Flowchart
1. Break Statement:
Break statement is used to terminate any type of loop e.g, while loop, do while loop or for
loop. The break statement terminates the loop body (jump out of the loop skipping the code
Example
#include<stdio.h>
void main ()
{
int i;
for(i = 1; i<=10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("/ncame outside of loop i = %d",i);
}
Output
12345
2. Continue Statement:
Continue statement 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.
Example
#include <stdio.h>
int main()
{
B.E (II Semester) Programming for Problem Solving 34
int i=1;
label:
printf("%d",i);
i++;
if(i<=5)
goto label;
}
Output
12345
4. return statement
The return statement terminates the execution of a function and returns control to the calling
function. Execution resumes in the calling function at the point immediately following the
calling statement.
____________________________________________________________________________________
Type Casting in C
Typecasting allows us to convert one data type into other. In C language, we use cast operator
for typecasting which is denoted by (type).
Syntax:
(type)value;
int f= 9/4;
printf("f : %d\n", f );
Output: 2
With Type Casting:
UNIT III
What is an Array?
Note:
If there is no free contiguous memory locations as size of array, the declaration of array will
be failed.
Let us consider to find out the average of 100 integer numbers entered by user. In C, you
have two ways to do this:
1) Define 100 variables with int data type and then perform 100 scanf() operations to
store the entered values in the variables and then at last calculate the average of them.
2) Have a single integer array to store all the values, loop the array to store all the
entered values in array and later calculate the average.
From the second solution, it is convenient to store same data types in one single variable and
later access them using array index
Array Declaration:
a. Array datatype,
c. Array size.
Types of C Arrays:
data_typearray_name[size of array]
Examples:
This statement allocates a contiguous block of memory for four integers and initializes all
the values to 0. This is how it is laid out in memory:
Note:
Array indexes start from zero and end with (array size – 1). So for the above array,
you can use the first element with a[0], second element with a[1], third element with
a[2] and fourth (last) element with a[3].
➢ You can use the indexes to set or get specific values from the array.
a[0] = 10;
a[1] = 20;
a[2] = a[1] / a[0]; // a[2] will be set to 20/10 = 2
a[3] = a[1] - 2; // a[3] will be set to 20-2 = 18
After these changes, here is how the array will look like in memory:
Note:
C does not enforce any array bounds checks, and accessing elements outside the
maximum index will lead to “undefined behaviour”. if you try to access a[5], the
element is not available. This may cause unexpected output (your program to
crash or behave abnormally).
➢ Similarly an array can be of any data type such as double, float, short etc.
Array Initialization:
1. Initialize array at time of declaration – means save all the values in array columns
during declaration like below.
Here, we haven't specified the size. Compiler knows its size is 5 as we are initializing it with 5
[Link], you cannot skip both the size and the initializer list, and writeas
intmark[].If you skip both of them, C cannot create the array, and this will lead to a
compile-time error
intarr[5];
inti;
for(i=0;i<5;i++)
{
printf("Enter a number: ");
scanf("%d", &num);
arr[i] = num;
}
Note:
1. You can also make an array that is bigger than the initializer list, like
int a[6] = {10, 20, 30, 40};
printf("%d %d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4], a[5]);
In this case, the rest of the elements are initialized with zero. In our above example,
elements from a[0] to a[3] will be initialized, whereas a[4] and a[5] will be set to zero.
(ie) a[0]=10, a[1]= 20,a[2]= 30, a[3]= 40, a[4]= 0 and a[5]= 0.
In array we can access any element by specifying their index number. For example if we want to
access the element stored on index 2 in array named arr. Use following
int value;
value = arr[2];
Or we can fetch and print entire array elements using for or while loop
inti;
for(i=0;i<5; i++)
{
printf("%dn", arr[i] );
}
Example:
avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
Output:
Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20
The elements of the 2D array are stored in contiguous memory locations in a row-wise
manner, starting from first row and ending with lastrow.
Declaration:
data_type array_name[row size][column size];
For example,
float x[3][4];
Here, x is a two-dimensional (2D) array with 3 rows and each row has 4 columns. This array
can hold 12 elements (3 * 4).
Initialization of a 2D array
There are Different ways to initialize two-dimensional array
Eg1.:int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
Eg2.:int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
Eg3.:int c[2][3] = {1, 3, 0, -1, 5, 9};
#include <stdio.h>
main()
{
introw,col;
int table[3][2] = { {10, 22}, {33, 44}, {45, 78} };
for (row = 0; row < 3; row++)
{
for (col = 0; col < 2; col++)
{
Declaring a string
Initializing a string
1. scanf(“%s”, string1);
scanf() reads a sequence of characters and terminates when the first white space is
encountered or a new line character (‘\n’) is encountered.
2. gets(string1);
gets() terminates only when new line character (‘\n’) is encountered.
Displaying Strings
Strings can be displayed using printf() or puts().
printf(“%s, string1);
puts(string2);
Example:
printf(%s”,name);
String Operations
To perform string operations many important library functions are defined in "string.h" header file.
3) strcat(first_string, Joins first string with second string. The result of the
second_string) string is stored in first string.
The first index of the array is used for definingtotal numbers of strings and the second index
is used for defining length of the string.
Example:
char name[5][10]
SEARCHING ALGORITHMS
Searching is the process of finding the position of givenvalue in a list or an array. To search an
element in a given array, there are two popular algorithms available:
1. Linear
B.E (II Semester) Programming for Problem Solving 43
2. Binary
1. Linear Search
Linear search is a very basic and simple search algorithm. It is used with unsorted or
unordered lists.
Algorithm
Step 1: Iterate over every element of the array to check if it matches with the number
we’re looking for.
Step 2: when the element is matched , return the index of the element in the array.
Step 3: else return -1.
Program:
#include <stdio.h>
int main() {
// declare an array, a loop variable, and the number to search
int a[5], i, search;
if (pos == -1) {
printf("%d was not found\n", search);
} else {
printf("%d was found at position %d\n", search, pos);
}
2. Binary Search
Binary Search is used with sorted array or list. Binary search follows divide and conquer
approach in which, the list is divided into two halves and the item is compared with the
middle element of the list. If the match is found then, the location of middle element is
returned otherwise, we search into either of the halves depending upon the result produced
through the match.
Algorithm:
Step 1: Compare the element to be searched with the element in the middle of the
sorted list.
Step 2: If matched, return the index of the middle element
Step 3: If not matched, check whether the element to be searched is less or
greater than the middle element.
Step 4 :If the element to be searched is lesser than the middle number, then do
binary search in left half of the array.
Step 5: Else do binary search in right half of the array.
Step 6: If not matched with any elements, return -1.
SORTING ALGORITHMS
Sorting is a process of arranging elements of an array in ascending or descending order.
Consider an array
2 Insertion Sort As the name suggests, insertion sort inserts each element of the
array to its proper place. It is a very simple sort method .
3 Selection Sort It finds the smallest element in the array and place it on the first
place on the list, then it finds the second smallest element in the
array and place it on the second place. This process continues
until all the elements are placedin their correct position.
1. Bubble Sort
In Bubble sort, Each element of the array is compared with its adjacent element. The algorithm
processes the list in passes. A list with n elements requires n-1 passes for sorting.
Algorithm
1. Compare firstelement with the second [Link] the first element is greater than the
second element, swap them.
2. Repeat the above process with the next two elements until the last element. Now the
largest element is placed in the highest index of the array.
3. Do step1 and step 2 to place the next largest element in the next highest index. Repeat
the process until the list is sorted
Example
Take an array of numbers " 5 1 4 2 8", and sort the array from lowest number to greatest
number using bubble sort. In each step, elements written in bold are being compared. Three
passes will be required;
First Pass
( 5 1 4 2 8 ) → ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps
since 5 > 1.
( 1 5 4 2 8 ) → ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) → ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) → ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5),
algorithm does not swap them.
Second Pass
(14258)→(14258)
( 1 4 2 5 8 ) → ( 1 2 4 5 8 ), Swap since 4 > 2
(12458)→(12458)
(12458)→(12458)
Third Pass
(12458)→(12458)
(12458)→(12458)
(12458)→(12458)
(12458)→(12458)
2. Insertion Sort
Insertion sort works similarly as we sort cards in our hand in a card game. This sort inserts each
element of the array to its proper place. It is a very simple sort method .
Algorithm:
1. Assume the first element in the array is sorted. Take the second element and
store it as key
2. Compare key with the first element. If the first element is greater than key,
then key is placed in front of the first element.
3. Take the next element as key and compare it with the elements on the left of
it. Place it just behind the element smaller than it. If there is no element smaller
than it, then place it at the beginning of the array.
4. Repeat step 3 for every unsorted element.
Example1:
Algorithm
1. Set the first element as minimum
2. Compare minimum with the next element. If that element is smaller, then
assign it (ienext )as minimum.
3. Repeat this until the last element.
4. Swap the first element with minimum.
5. Repeat steps 1 to 4 from the first unsorted element until all the elements are
placed at their correct positions
Example1:
Sort the following array
2, 12, 10, 15, 20.
Space Complexity
Space Complexity of an algorithm denotes the total space used or needed by the algorithm for
its working, for various input sizes.
for(i = 0; i< n-1; i++)
scanf(“%d”,&a[i]);
In the above example, we are creating a array of size n. So the space complexity of the above
code is in the order of "n" i.e. if n will increase, the space requirement will also increase
accordingly.
Time Complexity
Time Complexity of algorithm is not equal to the actual time required to execute a particular
code. It is the number of operations an algorithm performs to complete its task with respect to
input size (considering that each operation takes the same amount of time). The algorithm that
performs the task in the smallest number of operations is considered the most efficient one.
Time Complexity of algorithm is not equal to the actual time required to execute a particular code
but the number of times a statement executes. There are three types of time complexities which
can be analyzed for the algorithm:
o Best case time complexity [ Ω Notation ] : It is defined as the minimum number of steps
required for an input of size n.
o Worst case time Complexity [ Big-O Notation ]: : It is defined as the maximum number
of steps required for an input of size n.
o Average Time complexity Algorithm[Θ Notation ]: : It is defined as the average number
of steps required for an input of size n.
We have one array named "arr" and an integer "k". We need to find if that integer "k" is present
in the array "arr" or not? If the integer is there, then return 1 or return 0.
Now, one possible solution for the above problem is traverse each and every element of the
array and compare that element with "k". If it is equal to "k" then return 1, otherwise, keep on
comparing for more elements in the array and if you reach at the end of the array and you did
not find any element, then return 0.
The section of code for the above task is
for (inti = 0; i< n; ++i)
{
if (arr[i] == k)
return1;
}
return0;
Time Complexity Analysis
In the above code
* i = 0 ------------> will be executed once
* i< n ------------> will be executed n+1 times
* i++ --------------> will be executed n times
* if(arr[i] == k) --> will be executed n times
* return 1 ---------> will be executed once(if "k" is there in the array)
* return 0 ---------> will be executed once (if "k" is not there in thearray)
Each statement in code takes constant time, "C". So, if a statement is executed "N" times, then
it will take C*N amount of time. Here we assume that each statement is taking 1sec of time to
execute.
As you can see that for the same input array, we have different time for different values of "k".
So, this can be divided into three cases:
_____________________________________________________________________
Introduction to Functions
A number of statements grouped into a single logical unit are called a function. The use of
function makes programming easier since repeated statements can be grouped into functions.
Splitting the program into separate function make the program more readable and maintainable.
A function definition has two principal components:
(i) the function header
(ii) body of the function.
The function header is the data type of return value followed by function name and a set of
arguments. Associated type to which function accepts precedes each argument. The function
header statement can be written as
return_type function_name (type1 arg1,type2 arg2,..,typen argn)
where return_type represents the data type of the item that is returned by the function,
function_name represents the name of the function, and type1,type2,...,typen represents the data
type of the arguments arg1,arg2,..,argn.
• The number of arguments in the function calls and function declaration must be same.
• The prototype of each of the argument in the function call should be same as the
corresponding parameter in the function declaration statement.
For example the code shown below illustrate how function can be used in programming
//C Program for Addition of Two Number's using User Define Function
#include<stdio.h>
#include<conio.h>
float add(float,float); // function declaration
void main()
{ float a,b,c;
clrscr();
printf("Enter the value for a & b\n\n");
scanf("%f%f",&a,&b);
c=add(a,b);
printf("\nc=%f",c);
getch();
}
Every function in C programming should be declared before they are used. This type of
declaration are also called function prototype. Function prototype gives compiler information
about function name, type of arguments to be passed and return type. Syntax of function
prototype
Pass by value
#include <stdio.h>
void main()
{
int x=3;
printf(“\n x=%d(from main, before calling the function”),x);
change(x);
printf(“\n\nx=%d(from main, after calling the function)”,x);
}
void change(x)
{
int x;
x=x+3;
printf(“\nx=%d(from the function, after being modified)”,x);
return;
}
The original value of x (i.e. x=3) is displayed when main begins execution. This value
is then passed to the function change, where it is sum up by 3 and the new value
displayed. This new value is the altered value of the formal argument that is displayed within
the function. Finally, the value of x within main is again displayed, after control is
transferred back to main from change.
x=3 (from main, before calling the function) x=6
(from the function, after being modified) x=3
(from main, after calling the function)
Passing an argument by value allows a single-valued actual argument to be written as an
expression rather than being restricted to a single variable. But it prevents information from
being transferred back tothe calling portion of the program via arguments. Thus, passing by
value is restricted to a one-way transfer of information.
#include <stdio.h>
#define SIZE 5
void showarray(int array[]);
Recursion
When function calls itself (inside function body) again and again then it is called as recursive
function. In recursion calling function and called function are same. According to recursion
problem is defined in term of itself. Here statement with in body of the function calls the same
function and same times it is called as iterative definition. Recursion is the process of defining
something in form of itself.
int main()
{
rec();
}
void rec()
{
if(base_condition)
{
// terminating condition
B.E (II Semester) Programming for Problem Solving 59
}
statement 1;
...
rec();
}
Example:
/*calculate factorial of a [Link] recursion*/
After this, the list is divided into sub lists, one sub list containing the elements less than the pivot
element and the other containing the elements more than the pivot element. These two lists are
again individually sorted using Quick sort algorithm that is by again finding a split-point and
dividing into two parts. The process is recursively done until all the elements are arranged in
order. So it is called divide and conquer algorithm.
Consider the given list,
Select the first element as pivot element and place it, at its position using an algorithm. Find
the biggest element than the pivot element from first using “i” and smallest element from
the last using “j” and interchange them.
As i<j is false, the current process is stopped and a[start] and a[j] are interchanged.
Now the pivot element is at its position “j”, which is the split position for next sub arrays
because all elements to its left are smaller and to its right are greater.
#include<stdio.h>
int a[50];
void qsort(int,int);
int split(int,int); int
main()
{
int n,i;
printf("How many elements?");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
qsort(0,n-1);
In Merge Sort, take a middle index and break the array into two sub-arrays. These sub-array
will go on breaking till the array have only one element.
2) MERGING
With the single elements left, start merging the elements in the same order in which divided
them. During Merging, sort the sub-arrays, because sorting 10 arrays of 2 elements is cheaper
than sorting an array of 20 elements.
#include<stdio.h>
void merge(arr, low, mid, high )
{
int temp[MAX];
int i = low;
int j = mid +1 ;
int k = low ;
while( (i <= mid) && (j <=high) )
{
if(arr[i] <= arr[j])
temp[k++] = arr[i++] ;
else
temp[k++] = arr[j++] ;
}
void merge_sort( int low, int high )
{
int mid;
if( low != high )
{
mid = (low+high)/2;
merge_sort( low , mid );
merge_sort( mid+1, high );
merge( low, mid, high );
}
}
int main()
{
int i,n;
printf("Enter the number of elements : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter element %d : ",i+1);
scanf("%d",&arr[i]);
Unit V
Structure
Syntax of a structure:
struct [structure_tag]
{
Member definition
Member definition
..
Member definition
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition or any
other valid variable definition. At the end of the structure's definition, before the final semicolon,
one or more structure variables can be specified but it is optional
Examples:
1.
struct Student
{
Each member can have different datatype: name is an array of char type and age is of int type
branch and gender is of character type.
2.
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
A structure named ‘address’ with 5 members is declared. The members namely name, street, city,
and state are of character type of length 50, 100,50 and 20 respectively and pin is of integer type.
3.
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
A structure named ‘Books’ with 4 members is declared. The members title, author and subject are
of character type of length 50, 50 100 respectively. The book_id is of integer type.
4.
struct Person
{
char name[50];
int citNo;
A structure named ‘Person’ with 3 members is declared. The members name is of character type,
citNoof integer type and salary is of float type.
5.
struct
float x, y;
} complex;
An anonymous structure with two members with float type, x and y is declared. The structure type
has no tag and is therefore unnamed or anonymous.
When a struct type is declared, no storage or memory is allocated. To allocate memory of a given
structure type and work with it, we need to create variables.
We can declare a variable for the structure so that we can access the member of the structure easily.
The two ways to declare structure variable are:
struct employee
{ int id;
char name[50];
float salary;
};
int main()
{
struct employee e1;
The variable e1 can be used to access the values stored in the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1;
The following image shows the memory allocation of the structure employee that is defined in the
above example.
Let's see the code to access the id member of p1 variable by. (member) operator.
#include<stdio.h>
employee 1 id : 101
employee 1 name :ABC
Designated Initialization :
Designated Initialization allows structure members to be initialized in any order.
#include<stdio.h>
struct Point
{
int x, y, z;
};
int main()
{
// Examples of initialization using designated initialization
struct Point p1 = {.y = 0, .z = 1, .x = 2};
struct Point p2 = {.x = 20};
Array of structures :
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
Output:
10 20
Structure pointer :
Like primitive types, we can have pointer to a structure. If we have a pointer to structure, members
are accessed using arrow ( -> ) operator.
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
// p2 is a pointer to structure p1
struct Point *p2 = &p1;
Output:
12
Limitations of C Structures :
In C language, Structures provide a method for packing together data of different types. However,
C structures have some limitations.
1. The C structure does not allow the struct data type to be treated like built-in data types:
2. We cannot use operators like +,- etc. on Structure variables.
struct number
{
float x;
};
int main()
{
struct number n1,n2,n3;
n1.x=4;
n2.x=3;
n3=n1+n2;
return 0;
}
/*Output:
3. No Data Hiding: C Structures do not permit data hiding. Structure members can be
accessed by any function, anywhere in the scope of the Structure.
4. Functions inside Structure: C structures do not permit functions inside Structure
5. Static Members: C Structures cannot have static members inside their body.
___________________________________________________________________
Pointers
A pointer is a variable that stores the address of another variable. Unlike other variables that
hold values of a certain type, pointer holds the address of a variable. For example, an integer
variable holds (or you can say stores) an integer value, however an integer pointer holds the
address of a integer variable.
A simple example to understand how to access the address of a variable without pointers?
In this program, we have a variable num of int type. The value of num is 10 and this value must
be stored somewhere in the memory, right? A memory space is allocated for each variable that
holds the value of that variable, this memory space has an address. The value of the variable is
stored in a memory address, which helps the C program to find that value when it is needed.
So let’s say the address assigned to variable num is 0x7fff5694dc58, which means whatever
value we would be assigning to num should be stored at the location: 0x7fff5694dc58.
#include <stdio.h>
int main()
*/
return 0;
Output:
This program shows how a pointer is declared and used. There are several other things that we
can do with pointers, we just need to know how to link a pointer to the address of a variable.
Important point to note is: The data type of pointer and the variable must match, an int pointer
can hold the address of int variable, similarly a pointer declared with float data type can hold the
address of a float variable. In the example below, the pointer and the variable both are of int
type.
#include <stdio.h>
int main()
//Variable declaration
//Pointer declaration
int *p;
p=#
return 0;
Output:
Lets discuss the operators & and * that are used with Pointers in C.
We have already seen in the first example that we can display the address of a variable using
ampersand sign. I have used &num to access the address of variable num. The & operator is
also known as “Address of” Operator.
Point to note: %p is a format specifier which is used for displaying the address in hex format.
The above are the few examples of pointer declarations. If you need a pointer to store the
address of integer variable then the data type of the pointer should be int. Same case is with
the other data types.
double a = 10;
double *p;
printf("%d", *p);
*p = 200;
It would change the value of variable a. The statement above will change the value of a from 10
to 200.
#include <stdio.h>
int main()
*/
int *p;
*/
p= &var;
return 0;
Output:
Self Referential structures are those structures that have one or more pointers which point to the
same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-referential in nature.
Example:
structnode {
intdata1;
chardata2;
structnode* link;
};
Example:
#include <stdio.h>
structnode {
intdata1;
chardata2;
structnode* link;
};
intmain()
{
structnode ob1; // Node1
// Initialization
[Link] = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
40
Self Referential Structure with Multiple Links: Self referential structures with multiple links
can have more than one self-pointers. Many complicated data structures can be easily
constructed using these structures. Such structures can easily connect to more than one nodes at a
time. The following example shows one such structure with more than one links.
The connections made in the above example can be understood using the following figure.
Example:
#include <stdio.h>
structnode {
intdata;
structnode* prev_link;
structnode* next_link;
};
intmain()
{
structnode ob1; // Node1
// Initialization
ob1.prev_link = NULL;
// Initialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
[Link] = 20;
// Initialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
[Link] = 30;
// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;
// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;
10 20 30
10 20 30
For a real-world analogy of linked list, you can think of conga line, a special kind of dance in
which people line up behind each other with hands on shoulders of the person in front. Each
dancer represents a data element while their hands serve as the pointers or links to the next
element.
• In contrast to arrays, which have pre-defined or fixed length, linked lists have a dynamic
length which can be increased or decreased at runtime.
• Insertion and deletion operations in the linked list are much faster in comparison to other
data structure such as the queue, stack, and arrays.
Consequently, it often better to consider using a list when the exact volume and quantity is not
known ahead of time and cannot be made fixed. For instance, a programmer designing a school
management system cannot determine how many students will enroll in the school. Therefore, it
is most efficient to choose an ordered list data structure over arrays.
In the above code, the structure node contains data element data as well as pointer next which
points to the structure of the same type. The (*) indicates a pointer definition and it points to the
address of the next node of the linked list. As the linked list is traversed using the next pointer,
the value of the pointer in the last node will be NULL. The self-referential structure is the reason
why a linked list is called a dynamic data structure and can be expanded and pruned at runtime.
arr[]=[50,100,120,150,200];
If we have to insert a new value 70 into the array, then we have to move all elements after 50 to
maintain the ordered array. Similarly, if we have to delete a value 100 from the array, we have to
move all the values after 100. So, insert and delete operations are expensive in ordered arrays. If
we maintain an ordered list, the insert and delete operations are faster and more efficient due to
the use of pointers.
Following are the basic operations supported by a list.
• Insertion − Adds an element at the beginning of the list.
• Deletion − Deletes an element at the beginning of the list.
• Display − Displays the complete list.
• Search − Searches an element using the given key.
• Delete − Deletes an element using the given key.
Basic Operations
Following are the basic operations supported by a list.
• Insertion − Adds an element at the beginning of the list.
• Deletion − Deletes an element at the beginning of the list.
• Display − Displays the complete list.
• Search − Searches an element using the given key.
• Delete − Deletes an element using the given key.
Insertion Operation
Adding a new node in linked list is a more than one step activity. We shall learn this with diagrams
here. First, create a node using the same structure and find the location where it has to be inserted.
Imagine that we are inserting a node B (NewNode), between A (LeftNode) and C (RightNode).
Then point [Link] to C −
[Link] −>RightNode;
It should look like this −
This will put the new node in the middle of the two. The new list should look like this −
Similar steps should be taken if the node is being inserted at the beginning of the list. While
inserting it at the end, the second last node of the list should point to the new node and the new
node will point to NULL.
Deletion Operation
Deletion is also a more than one step process. We shall learn with pictorial representation. First,
locate the target node to be removed, by using searching algorithms.
This will remove the link that was pointing to the target node. Now, using the following code, we
will remove what the target node is pointing at.
[Link] −> NULL;
We need to use the deleted node. We can keep that in memory otherwise we can simply deallocate
memory and wipe off the target node completely.
______________________________________________________________________________
File Handling
A file represents a sequence of bytes on the disk where a group of related data is stored. File is
created for permanent storage of data.A file is a container in computer storage devices used for
storing data. The uses of files are:
• When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of
the file using a few commands in C.
• You can easily move your data from one computer to another without any changes.
Types of Files:
Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and
takes bigger storage space.
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides better security than
text files.
File Operations :
In C, you can perform four major operations on files, either text or binary:
C provides a number of functions that helps to perform basic file operations. Following are the
functions:
When working with files, you need to declare a pointer of type file. This declaration is needed
for communication between the file and the program.
FILE *filepointer;
FILE *filePointer;
So, the file can be opened as
filePointer = fopen(“[Link]”, “w”)
The second parameter can be changed to contain all the attributes listed in the above table.
Reading from a file :–
The file read operations can be performed using functions fscanf or fgets. Both the
functions performed the same operations as that of scanf and gets but with an additional
parameter, the file pointer. So, it depends on you if you want to read the file line by line or
character by character.
And the code snippet for reading a file is as:
FILE * filePointer;
Writing a file :-
The file write operations can be perfomed by the functions fprintf and fputs with
similarities to read operations. The snippet for writing to a file is as :
FILE *filePointer ;
FilePointer = fopen(“[Link]”, “w”);
fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);
Closing a file :-
After every successful fie operations, you must always close a file. For closing a file, you
have to use fclose function. The snippet for closing a file is given as :
FILE *filePointer ;
filePointer= fopen(“[Link]”, “w”);
---------- Some file Operations -------
fclose(filePointer)
Example 1: Program to Open a File, Write in it, And Close the File
# include <stdio.h>
# include <string.h>
intmain( )
{
This program takes a character which is stored in the variable “dataToBeWritten” and stores in the
file [Link].
After you compile and run this program, you can see a text file [Link] in C drive of your
computer. When you open the file, you can see the integer you entered.
Example 2: Program to Open a File, Read from it, And Close the File
# include <stdio.h>
# include <string.h>
intmain( )
{
If you successfully created the file from Example 1, running this program will get you the string
you entered.