0% found this document useful (0 votes)
3 views360 pages

PSTC

Uploaded by

ranjansaoun3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views360 pages

PSTC

Uploaded by

ranjansaoun3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 360

“Problem Solving Techniques” syllabus as per NEP

prescribed by Bengaluru City University


I Semester BCA Examination, FEB/MAR 2022
NEP - 2021 ONWARDS
Subject: COMPUTER SCIENCE
CA-C2T: PROBLEM SOLVING TECHNIQUES
Time: 2 hours Max. Marks: 60

Instruction: Answer any FOUR questions from each part

PART- A
[ 2m x 4q = (8 marks) ]
ANSWER ANY 4 QUESTIONS
Each question carries 2 marks (concept based)

6 QUESTIONS TO BE SET* (Answer any 4 questions)


(Question Numbers: 1,2,3) from Unit-1 & Unit-2
(Question Numbers: 4,5,6) from Unit-3 & Unit-4

PART-B
[5m x 4q = (20 marks)]
Each question carries 5 marks (numerical problems /algorithm/
tracing/flowcharts/programs based)**

6 QUESTIONS TO BE SET* (Answer any 4 questions)


(Question Numbers: 7,8,9) from Unit-1 & Unit-2
(Question Numbers: 10,11,12) from Unit-3 & Unit-4
PART-C
[8m x 4q = (32 marks)]
Each question carries 8 marks (long answers / short notes / logical
thinking ….)
6 QUESTIONS TO BE SET* (Answer any 4 questions)
(Question Numbers: 13,14,15) from Unit-1 & Unit-2
(Question Numbers: 16,17,18) from Unit-3 & Unit-4

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.

• Questions in Part-B should contain numerical problems / algorithms /


flowcharts / code programs … in the specific cases of discipline core
subjects, where problem solving is an essential component of learning.

• Questions of Part B and Part C may contain subdivisions i.e.,


o (i) questions 7 to 12 of Part B may be split into a, b & division of
marks in such cases should be clearly indicated – for example 2 +
3=5 marks or 1+4=5 marks. Similarly
o (ii) question 13 to 18 of Part C may be split into a, b, c with division
of marks clearly indicated – for example 3+5=8 marks or 2+6=8
marks or 2+3+3=8 marks and so on).
Introduction to Algorithms
Define an Algorithm?
➢ An Algorithm can be defined as a step-step procedure for accomplishing a task.
➢ An Algorithm is a sequence of unambiguous instructions for solving a problem .It is step by step
procedure with the input to solve the problem in a finite amount of time to obtain the required
output.
➢ An Algorithm is a set of well-defined instructions to solve a particular problem. It takes a set of input
and produces a desired output.
➢ An algorithm must be language independent i.e.It can be implemented in any language with same
output.
Characteristics of an Algorithm
1. Input
2. Output
3. Finiteness
4. Definiteness
5. Effectiveness
1.Finiteness:
➢ Algorithm should terminates after a number of steps.
➢ If we trace out the instruction of an algorithm then for all cases, the algorithm terminates after a finite number
of steps and finite time.
2.Definiteness:
➢ Each operation must be definite meaning that it must be perfectly clear.
➢ The action carried out must be rigorously and unambiguously.
3. Effectiveness:
➢ Each operation should be effective i.e. the operation must be able to carryout in finite amount of time.
For Example : Execution of 10billion instructions by algorithm1 takes 4Hrs where as for Algorithm2 it my take 24days.
4.Input:
➢ algorithm has zero or more “inputs” that are given to it initially before the algorithm begins or dynamically when as
the algorithm runs.
➢ These inputs are extremely provided to the algorithm.
5.Output:
➢ An algorithm has one or more “output” values that have a specified relation to the input.
➢ An algorithm produces at least one or more output.
Applications of Algorithms:
1.Internet
First, we will start with the internet which is very much important for our daily life and we cannot even
imagine our life without the internet and it is the outcome of clever and creative algorithms.
Numerous sites on the internet can operate and falsify this huge number of data only with the help of
these algorithms.
2.E.Commerce:
The everyday electronic commerce activities are massively subject to our data, for example, credit or
debit card numbers, passwords, OTPs, and many more. The centre technologies used incorporate
public-key cryptocurrency and digital signatures which depend on mathematical algorithms.
3.In Data Structure
1. stacks
2. Queues
3. Linked List
4. Strings
5. Matrix
4.Whether Forecasting
5.Networking
6.Sorting Algorithms
7.pageRanking in Google
8.In Graph Theory
9.Image processing
10.Artificial Intelligence
Algorithm Analysis:
➢ Algorithm analysis is an important part of computational complexity theory, which provides
theoretical estimation for the required resources of an algorithm to solve a specific computational
problem.
➢ Analysis of algorithms is the determination of the amount of time and space resources required to
execute it.
Two types of Analysis of Algorithm:
➢ The analysis of an algorithm is done base on its efficiency.
➢ The two important terms used for the analysis of an algorithm are: “
❖ Before implementation (Prior analysis)
❖ After implementation (Posterior analysis)
1.Priori Analysis:
➢ It is done before the actual implementation of the algorithm when the algorithm is written in the general
theoretical language.
➢ In this, the efficiency of the algorithm is calculated base on its complexity.
➢ It is just an approximate analysis.
2.Posterior Analysis:
➢ It is done after the actual implementation and execution of the algorithm using any programming
language like C, C++, Java, or Python.
➢ It is the actual analysis in which the space and time complexity of the algorithm is calculated more
correctly.
Sl.No A priori analysis A Posteriori analysis
1 Priori analysis is an absolute analysis. Posteriori analysis is a relative analysis.

It is independent of language of compiler and types of It is dependent on language of compiler and type of
2
hardware. hardware.

3 It will give approximate answer. It will give exact answer.

It uses the asymptotic notations to represent how


It doesn’t use asymptotic notations to represent the time
4 much time the algorithm will take in order to complete
complexity of an algorithm.
its execution.

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.

7 It is done before execution of an algorithm. It is done after execution of an algorithm.

It is costlier than priori analysis because of requirement of


8 It is cheaper than Posteriori Analysis.
software and hardware for execution.

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)

1. Constant time – O (1)


➢ An algorithm is said to have constant time with order O (1) when it is not dependent on the input size n.
Irrespective of the input size n, the runtime will always be the same.
Example: accessing the array element base on index, push, pop operations
T(n)=O(1)
2.Linear time – O(n)
An algorithm is said to have a linear time complexity O(n) when the running time increases linearly with the length of the
input.
When the function involves checking all the values in input data, with this order O(n).
Example: Linear search if the size of the array increases number of comparesions also increase intern time complexity
increases
T(n)=O(n)
3.Logarithmic time – O (log n)
An algorithm is said to have a logarithmic time complexity when it reduces the size of the input data in each step. This
indicates that the number of operations is not the same as the input size.
binary search functions. This involves the search of a given value in an array by splitting the array into two and starting
searching in one split.
T(n)=O(log n)
4.Quadratic time – O (n^2)
An algorithm is said to have a non-linear time complexity where the running time increases non-linearly (n^2) with the
length of the input. Generally, nested loops come under this order where one loop takes O(n) and if the function involves
a loop within a loop, then it goes for O(n)*O(n) = O(n^2) order
Similarly, if there are ‘m’ loops defined in the function, then the order is given by O (n ^ m), which are called polynomial
time complexity functions..
T(n)= O(n^2)
Growth-rate Functions
• O(1) – constant time, the time is independent of n, e.g. array look-up
• O(log n) – logarithmic time, usually the log is base 2, e.g. binary search
• O(n) – linear time, e.g. linear search
• O(n*log n) – e.g. efficient sorting algorithms Heap sort, Merge Sort
• O(n2) – quadratic time, e.g. selection sort
• O(nk) – polynomial (where k is some constant) :Matrix Multiplication,
Bubble Sort, Selection Sort, Insertion Sort, Bucket Sort.
• O(2n) – exponential time, very slow! :Towers of Hanoi
• O(n!) - Factorial algorithm –– Determinant Expansion by Minors, Brute
force
Order of growth of some common functions
O(1) < O(log n) < O(n) < O(n * log n) < O(n2) < O(n3) < O(2n)<O(n!)
Growth-rate Functions in Graphical Representation
Design techniques algorithm :
Selecting a proper design technique for algorithms is a complex but important task.
1) Brute-force or exhaustive search
2) Divide and Conquer
3) Greedy Algorithms
4) Dynamic Programming
5) Branch and Bound Algorithm
6) Randomized Algorithm
7) Backtracking

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

