PSTC
PSTC
PART- A
[ 2m x 4q = (8 marks) ]
ANSWER ANY 4 QUESTIONS
Each question carries 2 marks (concept based)
PART-B
[5m x 4q = (20 marks)]
Each question carries 5 marks (numerical problems /algorithm/
tracing/flowcharts/programs based)**
Note :
• In each part of the question paper first three questions should be set from
the first TWO units of the syllabus and next three questions should be set
from second half (last TWO units) of the syllabus.
It is independent of language of compiler and types of It is dependent on language of compiler and type of
2
hardware. hardware.
The time complexity of an algorithm using a priori The time complexity of an algorithm using a posteriori
5
analysis is same for every system. analysis differ from system to system.
If the algorithm running faster, credit goes to the If the time taken by the program is less, then the credit will go
6
programmer. to compiler and hardware.
Maintenance Phase is not required to tune the Maintenance Phase is required to tune the algorithm.
9
algorithm
Complexty of an Algorithms
The complexity of an algorithm computes the amount of time and spaces required by an algorithm
for an input of size (n).
The complexity of an algorithm can be divided into two types.
➢ Time complexity
➢ Space complexity.
Time Complexity of an Algorithm
The time complexity is defined as the process of determining a formula for total time required
towards the execution of that algorithm. This calculation is totally independent of implementation
and programming language.
Space Complexity of an Algorithm
Space complexity is defining as the process of defining a formula for prediction of how much
memory space is required for the successful execution of the algorithm. The memory space is
generally considered as the primary memory.
Space Complexity of an Algorithm
Space complexity is defining as the process of defining a formula for prediction of how much memory
space is required for the successful execution of the algorithm. The memory space is generally
considered as the primary memory.
For any algorithm Memory required for the following things:
➢ Instruction space: Amount of memory used to store instruction
➢ Data Space: Amount of memory used to store variables and constants
➢ Environment Stack: Amount of memory used to store function call info
Formula to calculate Space complexity:
S(P)=Cp + Sp
Where
➢ Cp is the space required for code segment(Cp)
➢ Sp is the space required to Dynamic part(Sp)
Time Complexity of an Algorithm
The time complexity is defined as the process of determining a formula for total time required towards the
execution of that algorithm. This calculation is totally independent of implementation and programming
language. Time complexity=compiletime + runtime
Time complexity of an algorithm will be denoted by notations called “Big O Notation”.ie O(n).
Order notation based on the relation between run time against the number of input data sizes and the
number of operations performed on them.
There are different types of time complexities used:
1. Constant time – O (1)
2. Linear time – O (n)
3. Logarithmic time – O (log n)
4. Quadratic time – O (n^2)
5. Cubic time – O (n^3)
Continued …..
Design techniques algorithm :
Algorithms are categorized according to the ideas used to do a job. Although there are
numerous sorts of algorithms, the key categories /designing Techniques of IT algorithms
includes:
•Divide and conquer algorithms :- Divide the issue into smaller sub-issues of the same type; solve
smaller issues and integrate the original problem solving answers.
•Brute force algorithms :- Try every potential solution until the solution is found satisfactory.
•Randomized algorithms :- To find a solution to the problem, employ a random integer for at least
once throughout a calculation.
•Greedy algorithms :- Finish at local level an ideal solution to discover the ideal answer to the
complete issue.
•Recursive algorithms :- Address the lowest and easiest form of an issue and solve it in a wider
and broader way until the original problem has been resolved.
•Backtracking algorithms :- Divide the issue into sub-problems that can be resolved, but if the
requested answer is not attained, reverse the problem until a route pushes it forward is
established.
•Dynamic programming algorithms :- Pause a difficult problem and solve them once only, instead
of re-calculating their answers, by collecting smaller subproblems and saving their solutions for
future use.
Problem Solving Techniques
Unite-2
Chapter1: Introduction to C Language
Program and Programming Language
|Not Portable
- Not Portable
STRUCTURE OF YOUR C PROGRAM
STRUCTURE OF YOUR C PROGRAM
Different Sections of C Program
1.Documentation Section
2.Linked Section
3.Definition Section
5. main( ) function: The main function is the section from where the actual program begins. The main function begins with
opening curly braces and ends with closing curly braces. The program should have one main function.
This section contains two parts:
int main(void)
1 Declaration Part {
2 Executable Part int x=2;
printf(" %d", x);
➢ Declaration Part :Declares all the variables used in the executable part. return 0;
➢ Executable part: which contains instructions } should be at least one statement in the
to perform certain task. There
executable part
The declaration and executable part must appear between the opening and closing braces. All statements in the
declaration part should end with the semicolon.
6.The Subprogram Section contains all the user defined functions that are called in the main function.
sub(int a, int b)
{
return a-b;
}
Example Program to represent the Structure of C Program
1.Define a program?
2.Define a programming Language?
3.Types of Programming Languages?
4.Define a compilers?
5.Define an Interpreter?
6.Define an Assembler?
7.What are translators? Give example.
8.Wrtie the structure of C Program? Explain with Example.
9.Types of Comments in C Language?
Operators in C
There are 8 types of Operators in C-language:
1) Arithmetic Operators
2) Relational Operators
3) Logical Operators
4) Bitwise Operators
5) Assignment Operators
6) Increment and Decrement Operators
7) Conditional Operators
8) Special Operators(comma,&,*,size of()
Basic Classification of operators:
Unary operators :Only one operand is required to perform calculation.
Binary Operators : Two operands are required to perform calculation.
Ternary Operators : Three operands are required to perform calculation.
Binary operators
Binary Operators in C Language:
Binary operators are those operators that work with two operands. A Binary
Operator in C is an operator that takes two operands in an expression or a
statement. These are binary operators like
3+5 , 3–5.
General Syntax
#include<stdio.h>
int main()
{
int x = 12, y = 13;
printf("x = %d\n", x);
printf("y = %d\n\n", y);
printf("x > y : %d\n", x > y); // Is x is greater than y?
printf("x >= y : %d\n", x >= y); // Is x is greater than or equal to y?
printf("x < y : %d\n", x < y); // Is x is smaller than y?
printf("x <= y : %d\n", x <= y); // Is x is smaller than or equal to y?
printf("x == y : %d\n", x == y); // Is x is equal to y?
printf("x != y : %d\n", x != y); // Is x is not equal to y?
}
Logical Operators
Logical operators are used to combine two or more relational expressions. This
operator is used to test more than one condition at a time.
(expr1 && expr2) True(1) only if expr1 and expr2 are true
False(0) if any one expression false
(expr1 || expr2) True(1) if either exp1 or expr2 is true
False(0) if both are false
! (expr1) True(1) of expr1 is False
False(0) if exp1 is True.
ret = ( (a <= b) || (a != b) );
// 5 <= 10 ==> true. 5 != 10 ==> true. So, 1 || 1 will return 1.
printf("Return value of above expression is %d \n",ret);
General Syntax
Example1 Example2
A=20; b=20+15;
Here 20 will be assigned to a Here the value 35(20+15) will be
variable A assigned to a variable b
The Assignment Operator
In C, the assignment operator(=) can be used for assigning a
value to a variable
Assignment operators are use to combine the operator = with any one of the
arithmetic operator (+,-,*,/).
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
List of Bitwise Operators
Operator Description Example
& Binary AND compares two bits generate result (A & B) = 12, i.e., 0000 1100
1 if both bits are one otherwise it returns 0.
| Binary OR compares two bits generate result 1 (A | B) = 61, i.e., 0011 1101
if either or both bits are one otherwise it
returns 0.
^ Binary XOR Operator copies the bit if it is set in (A ^ B) = 49, i.e., 0011 0001
one operand but not both.
~ Binary One's Complement Operator is unary (~A ) = ~(60), i.e,. -0111101
and has the effect of 'flipping' bits.
<< Binary Left Shift Operator. The left operands
value is moved left by the number of bits A << 2 = 240 i.e., 1111 0000
specified by the right operand.
The operators required only one operand are knows as Unary Operators.
There are three unary operators in c
Sl.no Unary Operator Operator Exampl
Description e
1 - Unary Minus -10; -b;
2 ++ Increment Operator ++a ,
a++
3 -- Decrement Operator --a ,
a--
if a=5
a++; //now a becomes 6
++a; //now a becomes 7
--a; //Now a is 6
a --; // now a is 5
Increment and Decrement Operators types:
Increment Operators
Decrement Operators
int a=5,b;
b=++a;
Oepreation1: First increment the value of a by 1(a becomes 6)
Operation 2: After which the updated value of a is assigned to b
Finally the value of a=6 and b = 6
The postfix increment operator the value of a variable is first used inside
the provided expression, and then its value gets incremented by 1.
int a=5,b;
b=a++;
Oepreation1: First the value of a is Assigned to b
Operation 2: After which the value of a is incremented by 1
Finally the value of a = 6 and b = 5
The prefix decrement operator first increments the value of a variable and
then used inside any expression.
int a=5,b;
b=--a;
Oepreation1: First decrement the value of a by 1(a becomes 4)
Operation 2: After which the updated value of a is assigned to b
Finally the value of a=4 and b=4
The postfix decrement operator the value of a variable is first used inside
the provided expression, and then its value gets decrement by 1.
int a=5,b;
b=a--;
Oepreation1: First the value of a is Assigned to b
Operation 2: After which the value of a is decrement by 1
Finally the value of a= 4 and the of b = 5
Ternary operators
Conditional Operator or Ternary Operator( ? : )
Example2
#include <stdio.h>
void main() Output
{ Output:
int a=5,b=10,c=7,big; big=10 is greatest
big=(a>b && a>c) ? a : (b>c? b : c);
printf(“big =%d is greatest”);
getch();
}
Operators Meaning Example
, Comma Operator Z=(x=5,y=6,x+y)
General Syntax
sizeof(operand)
❖ Where operand can be any data type or variable or constant
❖ sizeof(int), sizeof(char), sizeof(float) etc
Problem: To print the size of all primitive data types in C using sizeof( ) function
#include <stdio.h>
void main()
{
printf("int is %2d bytes \n", sizeof(short int));
printf("long int is %2d bytes \n", sizeof(long int));
printf("float is %2d bytes \n", sizeof(float));
printf("double is %2d bytes \n", sizeof(double));
printf("long double is %2d bytes \n", sizeof(long double));
printf("char is %2d bytes \n", sizeof(char));
}
10 + 20 * 30
Operator precedence determines which operator is performed first in an expression with
more than one operators with different precedence.
For example: Solve 10 + 20 * 30
1.Parentheses have the highest precedence. So, the expressions inside the
parentheses will be evaluated first. After solving, the whole expression simplifies
to: 7 * 20 / 10 – 3= 7∗2−3.
2.Now, multiplication and division have the same precedence. Since multiplication
and division have associativity from left to right, multiplication will be performed
first. The expression now becomes: 140 / 10 – 31=40/10−3.
3.Next, the division has higher precedence. So, the expression will become 14 –
3=14−3.
4.Finally, we will subtract 3 from 14 to get 11 as the output.
(10 - 4) + (20 / (2 * 5)) * 3; 0/p: 12
#include <stdio.h>
void main()
{
int a = 5;
printf("%d", ans);
}
Output : 27
Assignment -2 Submission Date 11-10-2022
Questions to write and revise:
1.What is an operand?
2.What is an operator?
3.What do you mean by unary operator? Mention unary operator.
4.What are logical Operators? Explain
5.What are Bitwise Operators? Explain.
6.Write the difference between post fix and prefix increment operator?
7.Write the about conditional operator in detail?(General syntax, Explanation and
Example)
8.a)What is the value of 2*4/2
b)Evaluate the following expression(2+((3*6)+8)*4)
c)3*4+12/2
d)8-24/(3+3)*(3-1)
9.Give the precedence of Arithmetic operators
10.Give the precedence of Relational and Logical operator
11.What are the different types of increment and decrement operators in C? Explain with
example
Control Structures or Statement in C
Control Structures / Statements In C Language
A program is nothing but the execution of sequence of one or more instructions.
Control Structure are used:
(i) To alter the flow of a program
(ii) Test the logical conditions
(iii) Control the flow of execution as per the selection these conditions can be placed in the program using decision-making statements.
Syntax :
if ( Test Expression or Condition )
{
True- Block Statements; /*true block (or) if block */
}
else
{
False-block Statements; /* false block (or) else block */
}
When a series of decisions are involved, we may have to use more than one if-else statement in nested form.
Syntax :
if ( Test Condition1)
{
if ( Test Condition2)
{
Statement -1;
}
else
{
Statement -2;
}
}
else
{
if ( Test Condition3)
{
Statement -3;
}
else
{
Statement-4;
}
} /* end of outer if-else *
# include<stdio.h>
# include<conio.h>
main( ) {
float a,b,c;
printf(“Enter Three Values:”);
scanf(“%f%f%f”, &a, &b, &c);
Output:
printf(“\n Largest Value is:”) ;
Run 1: Enter three values: 24 78 12
if(a>b) Largest Value is: 78
{
if(a>c) Run 2: Enter three values: 45 16 23
printf(“ %f ”, a); Largest Value is: 45
else
printf(“ %f ”, c);
}
else
{
if (b>c)
printf(“ %f ”, b);
else
printf(“ %f ”, c);
}
getch();
}
Else If Ladder: The syntax of else if ladder can be
Else- if ladder is Multi-way maker which contains two or more represented as:
else-if statements, form which one block will be executed.
if( condition-1)
➢ If the first condition is true ,then Statment1 will be statement-1;
executed and control will be sent out of the structure.
else if (condition-2)
➢ If the first condition is not true then the second statement-2;
condition is tested. if the second condition is true , then
Statment2 will be executed and control will be sent out of else if (condition-3)
the structure. statement-3;
➢ If the Second condition is not true then the Third else if (condition-4)
condition is tested. statement-4;
➢ If the condition is found to be false, it continues checking
the next else if statement until the condition comes to be else if (condition-n)
true or the control comes to the end of the else if ladder. statement-n;
else
default statement;
Working of Else If Ladder:
Example Program for else –if ladder
#include<stdio.h>
void main()
{
int a,b,c;
printf("Enter three numbers: \n");
scanf("%d%d%d", &a, &b, &c);
if(a>b && a>c)
{
printf("Largest = %d", a);
}
else if(b>a && b>c)
{
printf("Largest = %d", b);
}
else
{
printf("Largest = %d", c);
}
}
Switch_case statement :
➢ Switch statement in C tests the value of a variable and compares it with multiple cases.
➢ Once the case match is found, a block of statements associated with that particular case is executed.
➢ Each case in a block of a switch has a different name/number which is referred to as an identifier.
➢ The value provided by the user is compared with all the cases inside the switch block until the match is found.
Initialization statement;
while (condition)
{
statements;
Increment or decrement statement;
}
Note: In the while loop, we have to write a condition that needs to be evaluated. The statement inside curly
braces indicates the code to be executed.
Flow Chart Explanation for while loop:
Initialization statement;
do
{
Statements
Increment or decrement statement;
}while (expression);
Note:In the do-while loop, we need to first write the statement inside curly braces, which
indicates the code to be executed.
Flow Chart Explanation of do-while loop statement:
#include<stdio.h>
#include<conio.h>
Output:
void main()
Even Number Series till 20:
{
2 4 6 8 10 12 14 16 18 20
int i,n,sum=0;
for(i=2;i<=20;i=i+2)
printf(“%d \t ”,i);
getch();
}
3. Unconditional control statements Or Jumping statement
➢ Jumping statements are used to transfer the control to one location to other location with out testing nay condition.
➢ Example: break, continue ,goto statements
1.break statement
2.continue statement
3.Goto statement
1.break Statement:
➢ The break statement is used to terminate any of the looping statement.
➢ break key word is always used in connection with if with in a loop.
➢ break keywork is also used to terminates the switch-case
while(condition) do for (expr1;expr2;expr3)
{ { {
------------------ ------------------ ------------------
if(condition) if(condition) if(condition)
break; break; break;
----------------- ----------------- -----------------
----------------- ----------------- -----------------
} } while(condition) }
Statements outside the loop statements outside the loop; statements outside the loop;
i=1; Output:
while(I <= 5) for(i=1;i<=10;i++)
Output: 1
{ {
1 2
if(i==3) if(i==6)
2 3
// break; break;
4
printf(“%d”,i); printf(“%d”,i);
5
i++;
} }
printf(“break terminates the loop if i=3 ”); printf(“break terminates the loop if i=6”);
2.Continue statement:
➢ Continue statement transfer the control back to the loop condition by skipping the rest of the statements of the
body of the loop.
➢ Continue works only with loops.
➢ The key word continue canto be used in switch-case.
while(condition) do for (expr1;expr2;expr3)
{ { {
------------------ ------------------ ------------------
if(condition) if(condition) if(condition)
continue; continue; continue;
----------------- ----------------- -----------------
----------------- ----------------- -----------------
} } while(condition) }
Statements outside the loop statements outside the loop; statements outside the loop;
}
printf(“sum of numbers upto 100 ,skipping all numbers divisible by 2= %d”, sum);
3.Goto statement:
➢ The goto statement is a jump statement which is sometimes also referred to as unconditional jump
statement.
➢ the goto statement is used for altering the normal sequence of program execution by transferring
control to some other part of the program to the specified Label.(any part of the program)
Flowchart for goto statement
#include<stdio.h>
void main()
{
Output:
int x;
Enter a number : 5
printf(“Enter a number : ”);
5 is a odd number
scanf(“%d”,&x);
if(x % 2 == 0)
Output: 2nd run
goto even;
Enter a number : 6
else
6 is a even number
goto odd;
printf(“Given number:%d”,x);
even:
printf(“\n %d is a even number”);
return;
odd:
printf(“\n %d is a odd number”);
getch();
}
Problem: program to print multiplication table using got statement
#include<stdio.h>
void main()
Output:
{
Enter a number: 5
int count,n,product;
5*1=5
printf(“Enter a number”);
5 * 2 = 10
scanf(“%d”,&n);
5 * 3 = 15
count=1;
5 * 4 = 20
start:
5 * 5 = 25
if(count<=10)
5 * 6 = 30
{
5 * 7 = 35
product=n*count;
5 * 8 = 40
printf(“%d * %d= %d”,n,count, product;
5 * 9 = 45
count++;
5 * 10 = 50
goto start;
}
getch();
}
//nested while loop
while(condition)
Nested loop: {
What are nested loops: while(condition)
➢ When one loop inside the body of the another loop,it is called { //statements
a nested loop.This process allow us to create a loop within a
loop. }
➢ The contained loop is referred to as inner loop. The container }
loop is referred to as the outer loop
//nested do..while
do {
do {
Suppose to printf 5 stars continuously the code will be //statements
for(j=1;j<=5;j++) //it will print 5 stars continiously }while(condition);
{
printf("*"); }while(condition);
}
//nested for loop
Output: for(init; condition; inc or dec)
{
for(init; condition; inc or dec)
**** {
//statements
}
}
for(j=1;j<=5;j++) //it will print 5 stars continiously Program to print stars of 5 * 5 star BOX
{ #include<stdio.h>
printf("*"); #include<conio.h>
} Void main()
{
for(j=1;j<=5;j++) //it will print 5 stars continiously Int I,j;
{ for(i=1;i<=5;i++) //it will execute inner loop 5 times
printf("* "); {
} for(j=1;j<=5;j++) //it will print 5 stars continuously
for(j=1;j<=5;j++) //it will print 5 stars continiously {
{ printf("*");
printf("* "); }
} printf(“\n”); //It will give a newline, once 5 stars are printed.
}
for(j=1;j<=5;j++) //it will print 5 stars continiously
getch();
{
}
printf("* ");
}
for(j=1;j<=5;j++) //it will print 5 stars continiously Output:
{ *****
printf("* "); *****
} *****
*****
Above code will be replaces with single nested loops *****
Program to print stars of 5 * 5 star BOX
#include<stdio.h>
#include<conio.h>
Void main()
{
int I,j; Outer Loop
Output:
getch(); *****
} *****
*****
*****
*****
Program to display the following output: Program to display the following output:
11111 1
22222 22
33333 333
44444 4444
55555 55555
Program to display the following output: Program to display the following output:
* 55555
** 4444
*** 333
**** 22
***** 1
Program to display the following output:
*****
****
***
**
*
Sample programs in C-programming using formulas
Problem :- Write A Program For Calculate A Simple Interest .Given Formula Show that to Calculate a Simple
Interest .With the following formula you can calculate a Simple Interest Of Amount Given By User Input
Formula :-
Simple Interest = ( Amount * Rate * Time ) / 100;
SI=(P*T*R)/100;
Solution :- Output:
#include<stdio.h>
void main() Enter Principal Amount: 5669.56
{ Enter Rate of Interest: 5.6
float amount, rate, time, si; Enter the Period of Time: 3.0
printf("\nEnter Principal Amount : "); Simple Interest: 952.486084
scanf("%f", &amount);
printf("\nEnter Rate of Interest : ");
scanf("%f", &rate);
printf("\nEnter Period of Time : ");
scanf("%f", &time);
si = (amount * rate * time) / 100;
printf("\nSimple Interest : %f", si);
}
Problem: Convert Celsius to Fahrenheit
Formula :- Fahrenheit = ((9/5) * Celsius) + 32; //or you can use 1.8 in place of 9/5
Solution :-
#include<stdio.h>
void main()
{ Output:
float cel, fah;
printf("\n Enter Temperature in Celsius : "); Enter Temperature in Celsius : 37
scanf(“ %f ", &cel); Temperature in Fahrenheit: 58.599998
fah = (1.8 * cel) + 32;
printf("\n Temperature in Fahrenheit : %f ", fah);
}
Problem :- Write a program to check given number is greater than 30
Solution :-
#include<stdio.h>
#include<conio.h>
void main()
{ Output:
int num;
clrscr() Enter a number: 40
printf(“Enter a number: "); Given number 40 is greater than 30
scanf("%d", &num);
if(num >30) Output:
printf(“\n Given number %d is greater than 30”,num); Enter a number: 23
getch();
}
Problem :- Write a program to check given number is greater than 30 or not
Solution :-
#include<stdio.h>
#include<conio.h>
void main()
{ Output:
int num;
clrscr() Enter a number: 40
printf(“Enter a number: "); Given number 40 is greater than 30
scanf("%d", &num);
if(num >30) Output:
printf(“\n Given number %d is greater than 30”,num); Enter a number: 23
else Given number 23 is not greater than 30
printf(“\n Given number %d is not greater then 30”,num)
getch();
}
Problem :- Write a program to find the Greatest of given Two numbers using if-else statements
Solution :-
#include<stdio.h>
#include<conio.h>
void main()
{
int a , b ;
clrscr() Output:
printf(“Enter Two numbers: ");
scanf("%d %d", &a,&b); Enter Two numbers : 40 30
if(a >b) a=40 is greater than b=30
printf(“\n a= %d is greater than b= %d”, a, b);
else Output:
printf(“\n b= %d is greater than a= %d”, b, a); Enter a number: 23 35
getch(); b=35 is greater than a=23
Exercise to students:- Write a program to find given Two numbers are equal or not using if-else statement
Problem :- Write a program to check whether a number is even or odd
Solution :-
#include<stdio.h>
#include<conio.h>
void main()
{
int num ;
clrscr() Output:
printf(“Enter a number: ");
scanf("%d ", &num); Enter a number : 44
if(a %2 == 0) Given number 44 is Even Number
printf(“\n Given number %d is Even Number “,num); Output:
else Enter a number : 13
printf(“\n Given number %d is Odd Number”,num); Given number 13 is Odd Number
getch();
}
Problem :- Write a program to find the Greatest of Three numbers using Nested if-else statements
Solution :-
#include<stdio.h>
#include<conio.h>
void main()
{
int a , b ,c;
clrscr() Output:
printf(“Enter Three numbers: ");
scanf("%d %d %d", &a,&b,&c); Enter Three numbers : 40 30 26
if(a >b) a 40 is Greatest among three numbers
{
if ( a > c ) Output:
printf(“\n a %d is Greatest among three numbers ”,a); Enter Three numbers : 45 60 31
else
b 60 is Greatest among three numbers
printf(“\n c %d is Greatest among three numbers ”,c);
}
else Output:
{ Enter Three numbers : 32 45 67
If( b > c ) c 67 is Greatest among three numbers
printf(“\n b %d is Greatest among three numbers ”,b);
else
printf(“\n c %d is Greatest among three numbers ”,c);
}
getch(); }
Exercise to students: Write a program to find the smallest of Three numbers using Nested if-else statements
Problem :- Write a program to accepts a percentage of a students marks.
Depending on the following condition print the category of class achieved Condition Category
}
Problem :- Write a program to find whether a character accepted is a number ,lowercase letter,upper case letter or a
special character.Print the ASCII value of accepted character Using else-if ladder statements.
Solution :-
#include<stdio.h>
#include<conio.h>
void main() Output:
{
char ch;
Enter a character: 4
clrscr()
printf(“Enter a character: "); Entered Character is Numeric character
scanf("%c", &ch); ASCII value of 4 is 52
if(ch >=‘0’ && ch<=‘9’)
printf(“\n Entered Character is Numeric character”); Output:
else if (ch >=‘a’ && ch <=‘z’) Enter a character: A
printf(“\n Entered Character is Lower case character”) Entered Character is Upper case character
else if (ch>=‘A’ && ch<=‘Z’) ASCII value of A is 65
printf(“\n Entered Character is Upper case character”);
else
printf(“\n Entered Character is special character”);
Solution :-
#include<stdio.h>
#include<conio.h>
void main()
{ Output:
int num;
clrscr() Enter a number: 40
printf(“Enter a number: "); Given number 40 is greater than 30
scanf("%d", &num);
if(num >30) Output:
printf(“\n Given number %d is greater than 30”,num); Enter a number: 23
getch();
}
Problem :- Write a program to check given number is greater than 30 or not
Solution :-
#include<stdio.h>
#include<conio.h>
void main()
{ Output:
int num;
clrscr() Enter a number: 40
printf(“Enter a number: "); Given number 40 is greater than 30
scanf("%d", &num);
if(num >30) Output:
printf(“\n Given number %d is greater than 30”,num); Enter a number: 23
else Given number 23 is not greater than 30
printf(“\n Given number %d is not greater then 30”,num)
getch();
}
Problem :- Write a program to find the Greatest of given Two numbers using if-else statements
Solution :-
#include<stdio.h>
#include<conio.h>
void main()
{
int a , b ;
clrscr() Output:
printf(“Enter Two numbers: ");
scanf("%d %d", &a,&b); Enter Two numbers : 40 30
if(a >b) a=40 is greater than b=30
printf(“\n a= %d is greater than b= %d”, a, b);
else Output:
printf(“\n b= %d is greater than a= %d”, b, a); Enter a number: 23 35
getch(); b=35 is greater than a=23
Exercise to students:- Write a program to find given Two numbers are equal or not using if-else statement
Problem :- Write a program to check whether a number is even or odd
Solution :-
#include<stdio.h>
#include<conio.h>
void main()
{
int num ;
clrscr() Output:
printf(“Enter a number: ");
scanf("%d ", &num); Enter a number : 44
if(num %2 == 0) Given number 44 is Even Number
printf(“\n Given number %d is Even Number “,num); Output:
else Enter a number : 13
printf(“\n Given number %d is Odd Number”,num); Given number 13 is Odd Number
getch();
}
Problem :- Write a program to find the Greatest of Three numbers using Nested if-else statements
Solution :-
#include<stdio.h>
#include<conio.h>
void main()
{
int a , b ,c;
clrscr() Output:
printf(“Enter Three numbers: ");
scanf("%d %d %d", &a,&b,&c); Enter Three numbers : 40 30 26
if(a >b) a 40 is Greatest among three numbers
{
if ( a > c ) Output:
printf(“\n a %d is Greatest among three numbers ”,a); Enter Three numbers : 45 60 31
else
b 60 is Greatest among three numbers
printf(“\n c %d is Greatest among three numbers ”,c);
}
else Output:
{ Enter Three numbers : 32 45 67
If( b > c ) c 67 is Greatest among three numbers
printf(“\n b %d is Greatest among three numbers ”,b);
else
printf(“\n c %d is Greatest among three numbers ”,c);
}
getch(); }
Exercise to students: Write a program to find the smallest of Three numbers using Nested if-else statements
Problem :- Write a program to accepts a percentage of a students marks.
Depending on the following condition print the category of class achieved Condition Category
}
Problem :- Write a program to find whether a character accepted is a number ,lowercase letter,upper case letter or a
special character.Print the ASCII value of accepted character Using else-if ladder statements.
Solution :-
#include<stdio.h>
#include<conio.h>
void main() Output:
{
char ch;
Enter a character: 4
clrscr()
printf(“Enter a character: "); Entered Character is Numeric character
scanf("%c", &ch); ASCII value of 4 is 52
if(ch >=‘0’ && ch<=‘9’)
printf(“\n Entered Character is Numeric character”); Output:
else if (ch >=‘a’ && ch <=‘z’) Enter a character: A
printf(“\n Entered Character is Lower case character”) Entered Character is Upper case character
else if (ch>=‘A’ && ch<=‘Z’) ASCII value of A is 65
printf(“\n Entered Character is Upper case character”);
else
printf(“\n Entered Character is special character”);
Array Definition:
➢ An array is a collection of Homogeneous data elements( similar data items) stored at contiguous memory locations and
elements can be accessed randomly using indices of an array.
➢ They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type.
Single-Dimensional array or One-Dimensional Array or Linear array(single row to store the elements. ) is defines as
an array with n elements where each elements stored in consecutive locations(All elements are stored in sequential
fashion in memory one after the other
Declaring a Array:
Syntax
General Syntax of One-Dimensional Array
Example
int marks[5 ];
xarry S 6 I 8.9 A M A X
xarry S A I H A M A
xarry S 6 8 8 10 56 88
0 1 2 3 4 5 6
carry S R I R A M A
Arrayname
Memory Location
0 1 2 3 4 5 6
farry 3.45 6.7 8.9 9.7 4.1 5.78 8.77
Arrayname
Memory Location
10 11 45 23 56
Five contiguous memory locations will be reserved and the values will initialized as shown below
10 11 45 23 56
Five contiguous memory locations will be reserved and the values will initialized as shown below
10 23 0 0 0
int regno[5];
for(i=0;i<5;i++)
{
scanf(“%d”,regno[i]);
}
Five contiguous memory locations will be reserved and the values will be assigned at run time
regno[0] regno[1] regno[2] regno[3] regno[4]
10 23 56 55 89
Example 2:
more values are there use for loop
int a[6]={10,30,45,77,88,99};
for(i=0;i<6;i++)
{
printf(“%d %d %d”,a[i]);
}
Example: Program to read Five elements and print five elements in the One-Dimensional Array
#inclue<stdio.h>
#include<conio.h>
void main()
{
int arr[5],i;
clrscr();
printf(“\nEnter 5 values into the array”;
for(i=0;i<5;i++)
{
scanf(“%d”,&arr[i]);
}
Printf(“\nArray elements are”);
for(i=0;i<5;i++)
{
printf(“%d”,arr[i]);
}
getch();
}
Example: Program to read n elements and print n elements in the One-Dimensional Array
#inclue<stdio.h>
#include<conio.h>
void main()
{
int arr[5],I,n;
clrscr();
printf(“Enter array size n:”);
scanf(“%d”,&n);
printf(“\nEnter 5 values into the array”;
for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
Printf(“\nArray elements are”);
for(i=0;i<n;i++)
{
printf(“%d”,arr[i]);
}
getch();
}
Problem1: Program to Accept the elements of integers in to 1D- Array and display them on the screen:
#include <stdio.h>
#include<conio.h>
int main() Output:
{
Enter the number of you want to accept :
int a[20], n, i;
clrscr(); 5
printf("Enter the number of you want to accept ");
Enter 5 elements:
scanf("%d", &n);
Enter a[0]:3
//code to read the elements in to 1D-Array
Enter a[1]: 5
printf("Enter %d elements",n); Enter a[2]: 9
3 5 9 4 7
}
}
getch()
}
Problem 2: Program to Accepts the elements of integers in to 1D- Array , display them screen and find the
sum of all the array elements
#include <stdio.h>
#include<conio.h>
int main() Output:
{
Enter the number of you want to accept :
int a[20], n, i, sum=0;
clrscr(); 5
printf("Enter the number of you want to accept ");
Enter 5 elements:
scanf("%d", &n);
Enter a[0]:3
//code to read the elements in to 1D-Array
Enter a[1]: 5
printf("Enter %d elements",n); Enter a[2]: 9
3 5 9 4 7
}
Sum of all the Elements of Array: 28
}
Printf(“Sum of all the Elements of Array is : %d”,sum);
getch();
}
Problem 3: Program to Accepts the elements in to 2D array of two Matrix and display in Matrix format:
#include <stdio.h>
#include<conio.h>
int main()
{
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
clrscr();
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r); Output:
printf("Enter the number of columns (between 1 and 100): ");
Enter the number of rows (between 1 and 100):2
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n"); Enter the number of columns (between 1 and 100):2
for (i = 0; i < r; ++i)
Enter elements of 1st matrix:
{
for (j = 0; j < c; ++j) Enter element a[0][0]: 2 Enter element a[0][1]: 3
{
Enter element a[1][0]: 4 Enter element a[1][1]: 2
printf("Enter element a [ %d ][ %d ]: ", i , j );
scanf("%d", &a[i][j]); Enter elements of 2st matrix:
} Enter element b[0][0]: 3 Enter element b[0][1]: 6
}
printf("Enter elements of 2nd matrix:\n"); Enter element b[1][0]: 4 Enter element b[1][1]: 1
for (i = 0; i < r; ++i) Elements of First Matrix:
{
for (j = 0; j < c; ++j) *******************
{ 2 3
printf("Enter element b[%d][%d]: ", i , j );
4 3
scanf("%d", &b[i][j]);
} Elements of Second Matrix:
}
*********************
Printf(“\nElements of First Matrix”);
for (i = 0; i < r; ++i) 3 6
{
4 1
for (j = 0; j < c; ++j)
{
printf(" %d ", a[i][j] );
}
printf(“\n”);
}
Printf(“\nElements of second Matrix”);
for (i = 0; i < r; ++i)
{
for (j = 0; j < c; ++j)
{
printf("%d ", b[i][j] );
}
printf(“\n”);
}
Problem4: Program to add to Matrix using 2-Dimensional Array
#include <stdio.h> printf(“\nElements of second Matrix”);
#include<conio.h> printf(“\n***********************”);
void main() for (i = 0; i < r; ++i)
{
{
for (j = 0; j < c; ++j)
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
{
printf("Enter the number of rows (between 1 and 100): "); printf(" %d ", b[i][j] );
scanf("%d", &r); }
printf("Enter the number of columns (between 1 and 100): "); printf(“\n”);
scanf("%d", &c); }
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
{ // adding two matrices
for (j = 0; j < c; ++j) for (i = 0; i < r; ++i)
{ for (j = 0; j < c; ++j)
{
printf("Enter element a [ %d ][ %d ]: ", i , j );
sum[i][j] = a[i][j] + b[i][j];
scanf("%d", &a[i][j]);
}
}
} // printing the result
printf("Enter elements of 2nd matrix:\n"); printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i) for (i = 0; i < r; ++i)
{ {
for (j = 0; j < c; ++j) for (j = 0; j < c; ++j)
{ {
printf("Enter element b[%d][%d]: ", i , j ); printf("%d ", sum[i][j]);
scanf("%d", &b[i][j]); }
printf("\n\n");
}
}
}
printf(“\n Elements of First Matrix”);
printf(“\n*********************”); return 0;
for (i = 0; i < r; ++i)
}
{
for (j = 0; j < c; ++j)
{
printf(" %d ", a[i][j] );
}
printf(“\n”);
}
Output: Elements of First Matrix:
5 9
8 4
Problem5 : Program to subtract Two Matrices using Two-Dimensional Array (Same like above use the symbol
#include<stdio.h>
#include<conio.h>
void main( )
{
char str1[20], str2[20]; Output:
str[ 8 ]=u
Problem10: Program to read a string and to count number of Alphabets, vowels,
consonants, digits, spaces and special characters
#include<stdio.h>
#include<conio.h>
void main()
{
char str[50];
int i,alpha_count=0,vowel_count=0,consonant_count=0,
int digit_count=0,space_count=0,splchr_count=0;
clrscr();
printf(“Enter a string with digits and special characters”);
gets(str);
for(i=0;str[i]!=’\0’;i++)
{
if(str[i] >= ’a’ && str[i] <= ’z’)
{
alpha_count++;
if(str[i]==’a’ || str[i]==’e’ || str[i]==’i’ || str[i]==’o’ || str[i]==’u’)
vowel_count++;
else
consonant_count++;
}
else if(str[i] >= ’0’ &&str[i] <= ’9’)
digit_count++;
else if(str[i]==’ ‘)
space_count++;
else
splchar_count++;
}
printf(“\n No of Alphabets in a given String is \t = %d”, alpha_count);
printf(“\n No of Vowels in a given String is = \t %d”, vowel_count);
printf(“\n No of consonants in a given String is =\t %d”, consonant_count);
printf(“\n No of digits in a given String is = \t %d”, digit_count);
printf(“\n No of spaces in a given String is =\t %d” , space_count);
printf(“\n No of special characters in a given String is=\t %d”,splchar_count);
getch();
}
Output:
Enter a String : #187 3rd cross bengalore-560034
No of Alphabets in a given String is = 16
No of Vowels in a given String is= 5
No of consonants in a given String is=11
No of digits in a given String is =10
No of spaces in a given String is =3
No of special characters in a given String is = 2
Program11: Program to convert characters to numbers
#include<stdio.h>
#include<coino.h>
Output:
void main()
{ ASCII Number of ch1 is: 97
char ch1=’a’ ch2=’x’; ASCII Number of ch2 is: 120
clrscr();
printf(“ASCII Number of ch1 is %d”,ch1);
printf(“\nASCII Number of ch2 is %d”,ch2);
getch();
}
}
Prg13:Program to demonstration of all string built-in functions
#include<stdio.h>
#include<conio.h>
void main(){ ***** performing string length ******
char string1[25],string2[25];
int l; Enter one strings:
clrscr(); rama
printf(“***** performing string length ******\n”); the string length is 4
printf(“Enter only one string \n”);
scanf(“%s”,string1);
**** performing string concatenation ****
l = strlen(string1);
Enter two strings
printf(“the string length is %d\n\n”,l);
printf(“**** performing string concatenation ****\n”); rama
printf(“Enter two strings\n”); krishna
scanf(“%s%s”,string1,string2); The concatenated string is: ramakrishna
strcat(string1,string2);
printf(“The concatenated string is %s\n\n”,string1); ***** performing string compare *****
printf(“***** performing string compare *****\n”); Enter tow strings
printf(“Enter two strings \n”); Rama
scanf(“%s%s”,string1,string2); Rama
if(strcmp(string1,string2) = = 0) Given Strings are equal
printf(“Given strings are equal\n”);
else *** performing string copy ****
printf(“strings are not equal\n”); Enter a string:
printf(“*** performing string copy ****\n”); the first string is ‘Krishna ‘ is copied into
printf(“enter a strings\n”); second string is: Krishna
scanf(“%d”,string1);
printf(“The first string is %s \n”,string1); Converting string to Lower Case *****
strcpy(string2,string1); Enter a string in Upper case RAMA
printf(“the first string is ‘ %s ‘ is copied into second string is %s\n”,string1,string2); The string in Lower Case: rama
printf(“***** Converting string to Lower Case *****\n”);
printf(“Enter a string in Upper case\n”); Converting string to Upper Case *****
scanf(“%s”,string1);
printf(“The string in lower case %s”,strlwr(string1)); Enter a string in Lower case: krishna
printf(“\n ***** Converting string to Upper Case *****\n”); The string in Upper Case: KRISHNA
printf(“Enter a string in Lower case\n”);
scanf(“%s”,string1);
printf(“\nThe string in Upper case %s”,strupr(string1));
getch();
}
Prg14:program to read a numbers from the keyboard continuously till the user press 999 and find sum of
only positive numbers.
#include<stdio.h>
#include<conio.h> Output:
void main()
Enter the numbers both positive as well as negative:
{
int x,sum=0; you want to stop entering type 999 at the end
printf(“Enter the numbers both positive as well as
negative \n”); 23 45 67 8 -3 6 -2 98 999
printf(“you want to stop entering type 999 at the end”); Sum of the positive numbers Entered is : 242
while(1)
{
scanf(“%d”,&x);
if( x == 999)
break;
if (x >0)
sum=sum+x;
}
Printf(“\n Sum of the positive numbers Entered is : %d”,sum);
getch() }
int num[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
➢ In the above image shows the two dimensional array having 3 rows and 4 columns.
➢ The compiler will allocate the memory for the above two dimensional array row-
wise meaning the first element of the second row will be placed after the last element of the
first row.
if we assume that the first element of the array is at address 1000 and the
size of type int is 4 bytes then the elements of the array will get the
following allocated memory locations.
1000 1004 1008 1012 1016 1020 1024 1028 1032 1036 1040 1042
printf(“%d”, a[1][1]
printf(“%d”, a[2][0]
scanf(“%d”, list[i][j]
for(i=0;i<4;i++)
{
for(j=0;j<2;j++)
{
printf(“%d \t ”, list[i][j]);
}
printf(“\n”); // to give new line after each row
}
Operations on 2 D Array
The following operations can be carried out in 2D array:
1. Traversal of an array (Accept and Display Elements)
2. Sum of row /column elements
3. Transpose of a matrix
4. Addition and subtraction of two Matrix
5. Multiplication of Matrix
Programs on 2D Array :
1. Accept and display Elements in to the two dimensional Array
2. Addition and subtraction of two Matrix
3. Multiplication of two matrix
Refer the these programs in the PDF sent earlier
Functions in C
Functions:
In c, we can divide a large program into the basic building blocks known as function.
➢ A function is a named, independent section of c code that perform a specific task.
➢ The function is also known as procedureor, subroutinein other programming languages.
➢ Function is designed to perform smaller task.
Types of Functions
There are two types of functions in C programming:
1.Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(),
puts(), ceil(), floor() etc.
2.User-defined functions: are the functions which are created by the C programmer, so that he/she can use it
many times. It reduces the complexity of a big program and optimizes the code.
Advantage of functions in C
There are the following advantages of C functions.
➢ By using functions, we can avoid rewriting same logic/code again and again in a program.
➢ We can call C functions any number of times in a program and from any place in a program.
➢ We can track a large C program easily when it is divided into multiple functions(Modules).
➢ Reusability is the main achievement of C functions.
Function Aspects or different parts of function:
There are three aspects or parts of a C function.
1.Function declaration/ function prototype A function must be declared globally in a c program to tell the
compiler about the function name, function parameters, and return type.
2.Function call Function can be called from anywhere in the program. The parameter list must not differ in
function calling and function declaration. We must pass the same number of functions as it is declared in the
function declaration.
3.Function definition It contains the actual statements which are to be executed. It is the most important
aspect to which the control comes when the function is called. Here, we must notice that only one value can
be returned from the function.
➢ Function Name: This is the name of the function using which we can call the function when & where
needed.
➢ Parameters: The parameters are the input values which will be passed to the function. It tells about the data
types of the arguments, their order and the number of arguments that will be passed to the function. The
parameters are optional. You can also have functions without parameters.
2. Function Body: The function body is the set of statement which performs a specific task. It defines what the
function does.
Example for function Definition:
(Formal Parameter)
2.Function Declaration /Function prototype:
Example:
// function definition
Formal Parameter:
int add(int x, int y) 1.function header
{
int sum = x+y;
return(sum); 2.function body
}
Categories of function:
Depending on whether arguments are present or not and whether a value is returned or not, functions
are categorized into −
1. Functions without arguments and without return values
2. Functions without arguments and with return values
3. Functions with arguments and without return values
4. Functions with arguments and with return values
1.Functions without arguments and without return values:
➢ Functions does not contain any formal parameters and it does not return any
value to the calling function
➢ Any function does not return any value is nothing but void function
#include<stdio.h>
void main ()
{
1
void sum (); //function declaration or prototype
clrscr (); Output:
sum (); 2 //functioncall (No arguments) Enter 2 numbers:
getch (); 3
} 5
Sum=8
void sum ()
{
int a,b,c;
printf("enter 2 numbers:");
scanf ("%d%d", &a, &b); 3 //function Definition
c = a+b;
printf("sum = %d",c);
}
No Return value
2.Functions without arguments and with return values
➢ Functions does not contain any formal parameters and it returns not a value to the calling function
➢ Any function returns a value to called function should have return statement
#include<stdio.h>
void main ()
{
int sum ();
int c;
Output:
c= sum (); Enter two numbers 10 20
printf(“Sum = %d”,c); Sum = 30
getch ();
}
int sum ()
{
int a,b,c;
printf(“enter 2
numbers”);
scanf (“%d%d”, &a, &b);
c = a+b;
return c;
}
3.Functions with arguments and without return values
➢ Functions contains formal parameters and actual arguments will be passed to the calling function
➢ Any function does not return any value is nothing but void function
#include<stdio.h>
void main ()
{ Output:
void sum (int, int ); Enter two numbers 10 20
int a,b; Sum=30
printf("enter 2 numbers");
scanf("%d%d", &a,&b);
sum (a,b);
getch ();
}
void sum ( int x, int y)
{
int c;
c= x+y;
printf (“sum=%d”, c);
}
No Return value
4.Functions with arguments and with return values:
➢ Functions contains formal parameters and actual arguments will be passed to the calling function
➢ Any function returns a value to called function should have return statement
#include<stdio.h>
void main ()
{
int sum ( int,int); Output:
int a,b,c; Enter two numbers 10 20
printf("enter 2 numbers"); Sum=30
scanf("%d%d", &a,&b);
c= sum (a,b);
printf ("sum=%d", c);
getch ();
}
int sum ( int x, int y )
{
int c;
c= x+y;
return c;
}
Passing parameters to the called function(Calling a Function) :
There are two ways in which we can call a function:
➢ Call by value :- function_name(var1,var2);
➢ Call by reference:- function_name(&var1,&var2);
1.Call by value:
➢ In call by value method, the value of the actual parameters is copied into the formal parameters.
➢ In call by value method, we can not modify the value of the actual parameter by the formal parameter.
➢ The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in
the function definition.
➢ Calling the function with its vales is as follows: function_name(var1,var2);
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not change by changing the formal
parameters in call by value, a = 10, b = 20
} Output:
void swap (int x, int y)
Before swapping the values in main a = 10, b = 20
{
int temp; After swapping values in function x = 20, y = 10
temp = x; After swapping values in main a = 10, b = 20
x=y;
y=temp;
printf("After swapping values in function x = %d, y = %d\n",x,y); // Formal parameters, a = 20, b = 10
}
2.Call by reference in C:
➢ In call by reference, the address of the variable is passed into the function call as the actual parameter.
➢ The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is
passed.
➢ In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the
function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same
address.
➢ Calling function using call by reference :- function_name(&var1,&var2);
Example:-Call by reference Example: Swapping the values of the two variables:
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do change in call by reference, a = 10, b =
20
Output:
}
void swap (int *x, int *y)
Before swapping the values in main a = 10, b = 20
{ After swapping values in function x = 20, y = 10
int temp; After swapping values in main a = 20, b = 10
temp = *x;
*x=*y;
*y=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); } // Formal parameters, a = 20, b = 10
Difference between call by value and call by reference in c
1 A copy of the value is passed into the function An address of value is passed into the function
2 Changes made inside the function is limited to the Changes made inside the function validate outside of
function only. The values of the actual parameters the function also. The values of the actual parameters
do not change by changing the formal parameters. do change by changing the formal parameters.
3 Actual and formal arguments are created at the Actual and formal arguments are created at the same
different memory location memory location
Types of arguments/parameters in functions:
There are two types of arguments. They are
1.Actual Arguments/parameters
2.Formal Arguments/parameters
1.Actual Arguments:
➢ The arguments associated with a function call is referred to as actual arguments.
➢ The arguments that are sent from a function call to the called function are called Actual arguments
2.Formal arguments:
➢ Arguments specified in the function header is called formal arguments.
➢ The order, datatype and number of the actual and formal parameters must be same.
Assignment questions:
1.Define a function?
2.Advantages of function?
3.What do mean by called function and calling function?
4.What are the different types of functions?
5.What are the different Categories of function?
6.What are the different parts of function? Explain with syntax and Example?
7.What are the different way of calling function explain with example?(call by value and call
by reference)
8.What is library function? Give two example of it?
9.Explain function prototype?
Strings in C
1.Operations on Strings
2.Built-in-functions of Strings
Strings
What is a Strings?
String in C programming is a sequence of characters terminated with a null character ‘\0’. Strings are defined
as one-dimensional array of characters.
Each character in an array occupies one byte in the memory and last character must be ‘\0’.
Terminator character ‘\0’ is important in Strings.
Character Array:
Arrayname
Memory Location
➢ One character occupies 1bytes in the memory.
➢ So Each character occupies contiguous memory location.
➢ String are stored in memory as ASCII(American Standard Code for Information Interchange)
S R I R A M A \0
83 82 73 32 82 65 77 65 0
Operations on Strings
3) strcat(first_string, second_string) concats or joins first string with second string. The result of the string is
stored in first string.
4) strcmp(first_string, second_string) compares the first string with second string. If both strings are same, it
returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in lowercase.
7) strupr(string) returns string characters in uppercase.
1) strlen( ) Function :
➢ strlen( ) function is used to find the length of a character string.
➢ Its prototype will be available in <string.h>
Example: int n;
char st[20] = “Bangalore”;
n = strlen(st);
// Find the length of a given String Using the strlen() function
#include<stdio.h>
#inlcude<string.h>
Output:
#include<conio.h>
Enter a line of text: Rjsfgc college
void main()
The length of the string:14
{
int length;
char str[20];
clrscr();
puts(“\n Enter a line of text”);
gets(str);
length=strlen(str);
printf(“\n The length of the string is : %d “,length);
}
2.Copying a string using strcpy():
➢ Strcpy() copies the string from source string to destination string including ‘\0’ (string Terminator or Null
Character)
➢ strcpy() returns a pointer to the new string ie. destination string.
➢ When we are using strcpy(),destination string should be declared before.
Source str S R I R A M A \0
Destination str S R I R A M A \0
Example:
char sourcestr[20]=“SRI RAMA”;
char des_str[30];
strcpy(des_str, sourcestr);
strcpy(des_str, sourcestr);
char a[5]
Note:
➢ It copy’s ‘n’ characters of source string into destination
string.
➢ The length of the destination string must >= that of
the source string. char b[3]
3.Concatenation of two strings using strcat() function:
➢ strcat() C LIBRARY function performance the string “CONCATINATION”
➢ It is used to appending the string .
➢ Appends a copy of str2 onto the end of str1 moving the terminating character’\0’ at the end.
➢ The length of the destination string must be > than the source string.
str1 R A M A \0
str2 K R I S H N A \0
str1 R A M A K R I S H N A \0
AFTER CONCATINATION
Example:
char str1[60]=“RAMA”;
char str2[30]=“KRISHNA;
strcat( str1,str2);
str1 S R I R A M A \0
str2 S R I R A M A \0
Example:
char str1[20]=“ SRI RAMA”;
char str1[30]=“ SRI RAMA”
strcmp(str1,str2);
strcmp() functions returns “0” in this case because both the strings are equal
//program To compare two Strings using strcmp() function
#include<stdio.h>
#inlcude<string.h>
void main()
{
char str1[50], str2[20]; Output:
int i; Enter First String1: RAMA
puts(“ Enter First string1 ”); Enter Second String2: RAMA
gets(str1);
Printf(“Enter Second string2:”); The given two strings are equal
gets(str2);
Enter First String1: RAMA
i=strcmp(str1, str2); Enter Second String2: GAMA
}
strupr() function:
➢ strupr() function is used to convert the lowercase letters to uppercase letters.
➢ After converting uppercase the string will be stored in the same string.
}
strlwr() function:
➢ strlwr() function is used to convert the upper case letters to lower case letters.
➢ After converting lowercase the string will be stored in the same string.
}
strrev() function:
➢ The strrev() function is used for reversing a string.
➢ The reversed string will be stored in the same string.
Syntax:
strrev (string)
}
The strncat () function
•This is used for combining or concatenating n characters of one string into another.
•The length of the destination string must be greater than the source string
•The resultant concatenated string will be in the destination string.
Syntax:
strncat (Destination String, Source string,n);
#include<stdio.h>
#include <string.h>
void main ()
{
Output:
char a [30] = "Hello";
Concatenated string = Hello Good.
char b [20] = "Good Morning";
clrscr ();
strncat (a,b,4);
a [9] = '\0';
printf("concatenated string = %s", a);
getch ()
}
The strncmp () function
This function is used for comparing first ‘n’ characters of 2 strings.
Syntax:
strncmp ( string1, string2, 2)
#include<stdio.h>
#include <string.h>
void main () Output:
{ Both the strings are equal
char a [30] = “the";
char b [20] = “there";
int i;
clrscr ();
i=strncmp (a,b,3);
if(i==0)
{
printf(“Both the strings are equal”);
}
getch ()
}
Program to find the length of a given string with out using builtin function
#include<stdio.h>
#include<conio.h>
void main()
{
int i, length=0;
char str[50];
clrscr();
printf(“Enter a string to calculate the length”);
gets(str);
for(i=0;str[i]!=’\0’;i++)
{
length++;
}
printf(“\n The length of a given string is: %d”,length);
getch();
}
ASCII Table
Factorization Methods
Factorization Methods :
7 X 3 = 21
x X X-2 = x2 – 2x
Factors of 21 Factors of X2 – 2x
Example : √3
Approx=0.5 *number Iteration Approx Root
0.5*3=1.5 0.5*(1.5 + (3/1.5))=1.75
root=0.5 *(approx + (number/approx)
1 Root != Approx => 1.75 != 1.5 continue the
While root != Approx process
2 1.75 Root=0.5*(1.75+3/1.75)
Approx=Root =1.7321428571428572
New Root!=Approx=>
1.7321428714228572 != 1.75
root=0.5 *(approx + (number/approx)
3 1.7321428571428572 =1.7320508100147274
4 1.7320508100147274 1.7320508075688772
Root=0.5(1.75+3/1.75)
5 1.7320508075688772 1.7320508075688772
Square root of √3 = 1.7320508075688772
2 Finding Smallest Divisor of an integer
2.Finding Smallest Divisor of an integer
To find smallest divisor of an integer n is very straight forward. Just take the numbers 2, 3, 4, …,n
and divide n with each of number in ascending order. But not efficient method, because it need
more iteration ( loops) .
To efficiently calculate this problem we must reduce the loops by various techniques. And are
follows.
· All exact divisors of an integer are paired. What it means?.
for example an integer 24 have following divisors 2, 3, 4, 6, 8, 12.
And each divisor have pair.
Here 2 and 12 are paired. In other word they are linked because
24/2 = 12 ;
2, 12 are smaller and bigger factors respectively .
Same way 3 and 8 are paired, i.e. (24/3 = 8;) and so on.
Smaller factor Bigger factor
2 12
3 8
4 6
If n is an even number then its smallest divisor is 2. Now we need consider only odd
numbers test for n=3,5,7,9…..
If we get n is the smallest divisor of n then it’s a prime ,i.e. one is smallest divisor.
4.8989794855
Finding the smallest Divisor of an integer
Algorithm steps:
Step1.Start
Step 2 :Declare variable n,r,i
Step 3:Read input n
Step 4: If n is even ie. n mod 2==0 then 2 is smallest divisor.
Step 5: Compute r = square root n;
Step 6:Initialize i = 3;
Steps 7:While i is less than or equal to r do the following steps( r ≠ √n)
a)if (n mod i)==0 then print i is the smallest divisor go to stop
b) i=i+2
Step 8: Print n is the smallest divisor( it is a prime number)
Step 9: Stop
include <stdio.h>
#include <math.h>
void main()
{
int n,i;
float r;
printf("Enter a Number: ");
scanf("%d", &n);
if (n % 2 == 0)
printf(“ Number is Even 2 is the smallest Divisior”);
else
r=sqrt(n);
for (i = 3; i <= r; i=i+2 )
{
if (n % i == 0)
{
printf(“Smallest divisor of n %d is = %d “, n,i);
break;
}
}
print(“n =%d is the smallest divisor to itself (Prime number)”, n);
4.Prime factorization:
Prime factorization is a way of expressing a number as a product of its prime factors.
A prime number is a number that has exactly two factors, 1 and the number itself
Example of prime numbers:2,3 7,11,13,17,19 etc
For example, if we take the number 30.
➢ 30 = 5 × 6, but 6 is not a prime number.
➢ The number 6 can further be factorized as 2 × 3, where 2 and 3 are prime numbers.
➢ Therefore, the prime factorization of 30
30= 2 × 3 × 5,
➢ where all the factors are prime numbers.
Example:
Prime factorization of any number means to represent that number as a product of prime numbers. For
the prime factorization of 40 can be done in the following way:
Example:
Prime factorization of any number means to represent that number as a product of prime numbers.
The prime factorization of 40 can be done in the following way:
Prime Factorization of a Number
Let us see the prime factorization chart of a few numbers in the table given below:
36 22 × 32
24 23 × 3
60 22 × 3 × 5
18 2 × 32
72 23 × 32
45 32 × 5
40 23 × 5
50 2 × 52
48 24 × 3
30 2×3×5
42 2×3×7
Algorithm: To compute Prime Factors of an integer:
Step 1: Start
Step 2: Declare Variable n and i
Step 3: Read Number n
Step 4: While n is divisible by 2,repeate the following steps
a)Print 2
b)Divide n/2
Step 5:After step 4,n must be odd
i=3 to the square root of n, repeat the following steps
a)While n divisible by i,
a.1) print i
a.2) Divide n /i
b)After i fails to divide by n ,increment i by 2 and continue
Step 6: if n> 2 print n
Step 7: Stop
/ Prime factor program in C
#include<stdio.h> C Program: To compute Prime Factors of an integer:
#include<math.h>
void main()
void primeFactors(int num) { {
int i; int num;
// Print the number of 2s that divide num printf("Please enter any positive number to find factors : ");
while(num % 2 == 0) scanf("%d", &num);
{ primeFactors(num);
printf("%d, ", 2);
num = num/2;
}
} Output:
// num must be odd at this point Please enter any positive number to find factors : 110
for(i = 3; i <= sqrt(num) ; i=i + 2) 2, 5, 11,
{
// while i divides num, // print i and divide num
while(num % i == 0) Please enter any positive number to find factors : 99
{ 3, 3, 11,
printf("%d, ", i);
num = num/i;
}
}
// Handle the case when num is prime // number greater than 2
if(num > 2) {
printf("%d, ", num);
}
}
5. Generation of Pseudo Random Number Generation(PRNG):
There are generally two types of random number generators(RNG):
1. True random number generators.
2. pseudorandom number generators
1.True random number generators:
➢ True random number generators. A true random number generator (TRNG), also known as a
hardware random number generator (HRNG), does not use a computer algorithm.
➢ Instead, it uses an external unpredictable physical variable such as radioactive decay of isotopes
or airwave static to generate random numbers.
➢ Similarly, subatomic particles are also ideal variables of an unpredictable system since they
exhibit truly and completely random behavior, also known as pure randomness.
Xn+1 = (a Xn + c) mod m
➢ We generate the next random integer using the previous random integer, the integer constants, and
the integer modulus.
➢ To get started, the algorithm requires an initial Seed, which must be provided by some means.
Example [LCM]
• Use X0 = 27, a = 17, c = 43, and m = 100.
• Xn+1 = (a Xn + c) mod m
• The Xi values are:
X1 = (ax0 + c) mod m = (17*27+43) mod 100 = 502 mod 100 = 2,
X2 = (ax1 + c) mod m = (17*2+43) mod 100 = 77 mod 100 = 77,
X3 = (ax2 + c) mod m = (17*77+43) mod 100 = 1352 mod 100 = 52,
X4 = (ax3 + c) mod m = (17*52+43) mod 100 = 927 mod 100 = 27,
X5 = (ax4 + c) mod m = (17*27+43) mod 100 = 502 mod 100 = 2,
X6= (ax5 + c) mod m= (17*2+43) mod 100 = 77 mod 100 = 77,
Note: Random numbers are repeating since m value is small .So we should choose m is very big like 2 33
20
Pseudo Random Number Generation(PRNG): Linear Congruential Generator Method
#include<stdio.h>
#include<maths.h>
Void generatePseudoNumbers(int n)
{ Output:
int a=109, c=853, m=40960,I; Enter how many pseuodo numbers to Generate: 5
long long int x=3553; Pseudo numbers are: 19490 36303 25720 19053 29630
printf(“Pseudo numbers are\n”);
for (i=1;i<=n;i++)
{
x=(a *x + c) % m;
print(“\t %lli \t” , x)
}
Void main()
{
Int n;
Printf(“Enter how many pseuodonumbers to Generate”);
Scanf(“%d”,&n);
generatePseudoNumbers(int n);
}
Pseudo Random Number Generation(PRNG): Using Predefined Built_in function rand():
rand() method:
➢ The function rand() is used to generate the pseudo random number.
➢ It returns an integer value and its range is from 0 to rand_max .
➢ RAND_MAX: is a constant whose default value may vary between implementations but it is granted to be at least
32767.
➢ The random number is generated by using an algorithm that gives a series of non-related numbers
whenever this function is called.
#include <stdlib>
#include <stdio.h>> Output: 1804289383 846930886 1681692777 1714636915 1957747793
using namespace std;
void main()
{
Int n;
Printf(“Enter how many pseuodo numbers to Generate”);
Scanf(“%d”,&n);
printf(“*****Pseudo Numbers are *****);
for (int i = 0; i < n; i++)
printf(“ %d “, rand() );
return 0; }
srand() function:
➢ srand() function is an inbuilt function in C which is a header file defined in <cstdlib>.
➢ srand() is used to initialize random number generators.
➢ The srand() function sets the starting point for producing a series of pseudo-random
integers.
➢ If srand() is not called, the rand() seed is set as if srand(1) were called at the program start.
➢ Any other value for seed sets the generator to a different starting point.
Syntax of srand() method:
void srand( unsigned seed );
OR
int srand( unsigned int seed);
Note: Seeds the pseudo-random number generator used by rand() with the value seed.
void srand(unsigned int number); #include <stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
Printf(“Enter how many pseuodo numbers to Generate”);
Scanf(“%d”,&n);
Output 1:
srand(time(0)); Enter how many pseuodo numbers to Generate: 5
printf(“*****Pseudo Numbers are *****); Pseudo numbers are: 22622 28802 3179 18146 31579
forn(i=0;i<n;i++)
{
printf("%d", rand());
}
srand(time(0));
printf(“*****Pseudo Numbers are *****); Output 2:
forn(i=0;i<n;i++) Enter how many pseuodo numbers to Generate: 5
{ Pseudo numbers are: 22720 23574 14816 19149 13336
printf("%d", rand());
}
}
6.Raising Number to the large power: pow() function
➢ Given two numbers base and exponent, pow() function finds x raised to the power of y
i.e. xy. Basically in C exponent value is calculated using the pow() function.
➢ pow() is function to get the power of a number, but we have to use
➢ #include<math.h> in c to use that pow() function. then two numbers are passed.
➢ Example – pow(4 , 2); Then we will get the result as 4^2, which is 16.
Syntax: double pow(double x, double y);
Parameters: The method takes two arguments:
x : floating point base value Example 2:
y : floating point power value Input: 5.0, 2.0
Example 1: Output: 25
Input: 2.0, 5.0 pow(5.0, 2.0) executes 5.0 raised to the power 2.0, which
equals 25
Output: 32
pow(2.0, 5.0) executes 2.0 raised to the power 5.0, which is equals 32
// C program to illustrate power() function
#include <math.h>
#include <stdio.h>
}
Calculate the power of a number using while loop with out using pow() function
#include <stdio.h>
int main() {
int base, exp;
long double result = 1.0;
printf("Enter a base number: ");
scanf("%d", &base); Output:
printf("Enter an exponent: "); Enter a base number: 3
scanf("%d", &exp); Enter an exponent: 4
Answer = 81
while (exp != 0) {
result =result* base;
exp- - ;
}
printf("Answer = %.0Lf", result);
return 0;
}
Roots of a Quadratic Equation
Complex or imaginary Roots
Algorithm to calculate the square roots of a given Number
Algorithm
Input − a,b,c values •Start
Output − r1, r2 values
•Initialize a,b,c,r1,r2,d
•Read a, b, c values
•Compute d = b2 -4ac
•if d > 0 then
• r1 = b+ sqrt (d)/(2*a)
• r2 = b - sqrt(d)/(2*a)
• Print r1,r2
•Otherwise if d = 0 then r1=r2
• compute r1 = r2= -b/2a
• print r1,r2 values
•Otherwise if d < 0 then print roots are imaginary
• real part=b/2*a
• imaginary part=sqrt(d)/2*a
•Print r1,r2
•Stop
Finding Roots of a quadratic equation
#include <math.h> // condition for real and equal roots
#include <stdio.h> else if (discriminant == 0) {
int main() { root1 = root2 = -b / (2 * a);
double a, b, c, discriminant, root1, root2, realPart, imagPart; printf("root1 = root2 = %.2lf;", root1);
printf("Enter coefficients a, b and c: "); }
scanf("%lf %lf %lf", &a, &b, &c); // if roots are not real
else {
discriminant = b * b - 4 * a * c; realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
// condition for real and different roots printf("root1 = %.2lf+%.2lf i and root2 = %.2f-%.2f i", realPart, imagPart,
if (discriminant > 0) { realPart, imagPart);
root1 = (-b + sqrt(discriminant)) / (2 * a); } Output:
root2 = (-b - sqrt(discriminant)) / (2 * a); } Enter coefficients a, b and c: 2.3
4
printf("root1 = %.2lf and root2 = %.2lf", root1, root2); 5.6
} root1 = -0.87+1.30i and root2 = -0.87-1.30i
Hash Searching :
1. Hashing
2. Hash Table
3. Hash Function
4. Collision
1. Chaining
2. Linear Probe( or)Open Address Method)
What is Hashing:
➢ Hashing is a process of mapping keys to their appropriate locations in the hash table.
➢ It is the most effective technique for storing and searching the elements in the hash table.
➢ Hashing allows to update and retrieve any data entry in a constant time O(1).
Hashing in a data structure is a two way process:
1.The hash function convert the item into small integer or hash value. The integer is used as an index to
store the original data.
2.It store the data in a Hash table .We can also use hash key to search the data in Hash Table.
Index Value
What is Hash Table?
➢ A Hash table is a data structure which is used to store data in associative manner.
➢ In hash table data is stored in an array format where each value has its own index value.
➢ Access of data become very fast if we know index of the desired data.
➢ In Hash Table insertion and searching operations are very faster Index Value
0 Value_1
1 Value_2
2 Value_3
3 Value_4
0 -1 Arr[0]
1 -1 Arr[1]
2 -1 Arr[2]
3 -1 Arr[3]
4 -1 Arr[4]
5 -1 Arr[5]
6 -1 Arr[6]
7 -1 Arr[7]
Note :-1 indicates the index location is available to store the element
Elements to store in Hash Table: 36, 18 , 72 , 43, 6
-1
-1
-1
-1
Elements to store in Hash Table: 36, 18 , 72 , 43, 6
Key=36
H(Key)= Key % 8
H(36)=36 % 8 = 4
……….
-1
-1
Collision in Hash Table: trying to store elements 10 , 26 , 19 ,27
-1
10 % 8 = 2
26 % 8 =2
-1
19 % 8 = 3
27 % 8 = 3
-1
What is Collision in Hashing?
➢ Collision is said to occur when two keys generated the same value ie. there is more than one key that is
pointing /map to the same slot in the hash table, this phenomenon is called Collision.
➢ It is vary important to choose good hash function, Where function does not generate the same index for
multiple keys in the hash table.
Example:
-1
Techniques to avoid Collision:
0
1
2
3
4
5
6
7
ii)search 19
0
1
2
3
4
5
6
7
Hash Search Algorithm:
Example to solve by Students: Construct the Hash Table for the following Elements and
draw the mapping.
Sr.No. Elements Hash Key Hash Table Index
1 1 1 % 20 = 1 1
2 2 2 % 20 = 2 2
3 42 42 % 20 = 2 2
4 4 4 % 20 = 4 4
5 12 12 % 20 = 12 12
6 14 14 % 20 = 14 14
7 17 17 % 20 = 17 17
8 13 13 % 20 = 13 13
9 37 37 % 20 = 17 17
Matrix Multiplication program and Algorithm
Algorithm of C Programming Matrix Multiplication
Step 1: Start the Program.
Step 2: Enter the row and column of the first (a) matrix.
Step 3: Enter the row and column of the second (b) matrix.
Step 4: Enter the elements of the first (a) matrix.
Step 5: Enter the elements of the second (b) matrix.
Step 6: Print the elements of the first (a) matrix in matrix form.
Step 7: Print the elements of the second (b) matrix in matrix form.
Step 8: Set a loop up to row.
Step 9: Set an inner loop up to the column.
Step 10: Set another inner loop up to the column.
Step 11: Multiply the first (a) and second (b) matrix and store the element in the third matrix (c)
Step 12: Print the final matrix.
Step 13: Stop the Program.
#include <stdio.h> printf("\n Enetr the elements of second for(i=0;i<n;i++)
void main() matrix "); {
{ for(i=0;i<r;i++) printf("\n");
int a[25][25],b[25][25],c[25][25],i,j,k,r,s; { for(j=0;j<s;j++)
int m,n; for(j=0;j<s;j++) {
printf("Enter the first matrix\n"); scanf("\t%d",&b[i][j]); c[i][j]=0;
scanf("%d%d",&n,&m); } for(k=0;k<m;k++)
printf("Enter the second matrix\n"); printf("\n The element of first matrix c[i][j]=c[i][j]+a[i][k]*b[k][j];
scanf("%d%d",&r,&s); is"); }
if(m!=r) for(i=0;i<n;i++) }
printf("\n The matrix cannot multiplied"); { }
else printf("\n"); printf("\n Multiplication of two matrix is");
{ for(j=0;j<m;j++) for(i=0;i<m;i++)
printf("\n Enter the elements of first matrix printf("\t%d",a[i][j]); {
"); } printf("\n");
for(i= 0;i<n;i++) for(j=0;j<n;j++)
{ printf("\n The element of second matrix printf("\t%d",c[i][j]);
for(j=0;j<m;j++) is"); }
scanf("\t%d",&a[i][j]); for(i=0;i<r;i++) }
} {
printf("\n");
for(j=0;j<s;j++)
printf("\t%d",b[i][j]);
}
Sorting Techniques
Sorting:
Arranging the set of data given (elements) in the array in either ascending or descending order is called sorting
Sorting Techniques:
1. Selection sort
2. Bubble sort/Exchange sort
3. Insertion Sort
4. Shell sort-Sort by Diminishing
Steps for Selection Sort in C
There are following Step of selection sort algorithm.
•Step 1-Select the smallest value in the list.
•Step 2-Swap smallest value with the first element of the list.
•Step 3-Again select the smallest value in the list (exclude first value).
•Step 4- Repeat above step for (n-1) elements untill the list is sorted.
Program for Selection Sort in C
#include <stdio.h> for(i= 0; i < n ; i++)
int min(int a[],int k,int n) {
{ loc=min(a,i,n);
Int loc, j , min;
min = a[k]; temp=a[i];
loc = k; a[i]=a[loc];
for(j=k+1; j <= n; j++) a[loc]=temp;
If(min> a[j])
{ }
min = a[j]; printf("Sorted Array:n");
loc = j
} for(i = 0; i < n; i++)
return (loc) printf("%dn", a[i]);
}
void main() }
{
int a[100], i, loc=0, temp;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d Numbersn", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
Merge Sort(Two_way Merge) and Selection Sort Techniques
1. Algorithm
2. Program
3. Example with Trace
Define Merging
➢ Merging is the process of combining two or more sorted list of data into a single sorted list.
➢ Merging algorithm takes two sorted arrays and produce a single sorted array as output.
➢ Example of Margining: Two-way merge Algorithm.
Two_Way Merge Algorithm:
Def:
Two-Way Merging algorithm takes two sorted arrays and produce a single sorted array as output.
➢ Let us consider the an array of A of 8 elements(m=8) and array B of 4 elements (n=4).
➢ Both the arrays are in sorted order .
➢ The resultant Array C will contains m+n= 8 +4=12 Elements in sorted order after Merging
➢ This process is called Two-Merge.
Array 10 14 18 20 40 50 60 70
A Size A m=8
k
An array contains 5 elements (m=5) and array B contains 3 elelemnts ( n=3).The result array c contains 5+3 =8 Elements
1) A[i] < B[j] = ( 10 < 20 ) is true ,therefore store A[i] in C[k].and increment i by 1 and k by 1
0 1 2 3 4 5 0 1 2
A 10 15 35 45 50 56 B 20 25 40
i 10 < 20 = True j
0 1 2 3 4 5 6 7 8 9
C 10
k
2) A[i] < B[j] = 15 < 20 is true ,therefore store A[ I ] in C[ k ].and increment i by 1 and k by 1
0 1 2 3 4 5 0 1 2
A 10 15 35 45 50 56 B 20 25 40
i 15 < 20 = True j
0 1 2 3 4 5 6 7 8 9
10 15
C
k
3) A[i] < B[j] = 35 < 20 is False ,therefore store B[j] in C[k] and increment j by 1 and k by 1
35 < 20 = False
0 1 2 3 4 5 0 1 2
A 10 15 35 45 50 56 B 20 25 40
i j
0 1 2 3 4 5 6 7 8 9
10 15 20
C
k
4) A[i] < B[j] = 35 < 25 is False ,therefore store B[j] in C[k].and increment j by 1 and k by 1
0 1 2 3 4 5 0 1 2
A 10 15 35 45 50 56 B 20 25 40
i j
0 1 2 3 4 5 6 7 8 9
10 15 20 25
C
k
5) A[i] < B[j] = 35 < 40 is True,therefore store A[i] in C[k].and increment i by 1 and k by 1
0 1 2 3 4 5 0 1 2
A 10 15 35 45 50 56 B 20 25 40
i j
0 1 2 3 4 5 6 7 8 9
10 15 20 25 35
C
k
6) A[i] < B[j] = 45 < 40 is False, therefore store B[ j ] in C[ k ].and increment j by 1 and k by 1
0 1 2 3 4 5 0 1 2
A 10 15 35 45 50 56 B 20 25 40
i 45 < 40 = False
j
0 1 2 3 4 5 6 7 8 9
10 15 20 25 35 40
C
k
7) All the elements of B has been copied into C .Now remaining Elements of A has to copy without any comparison
with the increment of I by 1 and k by 1
0 1 2 3 4 5 0 1 2
A 10 15 35 45 50 56 B 20 25 40
i i+1 i+1 J=n J reached to n copy
remaining elements of A into
C
Else
0 1 2 3 4 5 6 7 8 If i reached to m
10 15 20 25 35 40 45 50 56 Copy remaining element of B
C into C
k K+1 K+1
Step 1: Start Algorithm: Simple Merge/Two-Merge
Step 2:Declare Variables m,n,I,j,k
Step 3: Read number of Elements of an array A store it in m
Step 4: Read number of Elements of an array B store it in n Step 10: Copy the remaining Elements of Either array A or
Step 5: Declare Array of Integers A [m ],B[ m ] and C[ m+n ] array B to array C
merge(A,n,B,m,C);
}
Example for Selection Sort
4
min
5
1 3 6 4 8 9 5
sorted Unsorted Subarray
Subarray
min
Swap
6
7
1 3 4 6 8 9 5 1 3 4 6 8 9 5
sorted Unsorted Subarray
sorted Unsorted Subarray Subarray 8
Subarray min Swap
9
1 3 4 5 8 9 6 1 3 4 5 8 9 6
sorted Unsorted Subarray sorted Unsorted Subarray
Subarray Subarray
10 Swap
11
1 3 4 5 6 9 8 1 3 4 5 6 8 9
sorted Subarray Unsorted sorted Subarray
Subarray
Selection Sort Algorithm:
Example2
Structures in C
What are Structures in C?
➢ A structure is user defined data type in C allows the user to combine different data types together under a single name.
➢ A structure is a composite data type (derived from primitive data types such as int and float) that we use in order to
define a collection of similar or different data types under a single name in a particular block of computer memory.
Points to remember:
1.It is a collection of data of different data type.
2.It is a user defined data type.
3.Data can of int, char, float, double etc. data type.
4.We can access the member of structure by making the variable of structure.
5.struct keyword is used to create a structure.
Example 1
1.Declaration of structure variable method1:
This way is suitable when there are few variables to be declared
Syntax
The syntax of declaration of structure variables with structure definition:
struct <structure_name>
{
data_type memeber1
data_type memeber1
-----------------------------
-----------------------------
} struct_vat1,struct_var2;
➢ The structure variables are declared at the end of the structure definition ,right before termination the structure.
➢ The struct_var1,struct_var2 are the variable of type struct
1.Declaration of structure variable method1:
This way is suitable when there are few variables to be declared
Example
struct emp
{
char ename[20];
int eno;
float esal;
} e1,e2;
➢ The structure emp created with two variable e1,e2 are declared at the end of the structure definition.
➢ The ename,eno,esal are called structure members .
➢ e1,e2 are called structure variable of type emp
2.Declaration of structure variable method2:
This way is suitable when there are multiple variables to be declared.The structure variables are declares out side the
structure
Syntax
The Syntax of declarations of structure variable with structure definition
struct <structure_name>
{
data_type memeber1
data_type memeber1
-----------------------------
-----------------------------
};
➢ The structure variables struct_var1,struct_var2 are declared out side of the structure definition.
➢ The struct_var1,struct_var2 are the variable of type struct
➢ The keyword struct followed by structure_name
2.Declaration of structure variable method2:
This way is suitable when there are multiple variables to be declared.The structure variables are declares out side the
structure
Example
struct emp
{
char ename[20];
int eno;
float esal;
};
struct emp e1,e2,e3; //this can be any where in main or other function
➢ The structure emp created with two variable e1,e2 are declared out side the structure definition.
➢ The ename, eno, esal are called structure members and e1,e2,e3 are called structure variable of type emp
void main()
{
struct emp e1,e2,e3;
}
Initializing the structure variables:
➢ Structure members cannot be initialized like other variables in side the structure definition.
➢ When the structure is defining no memory is allocated to the structure’s data members.
➢ Memory is allocated only when a structure variable is declared.
struct emp
{
char ename[20]=“Naveen”; //COMPILE ERROR can not be initialize
int eno=1001; //COMPILE ERROR can not be initialize
float esal=35000.00; //COMPILE ERROR can not be initialize
} e1,e2;
Syntax
void main()
#include<stdio.h>
{
#include<string.h>
struct emp e1; //struct declaration
struct emp //struct Definition
strcpy(e1.name,”Naveen”);
{
e1.eno=1001;
char ename[20];
e1.esal=35000.00;
int eno;
}
float esal;
};
Example2
Example2
#include<stdion.h> #include<stdion.h>
void main() void main()
{ {
struct emp struct emp
{ {
char ename[20]; char ename[20];
int eno; int eno;
float esal; float esal;
}; };
struct emp e1={ “Naveen”,1001,35000.0 }; struct emp s[]={ “Naveen”,1001,50000.0
struct emp e2={ “Madhu”,1002,36000.0 }; “Madhu”,1002,36000.0
------------------------------------------------ “varun”1003,40000.0
} };
struct emp
{
char ename[20];
int eno;
float esal;
};
e1.name
e1.eno
e1.esal
struct emp
{
char ename[20];
int eno;
float esal;
};
Int the above code the structure emp has been define.
#include<stdio.h>
/*assigning the values to the member of the structure of Employee2 */
#include<string.h>
void main()
e2.sal=40000.00; //assign value to member = esal
{
e2.eno=1001; //assign value to member = eno
/* defining a structure templete */
strcpy(e2.ename,”Hari”); //assign value to member = ename
struct emp
{
/* Accessing the member of the structure */
char ename[20];
int eno;
printf(“employee name of e2 is %s”, e2.name);
float esal;
printf(“employee eno of e2 is %d”, e2.eno);
};
printf(“employee esal of e2 is %f”, e2.esal);
getch();
/*Strucutre variable declaration */
}
struct emp e1,e2;
/*assigning the values to the member of the structure*/
Struct atudent ➢ The given code allocate 15 Bytes of memeory for std1 and 15 Bytes for std2.
{ ➢ Structure Allocate Memory location for Each member of the structure.Each
cahr name[10]; member has its own memory
int age;
char gender;
}
std1={“RAMA”,43,’M’};
std2={“BAVAN”,27,’M’}
Naveen 24 M
3001-3010 3011-3014 3015
10bytes 4bytes 1Bytes
union student
union <Union_name> {
{ int age;
data_type member1; char gender;
data_type member1; float percentage;
----------------------------
}; };
Description:
➢ Keyword union: The keyword union is used at the beginning while defining a strucutre
➢ Union_name: This is the name of the union which is specified after the key word
➢ Data-Type: The data type indicates the type of the members of the union.A union can have data members of
different data type
➢ Members: This is the name of the data member of the union. Any number of data members can be defined
inside a union. All data members share the common memory location
Declaring a variable of Union in two ways:
1.Method1: 2.Method2:
union student
{ union student u1,u2,u3;
int age;
char gender;
float percentage;
} u1,u2,u3;
U1.age=10; U1.age=10
U1.age=10 U1.gender=‘M’
U1.gender=‘M’
➢ In the above member variable latest member variable stored in union is u1.perentage=78.5.
➢ Since for union one memory location will be created.
Program to Demonstrate data assigning and retrieving in Union
#include<stdio.h>
void main()
{
union student //union definition
{
int sage;
char sname[20];
float percent
};
union student u1,u2; //union variable declaration
u1.sage=20; //20 will be stored in memory
strcpy(u.sname,”rama”); //”rama” is overwritten on 20 in memory
u1.percent=60.5; //60.5 is overwritten on “rama”
printf(“%d \n”,u1.percentage // prints 60.5
printf(“%d \n”u1.sage) //ERROR u1.sage is not avilabe in memory
}
structure student union student
{ {
char name[40]; char name[40];
int roll_no; int roll_no;
int phon_number; int phon_number;
}; };
#include<stdio.h>
#include<conio.h>
#define PI 3.142
void main()
{
int r;
double area,circum;
clrscr();
printf("\n Enter radius of a circle : ");
scanf("%d",&r);
area=PI*r*r;
circum=2*PI*r;
printf("\n Area of a circle = %0.2lf",area);
printf("\n Circumference of a circle = %0.2lf",circum);
getch();
# include<stdio.h>
# include<conio.h>
# define MAX(a,b) (a>b ? a : b)
void main()
{
int a,b,c,L1,L2;
clrscr();
printf("\n Enter three numbers(a,b,c) :
");scanf("%d %d %d",&a,&b,&c);
L1=MAX(a,b);
L2=MAX(c,L1);
printf("\n Biggest number = %d",L2);
getch();
}
3. Program to check whether the number is prime or not
#include<stdio.h>
#include<conio.h>
void main()
{
int num,count=0,i;
clrscr();
printf("\n Enter a number : ");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
if(num%i==0)
count++;
}
if(count==2)
printf("\n %d is a Prime number",num);
else
printf("\n %d is not a Prime number",num);
getch();
}
# include<stdio.h>
# include<conio.h>
void main()
{
int num,orgnum;
int sum=0,rev=0,rem;
clrscr();
printf("\n Enter a number : ");
scanf("%d",&num);
orgnum=num;
while(num>0)
{
rem=num%10;
sum=sum+rem;
rev=rev*10+rem;
num=num/10;
}
printf("\n Sum of digits = %d",sum);
printf("\n Reversed number = %d",rev);
if(orgnum==rev)
printf("\n Number is a Palindrome");
else
printf("\n Number is not a Palindrome");
getch();
}
5. Program to read numbers from keyboard continuously till the user presses
999 and find the sum of only positive numbers
# include<stdio.h>
# include<conio.h>
void main()
{
int num,sum=0;
clrscr();
do
{
printf("\n Enter a number : ");
scanf("%d",&num);
if(num > 0 && num!=999)
sum = sum + num;
printf("\n Sum = %d",sum);
}while(num!=999);
printf("\n You have pressed 999 : STOP");
getch();
}
6. Program to read percentage of marks and to display appropriate message
Demonstration of (else-if) ladder
Percentage Grade
> 90% Exemplary
// 80% - 90% Outstanding
// 70% - 79% First Division with Distinction
// 60% - 69% First Division
// 50% - 59% Second Division
// 35% - 49% Pass class
// < 35% Fails : Re-appear
# include<stdio.h>
# include<conio.h>
void main()
{
float per;
clrscr();
printf("\n Enter Percentage : ");
scanf("%f",&per);
if(per > 90.0)
printf("\n Grade = EXEMPLARY");
else if(per >=80.0 && per < 90.0)
printf("\n Grade = OUTSTANDING");
else if(per >=70.0 && per < 80.0)
printf("\n Grade = FIRST DIVISION WITH DISTINCTION");
else if(per >=60.0 && per < 70.0)
printf("\n Grade = FIRST DIVISION");
else if(per >=50.0 && per < 60.0)
printf("\n Grade = SECOND DIVISION");
else if(per >=35.0 && per < 50.0)
printf("\n Grade = PASS CLASS");
else
printf("\n Grade = FAILS : RE-APPEAR");
getch();
}
7. Program to find roots of quadratic equation using Switch-Case
# include<stdio.h>
# include<conio.h>
# include<math.h>
void main()
{
int a,b,c,choice;
double
disc,root1,root2,real,img;
clrscr();
printf("\n Enter a,b,c : ");
scanf("%d %d
%d",&a,&b,&c);
disc=(b*b) - (4.0*a*c);
if(disc > 0)
choice=1;
else if(disc < 0)
choice=2;
else
choice=3;
switch(choice)
{
case 1 :
{
printf("\n Real and Distinct Roots");
root1= ( -b + sqrt(disc) ) / (2.0 * a);
root2= ( -b - sqrt(disc) ) / (2.0 * a);
printf("\n Root1 = %0.2lf",root1);
printf("\n Root2 = %0.2lf",root2);
}
break;
case 2 :
{
printf("\n Roots are complex and imaginary");
real = -b/(2.0 * a);
img = sqrt(abs(disc))/(2.0 * a);
printf("\n Root1 = %0.2lf +i %0.2lf",real,img);
printf("\n Root2 = %0.2lf -i %0.2lf",real,img);
}
break;
case 3 :
{
printf("\n Roots are Equal");
root1 = -b/(2.0 * a);
root2 = -b/(2.0 * a);
printf("\n Root1 = %0.2lf",root1);
printf("\n Root2 = %0.2lf",root2);
}
break;
# include<stdio.h>
# include<conio.h>
void main()
{
int a[20],n,i,j,ele;
clrscr();
printf("\n Enter array limit(n) : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter a[%d] : ",i);
scanf("%d",&a[i]);
}
// remove duplicate
for(i=0;i<n-1;i++)
{
ele=a[i];
for(j=i+1;j<n;j++)
{
if(ele==a[j] && a[j]!=-111)
{
printf("\n %d Duplicate entry!!!",a[j]);
a[j]=-111; //set -111 for duplicate entry
}
}
}
printf("\n Final Array list\n");
for(i=0;i<n;i++)
{
if(a[i]!=-111)
printf("%5d",a[i]);
}
getch();
}
10. program to perform addition and subtraction of Matrices
# include<stdio.h>
# include<conio.h>
void main()
{
int a[10][10], b[10][10], c[10][10], d[10][10];
int i,j,n;
clrscr();
printf("\n Enter order of square matrix(n) : ");
scanf("%d",&n);
getch();
}
# include<stdio.h>
# include<conio.h>
void main()
{
int num,i;
long int fact=1;
clrscr();
printf("\n Enter a number : ");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
fact=fact*i;
}
printf("\n Factorial of %d = %ld",num,fact);
getch();
}
12. Program to generate fibonacci series
# include<stdio.h>
# include<conio.h>
void main()
{
int n,i;
int F=0,S=1,NXT;
clrscr();
printf("\n Enter series limit(n) : ");
scanf("%d",&n);
printf("\n ******* FIBONACCI SERIES *******\n");
printf("%d \t %d",F,S);
for(i=3;i<=n;i++)
{
NXT=F+S;
printf("\t %d",NXT);
F = S;
S = NXT;
}
getch();
}
# include<stdio.h>
# include<conio.h>
void main()
{
int len=0,i=0;
char *str;
clrscr();
printf("\ Enter a string : ");
scanf("%s",str);
while(str[i]!='\0')
{
len++;
i++;
}
printf("\n Length of string = %d",len);
getch();
}
void main()
{
char *str1="Bangalore";
char *str2="University";
clrscr();
printf("\n String 1 = %s String 2 = %s\n",str1,str2);
printf("\n 1. Length of %s = %d",str1,strlen(str1));
printf("\n 2. String copy in str2 = %s",strcpy(str2,"CITY"));
printf("\n 3. Concatenation = %s", strcat(str1,str2));
printf("\n 4. Compare str1 & str2 %d",strcmp(str1,"bangalore"));
printf("\n 5. String in lower case = %s",strlwr(str1));
printf("\n 6. String in upper case = %s",strupr(str1));
printf("\n 7. Substring search = %s",strchr(str1,'L'));
printf("\n 8. Duplicate string = %s",strdup(str1));
printf("\n 9. String reverse = %s",strrev(str1));
printf("\n 10. Set all character to # = %s",strset(str1,'#'));
getch();
}
17. to read a string and to find the number of alphabets, digits, vowels,
consonants, spaces and special characters.
// C program to read a string and find the number of alphabets, digits,
// vowels, consonants, spaces and special characters
# include<stdio.h>
# include<conio.h>
# include<ctype.h>
void main()
{
char str[100],ch;
int acount=0, dcount=0, vcount=0, ccount=0, scount=0,spcount=0,i=0;
clrscr();
printf("\n Enter a string : ");
gets(str);
while(str[i]!='\0')
{
if(isalpha(str[i]))
{
acount++;
ch=tolower(str[i]);
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': vcount++;
break;
default : ccount++;
}
}
else if(isdigit(str[i]))
dcount++;
else if(isspace(str[i]))
scount++;
else
spcount++;
i=i+1;
}
printf("\n No. of Alphabets = %d",acount);
printf("\n No. of Vowels = %d",vcount);
printf("\n No. of Consonants = %d",ccount);
printf("\n No. of Spaces = %d",scount);
printf("\n No. of Digits = %d",dcount);
printf("\n No. of Special symbols = %d",spcount);
getch();
}
18. to Swap Two Numbers using Pointers
// C program to swap two numbers using pointers
# include<stdio.h>
# include<conio.h>
void main()
{
int n1,n2,*ptr1,*ptr2,temp;
clrscr();
printf("\n Enter two numbers : ");
scanf("%d %d",&n1, &n2);
ptr1=&n1;
ptr2=&n2;
//swapping
temp=*ptr1;
*ptr1=*ptr2;
*ptr2=temp;
# include<stdio.h>
# include<conio.h>
struct STUDENT
{
int regno;
char name[50];
char grade;
}BCA[50];
void main()
{
int n,i;
clrscr();
printf("\n Enter student count(n) :
");scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter %d student(regno,name,grade) : ",i+1);
scanf("%d %s %c", &BCA[i].regno, BCA[i].name, &BCA[i].grade);
}
getch();
}
# include<stdio.h>
# include<conio.h>
struct EMP1
{
int empid; //2 bytes
char name[50]; // 50 bytes
float salary; // 4 bytes (Total = 2 + 50 + 4 = 56)
};
union EMP2
{
int empid; // 2 bytes
char name[50]; // 50 bytes
float salary; // 4 bytes (highest = 50 bytes)
};
void main()
{
clrscr();
printf("\n Size of Structure EMP1 = %d",sizeof(struct EMP1));
printf("\n Size of Union EMP2 = %d",sizeof(union EMP2));
getch();
}
1.Write an algorithm to find the area and circumference of a circle.
Step 1: Start
Step 2: input r
Step 3: let pi = 3.14
Step 4: area = pi * r * r
Step 5: circum = 2 * pi * r
Step 6: print area, circum ,
Step 7: stop
2. Program to read three numbers and find biggest of three
Step 1: Start
Step 2: Ask the user to enter three integer values.
Step 3: Read the three integer values in num1, num2, and num3 (integer variables).
Step 4: Check if num1 is greater than num2.
Step 5: If true, then check if num1 is greater than num3.
5.1: If true, then print ‘num1’ as the greatest number.
5.2: If false, then print ‘num3’ as the greatest number.
Step 6: If false, then check if num2 is greater than num3.
6.1: If true, then print ‘num2’ as the greatest number.
6.2: If false, then print ‘num3’ as the greatest number.
Step7: Stop
STEP 1: START
STEP 2: Take num as input.
STEP 3: Initialize a variable count to 0.
STEP 4: Initialize the iterator variable loop to 2.
STEP 5: Iterate a “while” with the condition, loop <= num/2.
STEP 6: If num is divisible by loop iterator, then increment count.
STEP 7: If the count is equal to 0,
Return “Num IS PRIME”.
Else,
Return “Num IS NOT PRIME”.
STEP8: Stop
4. C program to read a number, find the sum of the digits reverse the number and
check it for palindrome
Step 1: Start
Step 2: Read the input number from the user
Step 3: Declare and initialize the variable sum=0 and reverse=0 and assign input to a
orgnum =num
Step 4: Start the while loop until num >0 becomes false
• rem = num % 10
• sum=sum+rem
• reverse=reverse* 10 + rem
• num = num / 10
Step 5: print sum to display the sum of digits
Step 6 : Check if reverse == orgnum
Step 7: If it’s true then the number is a palindrome
Step 8: If not, the number is NOT a palindrome
Step 9: Stop
5. Program to read numbers from keyboard continuously till the user presses 999 and
find the sum of only positive numbers
Step 2: Declare two integer variables, num and sum and initialize sum=0 value.
Step 3: Then, using the printf() function we displayed a message to the user that is Enter the
positive numbers between 0 to 999(enter 999 to quit):
Step 4 :Read integer number as input from the user
Step 5: start do - while loop and continue until user press the number 999 and do the sum of
all positive the numbers.Except 999.
5.1: sum=sum+num
Step 6 : Display sum of all the inputted integer numbers .
Step 7: Stop
Step 1 : start
Step 2 : read Percentage in the variable per
Step 3 : if per>= 90 then
Print grade as”EXEMPLARY”,
Step 4 : if per >= 80 and per <=90 then
Print grade is “OUTSTANDING”,
Step 5 : if per >=70 and per <=80 then
Print grade is “FIRST DIVISION WITH DISTINCTION”
Step 6 : if per >=60 and per <=70 then
Print grade is “FIRST DIVISION”
Step 7: if per >=50 and per <=60 then
Print grade is “SEOND DIVISION”
Step 8: if per >=35 and per <=50 then
Print grade is “PASS CLASS”
Step 9: display failed
Step 10 : stop.
STEP 1: START
STEP 2: declare n,marks[20],total_marks=0,avg_marks=0
STEP 2: READ the number of students whose average needs to be calculated
READ n
STEP 3: READ the marks of subjects of ‘n’ students into array marks
LOOP from i = 0 to n
READ m[i]
STEP 4: CALCULATE the total marks and average marks of ‘n’ students
LOOP from i = 0 to n
total=total+ m[i]
average = total_marks/n
STEP 5: PRINT total_marks and the average marks ,
STEP 6: END
RJS FRIST
I GRADE COLLEGE
I Semester BCA Examination (NEP - SCHEME)
Subject: COMPUTER SCIENCE
PAPER: PROBLEM SOLVING TECHNIQUE
MODEL PAPER -1
Time: 2 hours Max. Marks: 60
1. What is an Algorithm?
2. What is Ternary Operator?
3. What is Function Prototype?
4. Explain Array counting or Histogramming
5. List any 4 factoring methods
6. Mention any four string operations.
PART-B
II. ANSWER ANY 4 QUESTIONS
Each question carries 5 marks 4 x 5 = 20
PART-B
II. ANSWER ANY 4 QUESTIONS
Each question carries 5 marks 4 x 5 = 20
PART _ B
10. Write a C program to remove the duplicate entries in a single dimensional array.
11. How do find the smallest divisor of an integer ?
12. Write an algorithm to perform hash search on the given set of elements.
P.T.O.
NP - 163 Ilililril ililr til ililt ilfl ililll]
1 PART-C
Alswer any 4 questions. Each question carries 8 marks. (4x8=32)
18. a) Perform the Bubble sort operation on the following elements 29, s,19, 6s, 8
to arrange them in ascending order. 6
&t'{