4.Global Declaration Section

5.main( ) Function section

6.Sub Program Section/User-Define function


STRUCTURE OF YOUR C PROGRAM
Six different Sections are there in C Program
STRUCTURE OF YOUR C PROGRAM
Six different Sections are there in C Program. They have explained as follows
1. The Documentation Section: Every thing about the Program .It consists of a set of comment lines giving
the name of the program and other details.
Comments are ignored by the compiler. 1 Single line Comments //
/*File Name: program.c 2 Multi line Comments /* ------ */
Author: Programmer Name
date: 09/08/2019
description: a program to explain basic structure of c programming
user enters the radius
*/
2.The Link Section provides instructions to the compiler to link functions from the system library. It contains
all the Header Files
#include<stdio.h>
#include<conio.h>
We use #include to declare header files in the link section.

3.The Definition Section: Defines all symbolic constants.


➢ This section of the program is used to declare the symbolic constant that will be used in the program.
➢ A symbolic constant is a constant value given to a name that can't be changed in the program.
#define NAME value #define PI 3.14
#define NAME (expression)
We use #define to declare the symbolic constant in the Definition Section.
4. The Global Declaration Section: The Global Declaration section is a part of the program, where the programmer declares
variables that are used in more than one function. Such variables are called global variables. User-defined functions are also
declared in this part of the code.
float area(float s);
int 10;

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

/*Documentation Section: program to find the area of circle*/


#include "stdio.h" /*link section*/
#include "conio.h" /*link section*/
#define PI 3.14 /*definition section*/
float area; /*global declaration section*/
void main()
{
float r; /*declaration part*/
printf("Enter the radius of the circle\n"); /*executable part starts here*/
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f",area);
getch();
}
int Sub(int a, int b) //sub-Program section
{
Return a-b;
}
Questions to Learn from this Chapter

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.

Types of Binary Operators are:


1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Bit-wise operators
5. Assignment operators
Arithmetic operators

➢ Arithmetic Operators are used to perform Arithmetic operations.(used


for calculation)
➢ Five Arithmetic Operators in C

Sl.No Operator Meaning Example


1 + Addition x=10,y=5
x+y ->15
2 - Subtraction x-y -> 5
3 * Multiplication x*y -> 50
4 / Division x/y -> 2
5 % Modulo Division x%y -> 0
It gives remainder 0
Division Operator( / ): 25 / 6 = 4 (Quotient)
Modulo Operator ( % ): 25 % 6 = 1 (Remainder)
#include<stdio.h>
void main() Example for Arithmetic operators
{
int a = 11, b = 4; // Declare and initialize variable a and b
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b); // because both operands are integer result will be
an integer 11/4=2(quotient)
printf("a %% b = %d\n", a % b); // % operator returns the remainder of 11/4 i.e 3
}
Relational Operators
➢ Relational operators are used to test the relationship between two variables or
constant
➢ If the relation is true it returns the value 1 otherwise it returns 0 for false

General Syntax

Exp1 <relational Operator> Expr2

Where Exp1 and Exp2 are two variables


List of Relational operators

Relational Meaning Example Result value


Operator
< Less Than x=10,y=5 False 0
x<y

> Greater Than x>y True 1

<= Less than or Equal to x<=y False 0

>= Greater than or equal to x>=y True 1

!= Not Equal to x!=y True 1

== Equal To x==y False 0


Example for Relational operators Output

#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.

Operator Meaning Example Result

&& Logical AND When x=9, y=5 True


(y>=5) && (x==9)

|| Logical OR (X>=6) || (y==4) True

! Logical NOT ! (x>8) False


The expression (a>b) && (a>c) gives a value either True(1) or False(0)
Expression What it Evaluate to

(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.

Truth table for logical AND OR NOT is given below:


AND OR NOT
Expr1 Expr2 Expr1 && Expr2 Expr1 Expr2 Expr1 || Expr2 Expr1 !(Expr1)
TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE
TRUE FALSE FALSE TRUE FALSE TRUE FALSE TRUE
FALSE TRUE FALSE FALSE TRUE TRUE

FALSE FALSE FALSE FALSE FALSE FALSE


#include<stdio.h>
Example on Logical operators
int main()
{
int a = 5, b = 10 ,ret;

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);

ret = ( ( a < b) && (a == b ) );


// 5 < 10 ==>true. 5 == 10 ==> false. So, 1 && 0 will return 0;
printf("Return value of above expression is %d\n",ret);

ret = ! ( ( a < b) && (a == b ) );


/*we have used the same expression here.
And its result was 0.
So !0 will be 1.*/
printf("Return value of above expression is %d\n",ret);
OUTPUT
return 0;
}
Assignment operators

In C, the assignment operator(=) can be used for assigning a value to a variable

General Syntax

Variable = value or Expression

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 (+,-,*,/).

Operator Description Example Equivalent Meaning


= Assignment x=2 x=2 Assign 2 to X
+= Sum and Assign x+=2 x=x+2 Adds 2 to x
-= Subtract and Assign x-=2 x=x-2 Subtracts 2
from x
*= Multiply and Assign x*=2 x=x*2 Multiply 2 to
x
/= Divide and assign x/=2 x=x/2 Divides 2 to x
Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for Bit
wise AND(&) ,Bitwise OR( | ), and Bitwise XOR( ^ ) is as follows −

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −

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.

>> Binary Right Shift Operator. The left operands


value is moved right by the number of bits A >> 2 = 15 i.e., 0000 1111
specified by the right operand.
#include <stdio.h>
main() Example on Bitwise operators
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */ Output:


printf("Line 1 - Value of c is %d\n", c );
Line 1 - Value of c is 12
c = a | b; /* 61 = 0011 1101 */ Line 2 - Value of c is 61
printf("Line 2 - Value of c is %d\n", c ); Line 3 - Value of c is 49
c = a ^ b; /* 49 = 0011 0001 */
Line 4 - Value of c is -61
printf("Line 3 - Value of c is %d\n", c ); Line 5 - Value of c is 240
Line 6 - Value of c is 15
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */


printf("Line 5 - Value of c is %d\n", c );

c = a >> 2; /* 15 = 0000 1111 */


printf("Line 6 - Value of c is %d\n", c );
}
Unary operators
Unary Operators:

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--

1.Unary Minus: This operator is used to represent negative numbers


Example:
b= -5;
A= -b;
2 .Increment and 3.Decrement Operators
➢ Increment operators in C is used to increment the given value of a variable by 1.
➢ Decrement operator (- -) is used to decrement a given value by 1
➢ For instance,
int a = 2 , b = 1;
++b; //now b=2
++a //now a=3 x=x+1 is same as x++ or ++x
--a //now a=1
--b //b=0 x=x-1 is same as x-- or --x

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:

Types of Increment and Decrement Operators in C


Following types of increment and decrement operators are found in the C
language:

Increment Operators

Prefix Increment operator (++a)

Postfix Increment operator (a++)

Decrement Operators

Prefix Decrement operator (--a)

Postfix Decrement operator (a--)


The prefix increment operator first increments the value of a variable and
then used inside any expression.

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( ? : )

➢ The conditional operator contains a condition followed by two statements or values.


➢ If the condition(Expression1) is True then first statement (Expression2) will be executed.
➢ If the condition is False then second statement (Expression3) will be executed
➢ The conditional operator represented by ( ?: )
➢ The conditional operator is also called Ternary Operator because it requires Three
operands.

(Expression1) ? Expression 2 : Expression 3

Condition True Part False Part


Example1
#include <stdio.h>
void main() Output
{
int a=10,b=5,y; a=10 is greater
y=(a>b) ? a : b;
printf(“a =%d is greater”);
getch();
}

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)

* Pointer indirection Operator


& Address Operator scanf(“%d”,&no);

-> Arrow Operator in Structure


. Dot Operator in Structure
# String Sizing Operator (prepocessor) #include<stdio.h>

## Token passing Director


sizeof()Operator
➢ sizeof() operator is a unary compile-time operator
➢ it is used to find the sizeof() any primitive data type, variables and constants

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

10 + 20 * 30 is calculated as 10 + (20 * 30)


and not as (10 + 20) * 30
Operators Associativity is used when two operators of same precedence appear in an expression.
Associativity can be either Left to Right or Right to Left.
For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the expression
“100 / 10 * 10” is treated as “(100 / 10) * 10”.
Operators Precedence and Associativity are two characteristics of operators that
determine the evaluation order of sub-expressions in absence of brackets
For example: Solve 100 + 200 / 10 - 3 * 10
Note on Precedence and Associativity
➢ Associativity is only used when there are two or more operators of same
precedence.
➢ All operators with the same precedence have same associativity.
➢ Precedence and associativity of postfix ++ and prefix ++ are different
➢ Precedence of postfix ++ is more than prefix ++, their associativity is also
different. Associativity of postfix ++ is left to right and associativity of prefix ++
is right to left.
➢ Comma has the least precedence among all operators
Solving Arithmetic Expressions based on Precedence and Associativity

Students has to analyze and solve the following examples


4 2
7 * (5 + 15) / (2 * 5) – 3 O/p=11

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;

int ans = ++a * (3 + 8) % 35 - 28 / 7;

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.

“C” SUPPORTS MAINLY THREE TYPES OF CONTROL STATEMENTS.


1. Decision making statements
a) Simple if Statement
b) if – else Statement
c) Nested if-else statement
d) else – if Ladder
e) switch statement
2. Loop control statements
a) for Loop
b) while Loop
c) do-while Loop

3. Unconditional control statements


a) goto Statement
b) break Statement
c) continue Statement
d) return statement
1. Decision making statements
1. Simple if Statement
2. if – else Statement
3. Nested if-else statement
4. else – if Ladder
5. switch statement
1) Simple “if” statement :
“if” statement is a powerful decision making statement, and is used to control the flow of execution of statements.
Syntax : Flow chart for if – else statement :

if (Condition or test expression)


{
Statement1;
Statement2; TRUE
….
….
Statementn;
}
Rest of the program;
➢ Condition of if statement will be evaluated first .It can be TRUE or FALSE.
➢ When the condition of if is TRUE then the statements in the if block will be executes. Other wise the if block will be
skipped.
➢ The condition is always enclosed within a pair of parenthesis i.e. ( ) ,
➢ The conditional statement should not terminated with Semi-colons (ie ;)
Example
# include<stdio.h>
# include<conio.h> Output1
void main( )
Enter a number: 7
{
Entered number is positive numbers
int m;
clrscr( );
printf(“\n Enter a numbers:”);
scanf(“%d ”, &m);
if(m>0)
{
printf(“\n Entered number is positive number”);
}
printf(“Following statement of if”);
getch();
}
Flow chart for if – else statement :
2. if – else Statement

Syntax :
if ( Test Expression or Condition )
{
True- Block Statements; /*true block (or) if block */
}
else
{
False-block Statements; /* false block (or) else block */
}

➢ If the condition is True, then the True-block statements are executed ;


➢ if the condition is False the False-block statements are be executed.
➢ In either case ,either True-Block or False-block will be executed
➢ True-block is also called if-block.
➢ False-block is also called else-block
Example for if-else
# include<stdio.h>
# include<conio.h> Output1
void main( )
{ Enter a number: 7
Entered number is positive numbers
int m;
clrscr( );
printf(“\n Enter a numbers:”); Output1
scanf(“%d ”, &m);
Enter a number: -7
if((m>0)
Entered number is negative
{ numbers
printf(“\n Entered number is positive number”);
}
else
{
printf(“\n Entered number is negative number”);
}
printf(“out of if-else”);
getch();
}
# include<stdio.h>
Output
# include<conio.h>
Run:1
main( )
Enter a number : 24
{
The given number is EVEN
int n;
clrscr( );
Run 2: /* that means one more time we run the
printf(“Enter a number :”);
program */
scanf(“%d”, &n);
Enter a number : 17
if( (n%2)==0 )
The given number is ODD
{
printf(“\n The given number is EVEN ”);
}
else
{
printf(“\n The given number is ODD ”);
}
getch( );
}
(3) Nested “if–else” Statement :
Using of one if-else statement in another if-else statement is called as nested if-else control statement.

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.

G.Syntax: switch( expression )


{
case value-1:
Block-1;
break;
case value-2:
Block-2;
break;
case value-n:
Block-n;
break;
default:
Block-1;
break;
}
Statement-x;
➢ The expression can be integer expression or a character expression.
➢ Value-1, 2, n are case labels which are used to identify each case individually.
➢ case labels always end with a colon ( : ). Each of these cases is associated with a block.
➢ Whenever the switch is executed, the value of test-expression is compared with all the cases
which we have defined inside the switch.
➢ The break keyword in each case indicates the end of a particular case. If we do not put the
break in each case then even though the specific case is executed, the switch in C will
continue to execute all the cases
➢ The default case is an optional one. Whenever the value of test-expression is not matched
with any of the cases inside the switch, then the default will be executed.
➢ Once the switch is executed the control will go to the statement-x, and the execution of a
program will continue.
Example Program on switch-case:

1.In the given program we have explain initialized a variable


num with value 8.
2.A switch construct is used to compare the value stored in
variable num and execute the block of statements associated
with the matched case.
3.In this program, since the value stored in variable num is
eight, a switch will execute the case whose case-label is 8.
After executing the case, the control will fall out of the switch
and program will be terminated with the successful result by
printing the value on the output screen.
2. Loop control statements
1. while Loop
2. do-while Loop
3. for Loop
While loop:
➢ A While loop is an entry-controlled loop structure.
➢ In a while loop, a condition is evaluated before processing a body of the loop. If a
condition is true, then and only then the body of a loop is executed.
➢ After the body of a loop is executed, the control again goes back to the beginning, and
the condition is checked. If it is true, the same process is executed until the condition
becomes false.
➢ Once the condition becomes false, the control goes out of the loop.

Syntax of While loop in C


Here is a syntax of While loop in C programming:

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:

Step 1) Start of while loop


Step 2) The test expression or condition is evaluated
Step 3) Next, if the test expression is true, the program
executes the body of do-while loop
Step 4) If the test expression is false, the program outside
while loop is executed
Example program for while loop: To print First 10 natural numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int num=1,fact=1; //initializing the variable with value 1
printf(“Enter how many values you want to add”); Output:
scanf(“%d”,&n); 1
while(num<=n) //while loop with condition 2
{ 3
fact=fact*num; 4
//Sum=sum+num 5
//printf("%d\n",num); 6
num++; //incrementing operation 7
} 8
printf(“factorial of %d is = %d ”,n,fact); 9
} 10
Do-While Loop
➢ A Do-while loop is similar to the while loop except that the condition is always executed after the body
of a loop.It is also called an exit-controlled loop.
➢ In the do-while loop, the body of a loop is always executed at least once.
➢ After the body is executed, then it checks the condition. If the condition is true, then it will again
execute the body of a loop.
➢ Otherwise, the control is transferred out of the loop.

Syntax Do While Loop in C


Here is a syntax of Do while loop in C programming:

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:

Flow Chart Explanation:


Step 1) Start the do-while loop
Step 2) The body of do-while loop is executed
Step 3) The test expression or condition is evaluated
Step 4) If the test expression is true, the compiler executes the body of
do-while loop
Step 5) Next, if the test expression is false, the compiler executes the
statements after the loop body
Step 6) Statements that come after the loop body are executed
Example for do-while loop to print first 4 natural numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int num=1; //initializing the variable with value 1
do //do-while loop
Output:
{
1
printf("%d\n",num);
2
num++; //incrementing operation
3
} while(num<=4);
4
}
Difference between while loop and Do-While loop

Sl.No While Do While


This loop will execute the statement(s) at least once, then
1 It checks the condition first and then executes statement(s)
the condition is checked.
While loop allows initialization of counter variables before Do while loop allows initialization of counter variables
2
starting the body of a loop. before and after starting the body of a loop.
3 It is an entry controlled loop. It is an exit controlled loop.
We do not need to add a semicolon at the end of a while We need to add a semicolon at the end of the while
4
condition. condition.
5 In case of a single statement, we do need to add brackets. Brackets are always needed.
In this loop, the condition is mentioned at the starting of
6 The loop condition is specified after the block is executed.
the loop.
Statement(s) can be executed zero times if the condition is
7 Statement is executed at least once.
false.
Generally while loop is written as: Generally do while loop is written as:
while (condition) Do
8 { {
Statements; // loop body Statements; //loop body
} } while (condition);
For loop in c Flow chart of for loop

1 First Step 2 Second Step

for(initialization_statement; test_condition; increment/Decrement_statement)


{
statement 1;
statemetnt 2;
}
4 Fourth Step
3 Third Step

➢ for is the keyword.


➢ initialization_statement can have variable declarations which will be used inside for loop.
➢ test_condition can be a complex condition that evaluates to a boolean value: True or False.
➢ increment/Decrement_update statement can have statements to increment, decrement or update the variables that
control the iteration of loop execution.
➢ statement(s) are a set of statements that are meant to be executed in loop until the test_condition evaluates to
false.
Example Problem: Program to display series of EVEN numbers until 20 (2,4,6,8,10,12,14,16,18,20) using FOR loop

#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;

printf(“Even Number series till 20:”);

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;

for(i=1; I <= 5; i++)


Output:
{
1
if(i==2)
continue;
3
printf(“%d”,i);
4
5
}
printf(“statements out side the loop”);
Sum=0;
for(i=1; I <= 100; i++)
{
if(i%2!=0)
continue;
sum=sum + i

}
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

In the above syntax,


➢ the first line tells the compiler to go to or jump to the statement marked as a label.
➢ Here label is a user-defined identifier which indicates the target statement.
➢ The statement immediately followed after ‘label:’ is the destination statement.
➢ The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.
The label in go-to staement :
➢ Must be defined within a function
➢ Each label in one function must have a unique name. It cannot be a reserved C word.
➢ C has a separate namespaces for identifiers and labels, so you can use the same name for
a variable and a label.
➢ Must be followed by a statement. We call it a “labeled statement”.
➢ Has function scope. Therefore the label:
- must have a unique name within that function.
- is not accessible outside the function, where it was defined.
➢ When the code reaches the goto statement, the control of the program “jumps” to the
label. Then the execution continues normally.
If the execution reaches the labeled statement without a jump the program will execute it
just like any other.
Problem: program to check whether a number is an odd or even using got 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

for(i=1;i<=5;i++) //it will execute inner loop 5 times


{
for(j=1;j<=5;j++) //it will print 5 stars continuously
Inner Loop
{
printf("*");
}
printf(“\n”); //It will give a newline, once 5 stars are printed
}

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 to solve by yourself like above


Convert Fahrenheit to Celsius:
Formula: Celsius=(Fahrenheit-32) * 5/9
Problem: Accept Student Name, College Name and Marks in 5 Subject .Find out the Total Marks and
Percentage
#include<stdio.h>
void main() OUTPUT:
{ Input from the user:
int s1, s2, s3, s4, s5, sum, total = 500; Enter the student Name: Rama
float per; Enter the College Name of Student: RJSFGC
char name[20],coll[20]; 45
printf(“\n Enter the student Name”); 65
gets(name); 58
printf(“\n Enter the College Name of Student” 91
gets(coll); 99
printf("\nEnter marks of 5 subjects : "); Output form the program:
scanf("%d %d %d %d %d", &s1, &s2, &s3, &s4, &s5); Name of Student: Rama
sum = s1 + s2 + s3 + s4 + s5; College Name: RJSFGC
per = (sum * 100) / total; Sum:358
printf(“\n Name of Student: “); Percentage: 71
puts(name)
Printf(\n College Name:”);
Puts(coll);
printf("\nSum : %d", sum);
printf("\nPercentage : %f", per);
}
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));

}
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

Using else-if ladder statements. per>=75 Distinction


Solution :- Per>=60 First Class
#include<stdio.h> Per>=50 Second Class
#include<conio.h> Per>=40 Third class
void main() otherwise fail
{
float per;
clrscr() Output:
printf(“Enter The percentage: ");
scanf("%d", &per); Enter the percentage:80
if(per >=75) Distinction
printf(“\n Distinction”);
else if (per>=60)
Output:
printf(“\n First Class”);
else if (per>=50)
Enter the percentage: 65
printf(“\n Second class”); First class
else if(per>=40) Output:
printf(“\n Third class”); Enter the percentage: 30
else Fail
printf(\n Fail ”);

}
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”);

printf(“\n ASCII value of %c is %d”,ch,ch);


getch();
}
C-Programs using if-else to do in Lab on 8-10-22(Saturday)
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(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

Using else-if ladder statements. per>=75 Distinction


Solution :- Per>=60 First Class
#include<stdio.h> Per>=50 Second Class
#include<conio.h> Per>=40 Third class
void main() otherwise fail
{
float per;
clrscr() Output:
printf(“Enter The percentage: ");
scanf("%f", &per); Enter the percentage:80
if(per >=75) Distinction
printf(“\n Distinction”);
else if (per>=60)
Output:
printf(“\n First Class”);
else if (per>=50)
Enter the percentage: 65
printf(“\n Second class”); First class
else if(per>=40) Output:
printf(“\n Third class”); Enter the percentage: 30
else Fail
printf(\n Fail ”);

}
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”);

printf(“\n ASCII value of %c is %d”,ch,ch);


getch();
}
Arrays

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.

Points to remember on Arrays:


1.It is a group of variables of similar data types referred to by a single element.
2.Its elements are stored in a contiguous memory location.
3.The size of the array should be mentioned while declaring it.
4.Array elements are always counted from zero (0) onward.
5.Array elements can be accessed using the position of the element in the array.
6.The array can have one or more dimensions.
V[0] V [1] V [2] V[3] V[4]
Types of Arrays
Single-Dimensional Array:

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

Data-type arrayname[ size ];

➢ Where datatype can be a basic datatype as int, float, char, double


➢ Arrayname is the name of the array
➢ Size is indicates number of elements the array can hole

Example

int marks[5 ];

datatype arrayname size

Note: Integer array holds only integer data;


Int marks[5];
Memory representation of One-dimensional Array:
1.Integer Array: Example:
int Arr[6]; Cahr ch[10]; //Array of charactors
➢ One integer occupies 4 bytes in the memory.
➢ So Each integer occupies contiguous memory location.
Test For you:

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

xarry 5.6 6 I 8.9 A 8 A X


2.Character Array:

Example: char carray[7]; Index of Array Elements

0 1 2 3 4 5 6
carry S R I R A M A

300 301 302 303 304 305 306

Arrayname
Memory Location

➢ One character occupies 1bytes in the memory.


➢ So Each character occupies contiguous memory location.
2. Floating point Array:

Example: float farray[7]; Index of Array Elements

0 1 2 3 4 5 6
farry 3.45 6.7 8.9 9.7 4.1 5.78 8.77

300-3007 308-314 315-322 323-330 331-338 338-345 346-353

Arrayname
Memory Location

➢ One Floating point number occupies 8bytes in the memory.


➢ So Each Floating point occupies contiguous memory location.
Array Initialization:

1.Initializtion an Array with the size and initial values:


➢ Array can be initialize at the declaration time itself followed by “=“ sign and then followed by pair of braces”{ }”.
➢ These braces contains the values separated by commas.
int regno[5] ={10,11,45,23,56};
Five contiguous memory locations will be reserved and the values will initialized as shown below
regno[0] regno[1] regno[2] regno[3] regno[4]

10 11 45 23 56

400 4004 4008 4012 4016

Values will be initializes as follows:


Regno[0]=10
Regno[1]=11
Regno[2]=45
Regno[3]=23
Regno[4]=56
Array Initialization:
2.Initializtion an Array without the size and with initial values:
➢ Array can be initialize at the declaration time itself followed by “=“ sign and then followed by pair of braces”{ }”.
➢ These braces contains the values separated by commas.
int regno[ ] ={10,11,45,23,56};
Size is not specified
➢ Size of the array will be considered as the total number of initial values included in the braces

Five contiguous memory locations will be reserved and the values will initialized as shown below

regno[0] regno[1] regno[2] regno[3] regno[4]

10 11 45 23 56

400 4004 4008 4012 4016


Values will be initializes as follows:
Regno[0]=10
Regno[1]=11
Regno[2]=45
Regno[3]=23
Regno[4]=56
Array Initialization:
3.Partial Array without the size and with initial values:
➢ Partial Array initialize can be done in C.
➢ Number of values initiilzed can be less than the size of the Arry.
int regno[ 5] ={10,23};
Values less than the Size of the Array
➢ Size of the array will be considered as the total number of initial values included in the braces

Five contiguous memory locations will be reserved and the values will initialized as shown below

regno[0] regno[1] regno[2] regno[3] regno[4]

10 23 0 0 0

400 4004 4008 4012 4016


Values will be initializes as follows:
Regno[0]=10
Regno[1]=11
Regno[2]=0 Note:First Two values will be initialized as 10,23 .Remaining will be initialized as zeros
Regno[3]=0
Regno[4]=0
Array Initialization:
4.Run Time initialization using input functions (like scanf())
➢ Array can be initialized at run time using scanf function as

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

400 4004 4008 4012 4016


Values will be assigned at run time as follows:
Regno[0]=10
Regno[1]=23
Regno[2]=56
Regno[3]=55
Regno[4]=89
Accessing the Elements or values of an Array:

➢ Array elements can be access via its Index or subscript.


➢ An index is an integer value specified inside the square brackets.
➢ One dimensional Array always have one subscript
Example 1:
int a[3]={10,30,45};
printf(“%d %d %d”,a[1],a[2],a[3]);

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

for (i = 0; i < n; ++i) Enter a[3]: 4


{ Enter a[4]: 7
printf("Enter element a [ %d ]: ", i );
scanf("%d", &a[i]); Elements of Given Array : a

3 5 9 4 7
}

//code to display the elements from to 1D-Array


printf(“Elements of Given Array : a”);
for (i = 0; i < n; ++i)
{

printf(" %d\t", a[i]);

}
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

for (i = 0; i < n; ++i) Enter a[3]: 4


{ Enter a[4]: 7
printf("Enter element a [ %d ]: ", i );
scanf("%d", &a[i]); Elements of Given Array : a

3 5 9 4 7
}
Sum of all the Elements of Array: 28

//code to display the elements from to 1D-Array


printf(“Elements of Given Array : a”);
for (i = 0; i < n; ++i)
{

printf(" %d\t", a[i]);


sum=sum + a[i]; //code to add elements

}
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:

Enter the number of rows (between 1 and 100):2 *******************

Enter the number of columns (between 1 and 100):2 2 3

Enter elements of 1st matrix: 4 3

Enter element a[0][0]: 2 Enter element a[0][1]: 3 Elements of Second Matrix:

Enter element a[1][0]: 4 Enter element a[1][1]: 2 *********************

Enter elements of 2st matrix: 3 6

Enter element b[0][0]: 3 Enter element b[0][1]: 6 4 1

Enter element b[1][0]: 4 Enter element b[1][1]: 1 Sum of two matrices:

5 9

8 4

Problem5 : Program to subtract Two Matrices using Two-Dimensional Array (Same like above use the symbol

(-) in place of (+) for subtraction.


Problem6: Program for Multiplication of Two Matrix using 2D- Array
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c, i, j, k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//code for printing First Matrix
printf(“\n First Matrix:”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}

//code for printing second Matrix


printf(“\nSecond Matrix:”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t" b[i][j]);
}
printf("\n");
}

//for printing result


printf(“Multi plication of Two Matrix is as follows:”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
Program7: program to accept two string from the user and display it on the
screen.

#include<stdio.h>
#include<conio.h>
void main( )
{
char str1[20], str2[20]; Output:

Enter First String: Rama


//code to accept two strings at run time
Enter Second String: Madhu
puts(“Enter First String”); Given Strings are

gets(str1); First String Entered is: Rama

Second string Entered is: Madhu


puts(“Enter Second String”);
gets(str2);
//Code to display two strings on the screen
printf(“\n Given Strings are”);
puts(“\n First string Entered is:”);
puts(str1);
puts(“\n Second string Entered is:”);
puts(str2);
getch();
}
Problem8: program to find length of a given string(i.e counting number of characters in a given string)
#include<stdio.h>
#include<conio.h>
Output:
void main()
{ Enter a string to calculate the length: Hello How
int i, length=0; are you
char str[50]; The length of a given string is: 17
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+1);
getch();
}
Problem9: Program to display the string character by character
#include<stdio.h>
#include<conio.h>
Output:
void main()
{ Enter a string : Bengaluru
int i;
The characters in a given string is:
cahr str[50];
clrscr(); str[ 0 ]=B
printf(“Enter a string ”); str[ 1 ]=e
gets(str);
printf(“\nThe characters of a given string is”); str[ 2 ]=n
for(i=0;str[i]!=’\0’;i++) str[ 3 ]=g
{
str[ 4 ]=a
printf(“\n str[ %d ] = %c”,i,str[i]);
} str[ 5 ]=l
getch();
str[ 6 ]=u
}
str[ 7 ]=r

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();
}

Program12: program to print ASCII Values of All Alphabets


#include<stdio.h>
#include<conio.h>
void main()
{
char ch1,ch2;
clrscr();
for(ch1=’a’;ch1<=’z’;ch1++)
{
printf(“\n ASCII value of %c is =%d”,ch1,ch1);
}
for(ch2=’A’;ch2<=’Z’;ch2++)
{
printf(“\n ASCII value of %c is =%d”,ch2,ch2);
}
gets();
}
Program12: program to print ASCII Values of All Alphabets (another version)
#include<stdio.h>
#include<conio.h>
void main()
{
char ch1,ch2;
clrscr();
for(ch1=’a’,ch2=’A’; ch1<=’z’; ch1++,ch2++)
{
printf(“ASCII value of %c is =%d \t ASCII value of %c is =%d \n ”,ch1,ch1,ch2,ch2);
}
gets();

}
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.

Sl.No C function aspects Syntax


1 Function definition return_type function_name (argument list) {function body;}
2 Function declaration return_type function_name (argument list);
3 Function call function_name (argument_list)
1.Function Definition:
//function definition
Function Definition has two parts: return_type function_name(parameters(formal parameters)
1. Function Header {
2. Function body Function body
}
1. Function Header: function header is same as function declaration without the semicolon. Function header
contains function name, parameter & return type.
➢ Return Type: Return type is the data type of the value which will be returned by the function. The function
may or may not return a value. If it does then the data type of the retuning value should be specified,
otherwise the return type needs to be void.

➢ 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:

➢ Before using the function should be declared the function


➢ Function declaration tells compiler about the list of arguments the function is expecting with their data types & the
return type of the function.

Syntax of function declaration:

return_type function_name (data_type arg1, data_type arg2);

Example:

int add(int x, int y); //function declaration

There are two types of parameter:


➢ Actual Parameter: Those parameters which are passed to functions while calling them is are known
as actual parameter. For example, 23 & 31 in the example given are the actual parameters.
➢ Formal Parameter: Those parameters which are received by the functions are known as formal
parameters. For example, x & y in the above example are the formal parameters.
#include <stdio.h>
int add(int x, int y); or int add(int , int ); //function declaration
// Main Function
void main()
{
int a,b,z;
Printf(“enter two numbers”);
Scanf(“%d%d”,a,b);
z = add(a,b);
Function call (Actual Parameter )
printf("%d", sum);
}

// 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

Sl.No. Call by value Call by reference

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:

Example: char carray[7]; Index of Array Elements

Terminating Character(NULL Character)


0 1 2 3 4 5 6
carray S R I R A M A \0

300 301 302 303 304 305 306 307

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

Common String operation on string:


1) Finding the length of the string 5) Extracting portion of a string
2) Concatenating two string 6) Converting lowercase to uppercase
3) Copy a string to another String 7) Converting upper case to lowercase
4) Comparing two string 8) Reversing a String

➢ The C standard Library provides a number of built-in functions to handle String.


➢ These built-in functions defined in <string.h> header file.
Sl .No Function Description
1) strlen (string_name) returns the length of string name.
2) strcpy(destination, source) copies the contents of source string to destination string.

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);

Now Destination String contains “SRI RAMA”


//program To copy a String from source string to destination string
#include<stdio.h>
#inlcude<string.h>
void main() Output:
{ Enter a the String:
char sourcestr[20];
char des_str[30]; RJSFG College
puts(“ Enter the String \n”);
gets(sourcestr); The string in the destination is : RJSFG College

strcpy(des_str, sourcestr);

printf(“\n The string in the destination is : %s“,des_str);


}

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);

Now Str1 after APPENDING/CONCATINATION contains “ RAMAKRISHNA”


//program To concatenate two Strings using strcat() function
include<stdio.h>
#inlcude<string.h>
Void main() Output:
{ Enter a the String1: RJSFG
char str1[50], str2[20]; Enter a the String2: College
puts(“\n Enter the string1 \n”);
gets(str1); The concatenated string is : RJSFGCollege
Printf(“Enter string2:”);
gets(str2);

strcat(str1, str2); //strcat(str2, str1);

printf(“\n The string in the destination is : %s“,str1);


}
2.Comparing of two strings using strcmp():
➢ Strcmp() is used to compare two strings whether both the string are equal , greater or less than the first string.
➢ strcmp() returns three values =0 value ,>0 value or <0 value.

Return Value Meaning


<0 Str1 is less than str2(str1 < str2)
>0 Str1 is greater than str2 (str1 > str2)
=0 Str1 is equal to str2 (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

If (i==0) The given two strings are not equal


{
printf(“\n The given two strings are equal”);
else R: 82 G: 71 so 82 – 71 = 11 > 0
printf(“\n The given two strings are not equal”);

}
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.

//program to convert lower to upper using strupr() function


#include<stdio.h>
#inlcude<string.h> Output:
void main() Enter a the String in Lower case: rama
{
char str1[50]; Given string in UPPER CASE : RAMA
clrscr();
printf(“ Enter the String in Lower case\n”);
gets(str1);

printf(“Given string in UPPER CASE : %s”, strupr(str1) );


getch();

}
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.

//program to convert upper to lower using strlwr() function


#include<stdio.h>
#inlcude<string.h>
Output:
void main()
Enter a the String in Upper Case: RAMA
{
char str1[50];
Given string in LOWER CASE : rama
printf(“\n Enter the String in Upper Case\n”);
gets(str1);

printf(“Given string in LOWER CASE : %s”, strlwr(str1) );

}
strrev() function:
➢ The strrev() function is used for reversing a string.
➢ The reversed string will be stored in the same string.

Syntax:
strrev (string)

//program to reverse of a string


#include<stdio.h> Output:
#inlcude<string.h> Enter the String1: madhu
void main()
{ Given string in reverse of a given string :
char str1[50]; uhdam
clrscr();
printf(“ Enter the string in lower case\n”);
gets(str1);

printf(“Given string in UPPER CASE : %s”,strrev(str1) );


getch();

}
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)

For example, char a[10] = “the”;


char b[10] = “there”
strncmp (a,b,2);
Output − Both strings are equal

#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 :

1. Finding Square root of a number using Newton’s Method


2. Finding Smallest Divisor of an integer
3. Greatest common Divisor of Two Integers
4. Computing the Prime factors of an Integers
5. Generation of Pseudorandom Numbers
6. Raising a number to its power(xn n=0,1,2,…..)
Factor: Factor is a number or Algebraic expression that divides another number or expression evenly. That is its
remainder is 0.
Example:
3 ,6 are factors of 12
because 12 ÷ 3=4 exactly => remainder is 0
12 ÷ 6=2 exactly => remainder is 0

The other factors of 12 is 1,2,4,12.


Factorization or Factoring:
➢ Writing a number as a product of smaller numbers.
➢ Decomposition of a number or Mathematical object into smaller or simpler numbers or objects.

7 X 3 = 21
x X X-2 = x2 – 2x

Factors of 21 Factors of X2 – 2x

Factors can be numbers , algebraic expressions or algebraic variables


1. Finding Square root of a number using Newton’s Method
1. Finding Square root of a number using Newton’s Method:
Square root of a number is Given by the Formulas:
1.Root=0.5*(approx. + number/ approx.)
where n is a guess which can be assumed to be m or m/2 or 1
2.approx=number/2 or 0.5 * number
C Program refer in class work
Algorithm:
Step1: Assume Approx (Guess) as half of the given number
Approx=0.5 * number
Step 2: Find the root of the number by
Root=0.5*(Approx + (number/Approx))
Step 3: While root != Approx
3.1 Approx= Root (calculated)
3.2.Recalculate the value of Root
Root=0.5*(approx + (number/approx))
Step 4: Print the square root of the given number
Example: Finding Square root of a number using Newton’s Method:

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:

Numbers Prime Factorization

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.

Pseudo Random Number Generator(PRNG).


➢ It is Software-based Algorithm .
➢ Pseudo Random Number Generator(PRNG) refers to an algorithm that uses mathematical
formulas to produce sequences of random numbers.
➢ PRNGs generate a sequence of numbers approximating the properties of random numbers.
➢ A PRNG starts from an arbitrary starting state using a seed state.
➢ Many numbers are generated in a short time and can also be reproduced later, if the starting
point in the sequence is known.
➢ Hence, the numbers are deterministic and efficient.
Linear Congruential Generator is most common and oldest algorithm for generating pseudo-
randomized numbers.
The generator is defined by the recurrence relation:

Xn+1 = (a Xn + c) mod m

where X is the sequence of pseudo-random values


m => m >0 - modulus
a => 0 < a < m - multiplier
C => 0 ≤ c < m - increment
x0, 0 ≤ x0 < m - the seed or start value

➢ 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.

Here is the syntax of rand() in C language,


int rand(void);

#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>

void main() Output:


{ 5882.79
double x = 6.1, y = 4.8;

double result = pow(x, y);


printf("%.2lf", result);

}
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

What is Hash Function?


➢ Hash function is a mathematical formula which when applied to a key produces an integer which can be
used as index to the hash table. It is denoted by “ H “
➢ The function of converting key into table index is called HASH FUNCTION.
Creating a Hash Table:
➢ At First Hash Table is Empty. Filled with -1 Values

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 calculate the hash key?


Formula:
Hash Key=Key_Element % Hash Table Size H(key)=key % size of hash table
-1
Key=36
-1 H(Key)= Key % 8
H(36)=36 % 8 = 4
……….

-1

-1
-1
Elements to store in Hash Table: 36, 18 , 72 , 43, 6

-1 calculate the hash key?


Formula:
Hash Key=Key_Element % Hash Table Size H(key)=key % size of hash table

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

Hash Key=Key_Element % Hash Table Size

Add the keys 10, 26 19 27

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.

Technique to resolve the Collision:


➢ chaining
➢ linear probe ( linear open addressing)

Hashing with Chaining:


➢ When a collision occurs, elements with the same hash key will be chained together.
➢ A chain is simply a linked list of all the elements with the same hash key.
➢ The hash table slots will no longer hold a table element.
➢ They will now hold the address of a table element.
Technique to resolve the Collision
1.Hashing with Chaining:

Example:

-1
Techniques to avoid Collision:

2.Hashing with Linear Probe :


➢ When using a linear probe, the item will be stored in the next available slot in the table, assuming that the
table is not already full.
➢ This is implemented via a linear search for an empty slot, from the point of collision.
➢ If the physical end of table is reached during the linear search, the search will wrap around to the beginning
of the table and continue from there.
➢ If an empty slot is not found before reaching the point of collision, the table is full.
Linear Probing:
Let hash(x) be the slot index computed using a hash function and S be the table size

➢ If slot hash(x) % S is full, then we try (hash(x) + 1) % S


➢ If (hash(x) + 1) % S is also full, then we try (hash(x) + 2) % S
➢ If (hash(x) + 2) % S is also full, then we try (hash(x) + 3) % S
Searching elements from the hash table
i)search 8

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

Array 12 19 45 55 Size B n=4


B

Array 10 12 14 18 19 20 40 45 50 55 60 70 Size C=Size A + Size B


C=A+B m+n 8+4
Let us see how merge procedure works on the following two arrays A and B
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
C

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

Step 6: Read m elements in the array A in ascending Order a) While ( i < n)


Step 7: Read n elements in the array B in ascending Order C [ k ] =A[ I ]
i =i + 1
Step 8: set i=0,j=0,k=0 k =k + 1
Step 9: while ( i < m and j < n ) b) While ( j < n )
C [ k ] =B[ j ]
compare A[ i ] < B [ j ] then merge smaller member into array C j =j +1
a) if ( A [ I ] < B [ j ] the store A [ I ] in C [ k ] k =k + 1
Step 11: Print the sorted elements of C from C [ 0 ] to C [ m
C [ k ] =A [ i ]
+n]
i=i+1
Step 12: Stop
k=k+1
else b) Store B [ j ] in C [ k ]
C[k]=B[j]
j=j+1
k= k + 1
C program : Simple Merge/Two-Merge

#include <stdio.h> /* Copy remaining Elements of array A into


//Merge function Array C */
void merge( int A [ ],int m,int B [ ],int n,int C [ ] ) while ( i < n)
{ {
int i=0,j=0,k=0; C[ k ] = A[ i ];
/* Compare elements of A and B until either of array reached to i + +;
an end */ k++;
while ( i < m && j < n ) }
{
if ( A [ i ] < B [ j ] ) /* Copy remaining Elements of array B into
{ Array C */
C[ k ] = A[ i ]; while ( i < n)
i + +; {
} C[ k ] = B[ j ];
else j + +;
{ k++;
C[ k ] = B[ j ]; }
j + +; }
}
k++;
}
// Main program
void main() C program : Simple Merge/Two-Merge
{
int m,n, i;
int A[20],B[20],C[40];
printf( “ Enter Size of First Array A : “);
scanf(“%d”,&m);

printf(“Enter the First elements in Ascending Array”);


for ( i = 0; i < n; i ++ )
scanf( “ %d “,&A[ I ] );

printf( “ Enter Size of First Array B : “);


scanf(“ %d “,&n);
printf(“Enter the First elements in Ascending Array”);
for ( i = 0; i < m; i ++ )
scanf( “ %d “,&B[ i ] );

merge(A,n,B,m,C);

printf9”\n After Merging Array A and B into Array C : “);


for ( i = 0; i < m; i ++ )
sprintf( “ %d “,&C[ i ] );
}
Selection Sort:
➢ The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending
order) from the unsorted part and putting it at the beginning.
➢ The algorithm maintains two subarrays in a given array.
➢ The subarray which already sorted.
➢ The remaining subarray was unsorted.
➢ In every iteration of the selection sort, the minimum element (considering ascending order) from the unsorted
subarray is picked and moved to the sorted subarray.

Algorithm for Selection Sort:


Step 1 − Set min to the first location
Step 2 − Search the minimum element in the array
Step 3 – swap the first location with the minimum value in the array
Step 4 – assign the second element as min.
Step 5 − Repeat the process until we get a sorted array.
Selection Sort Program
void main()
{
int array[100], n, c,i, position, t;
printf("Enter number of elements\n");
#include <stdio.h> scanf("%d", &n);
int min(int a[ ],int k, int n) printf("Enter %d integers\n", n);
{ for (c = 0; c < n; c++)
scanf("%d", &array[c]);
int position,j,min;
for (k=0 ; k < n; k++)
min=a[k]; // finding minimum element position
for (j= k + 1; j < n-1; j++) {
{ position = min(array,k,n);
if (min > array[j]) t = array[k];
min=a[ j ]; array[k] = array[position];
position=j array[position] = t;
}
}
printf("Sorted list in ascending order:\n");
return porition; for (i = 0; i < n; i++)
} printf("%d\n", array[i]);

}
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
-----------------------------
-----------------------------
};

struct <struct_name> struct_vat1,struct_var2;

➢ 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
} };

s1.ename s1.eno s1.esal


Naveen 1001 35000.0

s2.ename s2.eno s2.esal


Madhu 1002 36000.0
Accessing members of structure variable:
The members of a structure can be accessed outside the structure by the structure variables using dot ( . )
operator
<structure_name> . <structure_member>

struct emp
{
char ename[20];
int eno;
float esal;
};

e1.name
e1.eno
e1.esal
struct emp
{
char ename[20];
int eno;
float esal;
};

struct emp e1,e2;

e1.sal=40000.00; //assign value to member = esal


e1.eno=1001; //assign value to member = eno
strcpy(e1.ename,”madhu”); //assign value to member = ename

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*/

e1.sal=40000.00; //assign value to member = esal


e1.eno=1001; //assign value to member = eno
strcpy(e1.ename,”madhu”); //assign value to member = ename

/* Accessing the member of the structure */


printf(“employee name of e1 is %s”, e1.name);
printf(“employee eno of e1 is %d”, e1.eno);
printf(“employee esal of e1 is %f”, e1.esal);
Strucutre variables in memory:

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;
}

struct student std1,std2;

std1={“RAMA”,43,’M’};
std2={“BAVAN”,27,’M’}

Naveen 24 M
3001-3010 3011-3014 3015
10bytes 4bytes 1Bytes

Total Size of the Structure =15 Bytes


Union:
➢ A Union can be defined as a User-defined data type which is a collection of different variables of different types in
the same memory location under a single name
➢ Union can have many members ,but only one memory location can contain a value at a particular point in time
Defining Union
The syntax of declaration of define a Union

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,u2,u3 are union variables of type student.


➢ In student union contains three member variables age, gender, percentage but one at a time can used the
memory location.
➢ Memory is allocated as per the largest member of Union.
➢ All Union members will share the common location which is equivalent to the size of largest member
variable.
Assigning values to Union Member variables:

U1.age=10; U1.age=10

U1.age=10 U1.gender=‘M’
U1.gender=‘M’

U1.percentage=78.56 U1.gender=‘M’ U1.percentage=78.5

➢ 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;

}; };

Allocate memory equal to largest


Member variable of Union
Difference between Structure and Union:
Assignment Questions:
1.Define a structure? Explain with example?
2.What is array of structure? Give example.
3.Write the difference between Structure and Union?
4.Write a program to accept and display the values in structure member variables?
5.Write a program to accept and display the values in union member variables?
6.Write the difference ways to declare the structure variables? Give example.
Bangalore University
CA-C4P: Problem Solving Lab using C
1. program to read radius of a circle and to find area and circumference

#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();

2. Program to read three numbers and find biggest of three

# 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();
}

4. C program to read a number, find the sum of the digits


reverse the number and check it for palindrome

# 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;

default : printf("\n Invalid inputs");


}
getch();
}

8. Program to read marks scored by n students and find the average of


marks
// Demonstration of single dimension array
# include<stdio.h>
# include<conio.h>
void main()
{
int n,i;
float marks[10],
tot_marks=0.0,avg_marks=0.0;clrscr();
printf("\n Enter students count(n) : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter mark scored by %d student
: ",i+1);scanf("%f",&marks[i]);
tot_marks=tot_marks + marks[i];
}
avg_marks = tot_marks / n;
printf("\n Total marks = %0.2f",tot_marks);
printf("\n Average marks = %0.2f",avg_marks);
getch();
}

9. C program to remove duplicate element in single dimensional array

# 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);

printf("\n Enter A matrix elements\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("\n Enter a[%d][%d] : ",i,j);
scanf("%d",&a[i][j]);
}
}

printf("\n Enter B matrix elements\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("\n Enter b[%d][%d] : ",i,j);
scanf("%d",&b[i][j]);
}
}

printf("\n Addition of matrices\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
c[i][j] = a[i][j] + b[i][j];
printf("%4d",c[i][j]);
}
printf("\n");
}

printf("\n Subtraction of matrices\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
d[i][j] = a[i][j] - b[i][j];
printf("%4d",d[i][j]);
}
printf("\n");
}

getch();
}

11. Program to find the factorial of a number

# 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();
}

14. program to find length of string without using built-in function

# 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();
}

15. Program to demonstrate string functions


# include<stdio.h>
# include<conio.h>
# include<string.h>

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);

printf("\n Before swapping n1 = %d n2 = %d\n",n1,n2);

ptr1=&n1;
ptr2=&n2;

//swapping
temp=*ptr1;
*ptr1=*ptr2;
*ptr2=temp;

printf("\n After swapping n1 = %d n2 = %d\n",n1,n2);


getch();
}

19. Program to demonstrate student structure to read & display records of n


students
// To demonstrate student structure to read & display records of n students

# 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);
}

printf("\n REGNO \t STUDENT NAME \t GRADE");


for(i=0;i<n;i++)
{
printf("\n %d \t %s \t %c", BCA[i].regno, BCA[i].name, BCA[i].grade);
}

getch();
}

20. Program to demonstrate the difference between structure & union


// To demonstrate student structure to read & display records of n students

# 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

3. Program to check whether the number is prime or not

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

6. Program to read percentage of marks and to display appropriate message


Demonstration of (else-if) ladder

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.

7. Program to find roots of quadratic equation using Switch-Case

Step 1. Input the value of a, b, c.


Step 2. Calculate k = b*b - 4*a*c
Step 3. If (d < 0)
Step 4 :Display "Roots are Imaginary, calculate and print r1 = (-b +i ?k)/ 2a and r2 =(b + i?k)/
2a. switch case 1.
else if (d = 0)
Display "Roots are Equal" and calculate and print r1 = r2 = (-b / 2*a) in switch case 2
else
Display "Roots are real and calculate and print r1 = -b + ?d / 2*a andr2 = -b - ?d / 2*a
in switch case 3
Step 5. End the algorithm.
8.Program to read marks scored by n students and find the average of marks(using
single dimensional array)

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

Instruction: Answer any FOUR questions from each part


PART- A
I. ANSWER ANY 4 QUESTIONS
Each question carries 2 marks 4x2=8

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

7. Explain the structure of C program with suitable programming Example.


8. Write an algorithm and flowchart to find the largest of three numbers.
9. Explain the Different data types supported by C.
10. Write an algorithm to find smallest divisor of an integer.
11. Write a C program to sort n numbers using Insertion sort.
12. Write a note on Text line editing.
PART-C
III. ANSWER ANY 4 QUESTIONS
Each question carries 8 marks 4 x 8 = 32

13. a) Write a ‘C’ Program to find factorial of a number


b) Write a note on Formatted I/O Functions in ‘C’. (4+4)
14. a) Explain Various if statements.
b) Write a ‘C’ program to find whether a given number is prime or not (4+4)
15. a)Explain Switch Case statement in ‘C’ with an Example.
b) Explain Pointer to Pointer. (4+4)
16. a) Write a ‘C’ Program to find the product of two matrices.
b) Explain array with structures. (4+4)
17. a)Write an Algorithm to search an element using Binary search.
b) Write a ‘C’ Program to find GCD of two numbers (4+4)
18. a) Explain text line adjustment with an example
b) Mention the applications of pattern searching. (4+4)

********************* ALL THE BEST *******************


RJS FIRST GRADE COLLEGE
Bangalore University
I Semester BCA Examination (NEP - SCHEME)
Subject: COMPUTER SCIENCE
PAPER: PROBLEM SOLVING TECHNIQUE
MODEL PAPER -2
Time: 2 hours Max. Marks: 60

Instruction: Answer any FOUR questions from each part


PART- A
I. ANSWER ANY 4 QUESTIONS
Each question carries 2 marks 4x2=8
1. What is the role of algorithm in computing?
2. What are formatted input/output statement?
3. How do you initialize a multidimensional array?
4. Define Pointer with an example.
5. What do you mean by keyword searching ?
6. Explain text line adjustment with an example.

PART-B
II. ANSWER ANY 4 QUESTIONS
Each question carries 5 marks 4 x 5 = 20

7. Write an algorithm to generate Fibonacci sequence.


8. Explain different forms of looping statements in C.
9. Differentiate between Call by Value and Call by reference.
10. Write an algorithm to find the maximum number in a set.
11. Write a C program to remove duplicate element in a single dimensional array.
12. Write a note on Pattern searching.
PART-C
III. ANSWER ANY 4 QUESTIONS
Each question carries 8 marks 4 x 8 = 32

13. A) Explain the characteristics of algorithm


B) Explain any three identifiers (5+3)
14. A) Explain unformatted input/output functions
B) Explain type conversions (5+3)
15. A) Explain categories of functions
B) Explain function prototype with an example (5+3)
16. A) Write a program to reverse the array elements
B) Explain pseudo random number generation function (5+3)
17. A) Explain how do you merge two arrays with an example.
B) Explain selection sorting techniques for 38, 47, 24,17 (4+4)
18. A) Explain Hash searching technique
B) Explain text processing (5+3)

**************** ALL THE BEST *************


Illililil lt!!til iltil ilil illtrilt NP - 163
L€
I Semester B.C.A. Degree Examination, May 2022
, t.l,
(NEP - 2021-22 and Onwards) t' Jl
'i:
COMPUTER SCIENCE |',
Paper - 1.2: Problem Solving Techniques

Time : 2/z Hours Max. Marks : 60

lnstruction : Answer any four questions from each Part.


PART _ A

Answer any 4questions. Each question carries 2 marks. (4x2=8)

1. Define Algorithm. r',

2. Define Token with an example.

3. Write any two rules for Identifiers.


4. Define Binary Search.

5. What is sorting ? List any two sorting techniques.


6. What is an array ? Giye the syntax.

PART _ B

Answer any 4 questions. Each question carries 5 marks. (4x5=20)

7. Write an algorithrl'to exchange the values {of two variables.


&t

8. Write a note on break and eontinue with an example.


9. lllustrate the declaration and initihlization of pointers with an example.

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)

13. a) Explain the various Asymptotic Notations with their significance. 6

b) What is pattern searching ? 2

14. a) Explain the structure of a C program. 4


b) Differentiate between if and if else. 4

15. Write a C program to find the roots of the Quadratic Equation. I


16. a) Write a'C' program to demonstrate the following string operations. 4
i) strepy 0 ii) strcat$ iii) Strlen0 iv) strrer0

b) Write a short note on hash search.

17. a) Write a C program to read2 x 2 matrices and perform Addition and


Subtraction opqrations on the matrices. 6
b) What do you mean by two way merge ? 2
':

18. a) Perform the Bubble sort operation on the following elements 29, s,19, 6s, 8
to arrange them in ascending order. 6

b) Write any two application of text line editing. 2

&t'{

You might also like