22CS101 Problem Solving Using C++ Unit I
22CS101 Problem Solving Using C++ Unit I
This document is confidential and intended solely for the educational purpose of RMK
Group of Educational Institutions. If you have received this document through email in
error, please notify the system manager. This document contains proprietary information
and is intended only to the respective group / learning community as intended. If you
are not the addressee you should not disseminate, distribute or copy through e-mail.
Please notify the sender immediately by e-mail if you have received this document by
mistake and delete this document from your system. If you are not the intended
recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.
22CS101
Problem Solving using C++
1 Contents
2 Course Objectives
3 Prerequisites
4 Syllabus
5 Course Outcomes
6 CO-PO Mapping
7 Lecture Plan
9 Lecture Notes
10 Assignments
12 Part-B Questions
16 Assessment Schedule
1.6 Evaluation.
1.7 Overview of C
1.11 Constants
1.12 Operators
1.13 Expressions
1.14 Statements
Pointers -Variables – Operators – Expressions – Pointers and Arrays – Functions - Scope Rules –
Function Arguments – return Statement – Recursion – Structures – Unions – Enumerations.
PO PO PO PO PO PO PO PO PO PO PO PO PS PS PS
COs 1 2 3 4 5 6 7 8 9 10 11 12 O1 O2 O3
CO1 3 3 3 1 1 1 1 1 1 1
CO2 3 3 3 1 3 3 3 1 1 1
CO3 2 2 2 3 3 1 1 1 1 1
CO4 3 3 3 3 3 3 1 1 1 1
CO5 3 3 3 1 1 1 1 1 1 1
7. Lecture Plan - Unit I
S. No. Propose Actual Pertaining Taxonomy Mode of
Topic
No. of d Lecture CO Level Delivery
Perio Date Date
ds
⮚Natural sciences:
❖ computational biology;
❖ genomics;
❖ applied physics;
❖ climate change;
❖ astronomy.
⮚Social Sciences :
❖ population analysis.
❖ Social studies
⮚Medicine :
❖ disease analysis;
❖ medical imaging;
❖ clinical practice.
⮚ linguistics;
⮚ law;
⮚ music;
⮚ teaching.
The following are examples from other sources discussing specific examples of CT in
action.
Flowchart Definition:
Flowchart is a pictorial representation of an algorithm in which the
steps are drawn in the form of different shapes of boxes and the logical flow is
indicated by interconnecting arrows.
Boxes represent operations
❖Arrows represent the sequence in which the operations are implemented It helps
in understanding the logic of the program.
❖It is not necessary to include all the required steps in detail. It outlines the general
procedure.
❖It provides visual representation of the program, So it is valuable.
Guidelines for preparing Flowcharts
❖The flow chart should be clear, neat and easy to follow
❖The flowchart must have logical start and finish
❖In drawing a proper flowchart, all necessary requirements
should be listed in logical order.
❖Only one flow line should come out from a process symbol. Or Only one flow line
should enter a decision symbol. Two or three flow lines may leave the decision
symbol
❖Connector symbols are used to reduce the number of flow lines. Useful in
testing the validity of the flow chart with normal and unusual test data.
❖Assists in finding the key elements of a process by drawing clear flow lines.
Effective Analysis:
❖It helps in analysing the logic of the program by other persons who may or may not
know
programming techniques.
❖It ensures that no steps are missed while coding. Coding can be done faster.
❖Proper testing and Debugging:
❖It helps in detecting errors.
❖Test the logic with normal/unusual data.
Appropriate Documentation:
❖It serves as a good program documentation tool.
❖It helps in knowing what the program does and how to use the program.
❖Efficient Program Maintenance
❖The maintenance of operating program becomes easy with
the help of flowchart.
❖It helps the programmer to put efforts more efficiently on that part.
Limitations
❖Complex
❖It is laborious to draw flow chart for larger programs
❖For large programs it continues to pages making difficult to understand.
❖Difficult to Modify
❖Any changes or modification to a flowchart usually require
redrawing the entire logic again.
❖It is not easy to draw thousands of flow lines and symbols, especially for a large
complex program.
❖No update
❖Usually, programs are updated regularly but corresponding
update of flowcharts may not take place, especially in case of
large programs.
❖As a result, the logic used in the flowchart may not match with the actual program's
logic.
Ex :To find the sum of two numbers Find the biggest of two numbers
Flowchart Symbols
1.3 Building Blocks :
An algorithm can be constructed from any one of the following
basic building blocks. The building blocks of algorithm are listed below:
(i)Sequence
(ii)Selection / decision
(iii)Repetition / Iteration
Instructions / Statements
Instructions are the statements of actions which are to be performed in a
sequential order.
A statement is a unit of code/instruction that has an effect, like creating a
variable or displaying a value.
Selection Decision
Sequence
❖ In sequence construct, statements are executed one by one in the order
from top to bottom.
❖ The actions are performed in the same sequence (top to bottom) in
which they are written.
Flow diagram
Example: Accept two numbers and find their product
Algorithm
step1. Input first number as A
step2. Input second number as B
step3. Set Prod=A*B
step4. Print Prod
step5. Stop
Flowchart
Selection / Decision
Statements are used when the outcome of the0 process depends on some condition.
A condition in this context may evaluate either to a true
or a false value.
The statement will be executed when the condition becomes true. If the
Flow Diagram :
Example: Accept two numbers, Display the first number if greater than the second.
Algorithm
step1. Start
step2. Accept two numbers and store the variables in A and B.
Repetition/Loops
Repetition involves in executing one or more steps for a number of times.
These statements execute one or more steps until some
condition is true.
Flow Diagram
Example: Factorial of a given number (Repetition)
Algorithm
Step 1: Start
Step 2: Get the value of n
Tragedies Comedies
Science
project
1 3 4
This has decomposed the task somewhat, but some sub-tasks may be still too big.
Those tasks should be broken down further by applying the same decomposition
process. For example, the front matter of a dissertation is made up of several parts,
such as:
Typos include:
⮚ spelling errors;
⮚ incorrect capitalizations;
⮚ missing words;
⮚ wrong words (for example, ‘phase’ instead of ‘phrase’);
⮚ numbered lists with incorrect numbering, and so on.
Such mistakes may often be trivial, but any of them could cause problems.
times. It all depends on the parameters passed, as well as other changeable factors in
the environment.
Therefore, algorithms should be exhaustive and contain instructions for
all conceivable outcomes.
If you fail to account for any of them, the computer’s behaviour becomes
unpredictable: it might take an unwanted action or it might do nothing when it should
in fact do something.
MITIGATING ERRORS
Getting defensive
One way to minimise the effects of errors is to anticipate where a problem might
occur and then put some ‘protective barriers’ in place. Computer science calls this
defensive programming.
The approach verifies that certain conditions are as expected before
carrying out the main business of the solution. A failure to meet those conditions
could either indicate anything from a warning to a potential system failure.
Reacting to problems
whether the system is interactive or not (which dictates whether or not
it can ask the user what to do);
whether the system is transactional or not. If it is, then it’s possible to
undo the changes made during a defective step.
Checking user input
Humans may make mistakes, so it’s best to assume that user will enter
faulty input at some point. Think of all the ways an input could be wrong.
(i) Entering ‘9O’ instead of ‘90’ is an easy enough mistake to make.
(ii) Making sure an account number is the expected eight digits in length is quick and
easy. All you have to do is count the number of digits in the input and ensure it’s the
right amount.
(iii) Incorrect formats: phone numbers, website URLs, email addresses, dates and
times are all examples of data that must match a specific format.
TESTING
Testing, a method for locating hidden bugs in a fully or partially working system.
We can choose between two approaches to testing, depending on what you want to
achieve.
The first is top-down testing, where you test the solution as a whole
to ensure that it works. This is most effective at finding design flaws and verifying
that the system hangs together well.
The second approach is bottom-up, which requires you to begin by
testing the smallest parts of the solution individually. This allows you to verify that
they correctly fulfil their own obligations within the whole system and to show that
your solution is built on solid foundations.
Advantages and disadvantages of top-down and bottom-up testing
Advantages Disadvantages
1.6 EVALUATION
You did it. You analysed the problem, broke it down into pieces, came up
with a solution design, which you then implemented, tested and debugged. You have
something that functions. So, you’re finished, right?
Well, not quite.
The work is not over just because you have a solution. Before you can
really finish, you have to make sure you’ve produced a good solution. You must
evaluate its quality.
There are many aspects to quality. Evaluating a solution involves asking several
basic questions, each addressing a specific aspect.
Important questions about the solution include:
• Is it correct? Does it actually solve the problem you set out to solve?
• Is it efficient? Does it use resources reasonably?
• Is it elegant? Is it simple yet effective?
• Is it usable? Does it provide a satisfactory way for the target audience to use it?
Is it Correct :
components that meas- ure how easy and satisfying it is for people to use a
solution. Despite involving humans in the equation, these components are
somewhat measurable. They are:
⮚ Learnability: how easy is it for users to accomplish basic tasks
the first time they encounter the solution?
⮚ Efficiency: once users have learned the solution, how quickly
can they perform tasks?
⮚ Memorability: when users return to the solution after a
period of not using it, how easily can they re-establish
proficiency?
⮚ Errors: how many errors do users make, how severe are these
errors and how easily can they recover from the errors?
⮚ Satisfaction: how pleasant is it to use the design?
1.7 Overview of C
History of C
⮚ The root of all modern languages is ALGOL, introduced in 1960. ALGOL was the
first computer language to use a block structure.
⮚ C was evolved from ALGOL, BCPL and B by Dennis Ritchie at Bell Laboratories in
1972 and it was known as “traditional C”.
⮚ The language became more popular after publication of the book ‘The C
Programming Language’ by Brian Kerningham and Dennis Ritchie in 1978. The
language came to know as “K&R C”.
Structure of a C Program :
Documentation section
Header Section
Definition section
Declaration part
........................................
Executable part
.........................................
}
Subprogram section
Executable part
⮚ This part contains a set of statements or a single statement.
⮚ These statements are enclosed between the braces ({}).
⮚ All the statements in the program end with a semicolon.
User- Defined function
⮚ The functions defined by the user are called user-defined functions.
⮚ These functions are generally defined after the main() function.
⮚ They can also be defined before main() function. This portion is not compulsory.
Programming Rules
⮚ All statements should be written in lower case letters. Upper case letters
are only used for symbolic constants.
⮚ Blank spaces may be inserted between the words.
⮚ The program statements can written anywhere between the two braces
following the declaration part.
⮚ The opening and closing braces should be balanced. eg., if opening braces are
four, then closing braces should be four.
Sample C Program
#include<stdio.
h > void main()
{
printf(“HELLO”);
}
Character Set
A character denotes any alphabet, digits, white spaces or special symbol used to
represent information.
Letters A to Z and a to z
Digits 0 to 9
White spaces Blank space, Horizontal tabs,
vertical tab, New line, Form
feed.
Special character , comma
& Ampersand
. period or dot
^ caret
; semicolon
* Asterisk
: colon
- minus
“ quotation mark
+ plus etc.,
Tokens, Keywords
C Tokens:
⮚ The C Language program can contain the individual units called the C tokens.
⮚ The tokens are usually referred as individual text and punctuation in the text.
C Tokens are,
⮚ Keyword
⮚ Identifier
⮚ Constants
⮚ Operators
Keyword:
Identifiers
An "Identifiers" or "symbols" are the names you supply for variables,
types, functions, and labels in your program. Identifier names must differ in spelling
and case from any keywords. You cannot use keywords (either C or Microsoft) as
identifiers; they are reserved for special use.
Rules
➢ A variable name can be any combination of alphabets, digits and underscore.
➢ Identifier should not start with a digit.
➢ The first character must be an alphabet or an underscore ( _ ).
➢ No commas or blank space are allowed within a Identifier name.
➢ No special symbol can be used in a identifier.
1.8 Data Types :
Data types are fundamental building blocks in computer programming and data
manipulation. They define the kind of values that variables or data structures can
hold and specify the operations that can be performed on those values. In essence,
data types categorize data into distinct groups based on their characteristics, such
as numeric, text, boolean, or more complex structures like arrays and objects.
These distinctions are crucial because they determine how data is stored in
memory, how it can be processed, and the constraints applied to it. Data types play
a critical role in ensuring the integrity and efficiency of computer programs, as they
dictate how data can be used and manipulated within the code, thus enabling
programmers to work with data in a structured and meaningful way.
Variable initializing
∙ Initialization of variable can be done using the assignment operator( =).
∙ The variable can be initialized when it is declared.
Syntax: variableName=constant or data_type variable Name=constant;
Example: int a ; a=2; int b=10;
Storage classes in C
#include<stdio.h>
int main()
{
int fun();
fun();
fun();
fun();
return 0;
}
int fun()
{
auto int a=13;
a++;
printf("\n The value of a Is : %d",a);
return 0;
}
Output
register Storage Class:
➢ Variables declared with the register storage class are stored in CPU
registers for faster access.
➢ They are used for frequently accessed variables.
Example:
#include <stdio.h>
int main()
{
// works (inside a block)
register int i = 10;
int x=160;
printf("%d\n", i);
printf("%d", x);
return 0;
}
➢ The register storage class in C is used to suggest to the compiler that a variable
should be stored in a CPU register for faster access. While the use of the
register keyword is a hint to the compiler and doesn't guarantee that a variable
will be placed in a register (modern compilers are highly optimized and make
their own decisions), there are advantages to using register storage when
appropriate:
➢ Faster Access: Variables stored in CPU registers can be accessed much faster
than those stored in memory. This is because registers are part of the CPU, and
accessing them doesn't involve the latency associated with fetching data from
RAM.
1. Reduced Memory Access: Accessing data from registers eliminates the need to
read from or write to memory, which can significantly improve program
performance, especially in tight loops or frequently used variables.
2. Optimized Code: Using register can lead to more optimized code generated by
the compiler. It may choose to perform certain operations using the register
variables more efficiently than if they were stored in memory.
3. Critical Variables: register is typically used for critical variables that are accessed
frequently within a small scope, such as loop counters or frequently used
pointers. By hinting to the compiler that these variables should be in registers,
you can potentially speed up critical sections of code.
static Storage Class
Variables declared with the static storage class have a lifetime throughout the
program execution.
They retain their values between function calls and persist in memory.
Example
include<stdio.h>
static int t=90;
int main()
{
int fun();
fun();
fun();
fun();
printf("\n I am Static from the main function: %d",t);
return 0;
}
int fun()
{
auto int a=13;
a++;
printf("\n The value of a Is : %d",a);
printf("\n I am Static from userdefined function: %d",t);
return 0;
}
Output
➢ The extern storage class is used to declare variables that are defined in
other source files.
➢ It provides visibility to variables declared in other files.
Example
#include<stdio.h>
int main()
{
//extern int first,last;
extern int first,last;
printf("\n This is Extern Test %d %d:",last,first);
return 0;
}
int first=88,last=77;
⮚ Escape sequence characters like \n, \t etc, can be used in printf() function.
%d integer
%c Character
%f float
%lf Double
%s string
+ Addition A+B
- Subtraction A–B
* Multiplication A*B
/ Division A/B
% Modulus A%B
/* Example */
#include<stdio.h>
void main()
{
int a = 10, b=3;
printf("a + b = ", (a + b) );
printf("a - b = ",(a - b) );
printf("a * b = ",(a * b) );
printf("a / b = ",(a / b) );
printf("a % b = ",(a % b) );
}
Output:
a + b = 13 a - b = 7
a * b = 30 a / b = 3 a
a% b = 1
2. Unary Operators
The following are the unary operators
void main()
{
int a = 10, b=3;
printf("a++ = ", (a ++));
}
printf("a - - = " , (a - -) );
}
Output:
a++ = 11
b-- = 2
3. Relational Operators
Relational operators are used to test condition and results true or false value, The
following table lists relational operators
Operator Description Exampl
e
Two values are checked, and if equal, then the
== (A == B)
condition becomes true
Two values are checked to determine whether
!= they are equal or not, and if not equal, then (A != B)
the condition becomes true
Two values are checked and if the value on the
> left is greater than the value on the right, then (A > B)
the condition becomes true.
Two values are checked and if the value on the
< left is less than the value on the right, then the (A < B)
condition becomes true
Two values are checked and if the value on the
>= left is greater than equal to the value on the
(A >= B)
right, then the condition becomes true
Two values are checked and if the value on the
<= left is less than equal to the value on the right, (A <= B)
then the condition becomes true
4. Logical Operators
⮚ Operators which are used to combine two or more relational operators are called as
logical operators.
⮚ These operators are used to test more than one condition at a time.
! Logical NOT
Truth Table
A B A&& A|| !A
B B
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
Example:
A B Expression Result
10 5 !A || (A= = B) 0 (false)
=, assigns right hand side value to left hand side variable. Eg. int a; a=10;
Compound Assignment
+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=, assigns right hand side value after the
computation to left hand side variable
Example:
int a; int b;
a += 10; // means a = a + 10;
a &= b; // means a = a & b;
7. Bitwise Operators
Bitwise operator act on integral operands and perform binary operations. The lists of
bitwise operators are
Bitwise AND &
Bitwise OR |
Bitwise EXOR ^
Bitwise NOT ~ (unary
operator)
Shift Left <<
Shift Right >>
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
➢ An expression is a combination of constants, variables and operators.
➢ Consider the expression, a + b * c, has higher precedence.
➢ Hence (b*c) will be evaluated first. This result will then be added to a.
➢ In order to override the precedence, parentheses can be used.
➢ Associativity refers to the order in which the operators with the same
precedence are evaluated in expression.
1.14 Statements
An expression such as x=0 or i++ or printf(…) becomes a statement when it is
followed by semicolon.
Example
x=10;
i++;
printf(…..);
Braces { and } are used to group declarations and statements or block, so that
they are syntactically equivalent to a single statement.
Example
Statement blocks
if( i == j)
{
printf(“C Programming \n");
}
The decision making statement checks the given condition and then executes its sub
block.
The decision statement decides the statement to be executed after the success or failure
of a given condition.
Decision making statements are classified into (i) if statements (ii)switch statement
If Statements :
Simple if statement
The if statement evaluates the test expression inside the parenthesis().If the test
expression is evaluated to true , statements inside the body of if are executed. If the
test expression is evaluated to false, statements inside the body of if are not executed.
syntax :
if(Boolean
expression)
{
statement–block;
}
Next statement;
//Example program
#include<stdio.h>
void main()
{
int n=5;
if(n<25)
{
printf(“This is if statement”);
}
}
if .. else statement
If the test condition is evaluated to true, statements inside the body of if are
executed.
If the test condition is evaluated to false, statements inside the body of else
are executed.
Syntax
if(boolean expression)
{
True-block statements;
}
else
{
False-block statements;
}
Next statement;
Example program for if-else statement
#include<stdio.h>
void main()
{
int age;
printf(“Enter the age”);
scanf(%d”,&age);
if(age>18)
{
printf(“Eligible to vote”);
}
else
{
printf(“Not eligible to vote”);
}
}
Nested if.. else
In if-else statement, else block is executed by default after failure of
condition, in order to execute the else block depending upon certain
condition, if statement is repetitively added in else block. It is termed as
Nested if-else statement.
A nested if-else can be chained with one another.
Syntax
if( condition )
if(condition) statement;
else statement;
if( condition )
statement;
else
if(condition)
statement;
//program to find largest three number
#include<stdio.h>
void main()
{
int n1,n2,n3;
printf(“Enter the number”);
scanf(“%d%d%d”,&n1,&n2,&n3);
if(n1>n2 && n1>n3)
{
printf(“%d is largest number”,n1);
}
else
{
If(n2>n3)
printf(“%d is the largest
number”,n2);
else
printf(“%d is the largest
number”,n3);
}
}
else if ladder:
When a series of many conditions have to be checked use the else if ladder
statement, which takes the following general form.
if (condition1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
else if (condition)
statement n;
else
default statement;
statement x;
Example:
#include<stdio.h>
void main()
{
int m1;
printf(“enter the m1:);
scanf(“%d”,&m1);
if(m1<50)
printf(“m1 is fail mark”);
else if(m1>50 &&m1<60)
printf(“m1 is average mark);
else if(m1>60 && m1<75)
printf(“m1 is firstclass mark”);
else
printf(“m1 is high mark”);
}
Switch Statement
⮚ It is a multi-way branch statement.
⮚ It requires only one argument of any data type, which is checked with
number of case option.
⮚ switch() statement evaluates expression and then for values among the
case constants.
⮚ If the value matches with case constant, the particular case statement is
executed, if not default is executed.
⮚ switch, case and default are reserved keywords.
⮚ Every case statement terminates with ':'.
⮚ The break statement is used to exit from the current case structure.
Syntax:
switch (expression)
{
case value-1;
block-1;
break;
case value-2;
block-2;
break;
default:
default-block;
} Statement- x
⮚ The expression is an integer expression or character.
⮚ value-1, value-2 is constants or constant expressions and is known as case
labels.
⮚ These values should be unique within a switch statement.
⮚ block-1, block-2… are statement lists.
When the switch is executed, the value of the expression is successively compared
against the values value-1, value-2…
If a case is found, whose value matches with the value of the expression, and then
the block of statements that follows the case is executed.
The break statement, transfers the control to the statement-x following the switch.
Default is an optional case.
example of a switch case statement
#include<stdio.h>
void main()
{
int w;
scanf(“%d”,&w);
switch(w)
{
case 1: printf(“Sunday”);
break;
case 2:
printf(“Monday”);
break;
case 3:
printf(“Tuesday”);
break;
case 4:
printf(“Wednesday”);
break;
case 5: printf(“Thursday”);
break;
case 6: printf(“Friday”);
break;
} }
Looping Statements
Syntax
do
{
body of the loop
}
while(Boolean expression);
/* This is an example of a do-while loop */
#include<stdio.h>
void main()
{
int i=5;
do
{
printf("i:%d”,i);
i = i + 1;
}
while (i < 5);
}
for Loop
The for loop initialize the value before the first step. Then checking the
condition against the current value of variable and execute the loop statement
and then perform the step taken for each execution of loop body. For-loops are
also typically used when the number of iterations is known before entering the
loop.
Syntax
for(initialization;condition; increment/decrement)
{
Body of the loop
}
/* This is an example of a for loop */
#include<stdio.h>
void main()
{
int i;
for(i=0;i<=5;i++)
{
printf(“i:%d\n”,i);
}
}
Output:
i: 1
i: 2
i: 3
i: 4
i: 5
Break statement
A break statement terminates the loop, and the control then automatically passes
to the first statement after the loop.
Break can be associated with all conditional statements.
Syntax
break;
Program to demonstrate the working of break statement in C
programming
main( )
{
int i;
for(i=1;i<10;i++)
{
if (i==5)
{
break; // breaks out of the for loop
}
printf(“ Value of i = %d\n”’ ,i);
}
}
Output
Value of i = 1
Value of i =2
Value of i =3
Value of i = 4
for(i=1;i<10;i++)
{
if (i% 4==0)
{
continue; // when i is divisible by 4 continue to next iteration
}
printf(“ %d\n”’ ,i);
}
}
goto Statement:
Syntax:
goto Label;
-
-
Label: Statement;
//Example:
main()
{
int age;
Vote:
printf("you are eligible for voting");
NoVote:
printf("you are not eligible to vote");
26 89 15 39 57
2D array – We can have multidimensional arrays like 2D and 3D array. However the
most popular and frequently used array is 2D – two dimensional array. We will see
how to declare, read and write data in 2D array along with various other features of
it.
Initialization of 2D Array
There are two ways to initialize a two Dimensional arrays during declaration.
int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
Although both the above declarations are valid, the first method is more readable,
because you can visualize the rows and columns of 2d array in this method.
We know that, when we initialize a normal array (one dimensional array) during
declaration, we need not to specify the size of it. However that’s not the case with 2D
array, you must always specify the second dimension even if you are specifying
elements during the declaration.
Example:
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
123
456
No of elements in a 2D Array
We can calculate how many elements a two dimensional array can have by using
this formula:
The array arr[n1][n2] can have n1*n2 elements.
The array that we have in the example below is having the dimensions 5 and 4.
These dimensions are known as subscripts. So this array has first subscript value as
5 and second subscript value as 4. So the array abc[5][4] can have 5*4 = 20
elements.
• Matrix Operations (Addition, Subtraction)
Matrix addition in C language to add two matrices, i.e., compute their sum and
print it. A user inputs their orders (number of rows and columns) and the
matrices. For example, if the order is 2, 2, i.e., two rows and two columns and
The matrices are:
First matrix:
1 2
3 4
Second matrix:
4 5
-1 5
The output is:
5 7
2 9
Matrix Addition Program:
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
} printf("\n");
}
return 0; }
Linear Search
Linear search is a very simple and basic search algorithm. Here we
will implement a program that finds the position of an element in an array using
a Linear Search Algorithm.
What is a Linear Search?
A linear search, also known as a sequential search, is a method of finding an
element within a list. It checks each element of the list sequentially until a match
is found or the whole list has been searched.
A simple approach to implement a linear search is
•Begin with the leftmost element of arr[] and one by one compare x with each
element.
•If x matches with an element then return the index.
•If x does not match with any of the elements then return -1.
Implementing Linear Search in C
#include<stdio.h>
int main()
{
int a[20],i,x,n;
printf("How many elements?");
scanf("%d",&n);
printf("Enter array elements:n");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
printf("nEnter element to search:");
scanf("%d",&x);
for(i=0;i<n;++i)
if(a[i]==x)
break;
if(i<n)
printf("Element found at index %d",i);
else
printf("Element not found");
return 0;
}
Output:
How many elements ? 5
Enter Array Elements : 77 45 16 33 26
Enter Element to search : 16
Element found at index 2
The time required to search an element using a linear search algorithm depends on
the size of the list. In the best-case scenario, the element is present at the
beginning of the list and in the worst-case, it is present at the end.
The time complexity of a linear search is O(n).
Binary Search
Search a sorted array by repeatedly dividing the search interval in half. Begin with
an interval covering the whole array. If the value of the search key is less than the
item in the middle of the interval, narrow the interval to the lower half. Otherwise
narrow it to the upper half. Repeatedly check until the value is found or the interval
is empty.
Example:
The idea of binary search is to use the information that the array is
sorted and reduce the time complexity to O(Log n).
String – Character Array – There is no separate data type for strings in C. The character
array is considered as a String.
String is a sequence of characters that is treated as a single data item and terminated by
null character '\0'. Remember that C language does not support strings as a data type.
A string is actually one-dimensional array of characters in C language. These are often used
to create meaningful and readable programs.
Example: The string "hello world" contains 12 characters including '\0' character which is
automatically added by the compiler at the end of the string.
Declaring and Initializing a string variables
There are different ways to initialize a character array variable.
char name[16]=”Students like C”;
char sname[6]={‘A’,’s’,’h’,’o’,’k’,’\0’};
Remember that when you initialize a character array by listing all of its characters separately
then you must supply the '\0' character explicitly.
Some examples of illegal initialization of character array are,
char s1[3]=”hello”; // Illegal
char s2[5];
s2=”hello”; // Illegal
String Input and Output
Input function scanf() can be used with %s format specifier to read a string input
from the terminal. But there is one problem with scanf() function, it terminates its
input on the first white space it encounters. Therefore if you try to read an input
string "Hello World" using scanf() function, it will only read Hello and terminate after
encountering white spaces.
#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str); //scanning the whole string, including the white spaces
printf("%s", str);
}
Another method to read character string with white spaces from terminal is by using
the gets() function.
char text[20];
gets(text);
printf("%s", text);
• A string is a null-terminated character array. This means that after the last
character, a null character (‘\0’) is stored to signify the end of the character array.
• For example:
char c[] = "c string"; When the compiler encounters a sequence of characters
enclosed in the double quotation marks, it appends a null character \0 at the end
by default.
We can also declare a string with size much larger than the number of
elements that are initialized.
For example, consider the statement below.
char str [10] = "HELLO";
In such cases, the compiler creates an array of size 10; stores "HELLO" in it
and finally terminates the string with a null character. Rest of the elements in
the array are automatically initialized to NULL.
Now consider the following statements:
char str[3]; str = "HELLO";
The above initialization statement is illegal in C and would generate a compile-
time error because of two reasons. First, the array is initialized with more
elements than it can store. Second, initialization cannot be separated from
declaration.
Note: When allocating memory space for a string, reserve space to hold
the null character also.
Let us try to print above mentioned string:
#include <stdio.h>
#include <conio.h>
int main()
{
char str[10]={'H',’E',‘L',‘L',‘O','\0'};
printf("Greeting string message : %s", str);
return 0;
}
Output :
Greeting string message : HELLO
Note: %s is used to print the string in C
WRITING STRINGS
printf("%s", str);
String functions
1) strlen( ) Function : strlen( ) function is used to find the length of a character
string.
Example: int n;
char st[20] = “Bangalore”;
n = strlen(st);
• This will return the length of the string 9 which is assigned to an integer variable
n.
• Note that the null character “\0‟ available at the end of a string is not counted.
2) strcpy( ) Function : strcpy( ) function copies contents of one string into another
string. Syntax for strcpy function is given below.
Syntax: char * strcpy (char * destination, const char * source);
Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
If destination string length is less than source string, entire source string value won’t
be copied into destination string.
For example, consider destination string length is 20 and source string length is 30.
Then, only 20 characters from source string will be copied into destination string and
remaining 10 characters won’t be copied and will be truncated.
Example: char city[15];
strcpy(city, “BANGALORE”) ;
This will assign the string “BANGALORE” to the character variable city.
3) strcat( ) Function : strcat( ) function in C language concatenates two given
strings. It concatenates source string at the end of destination string. Syntax for
strcat( ) function is given below.
Syntax: char * strcat ( char * destination, const char * source );
Example:
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.
• As you know, each string in C is ended up with null character (‘\0′).
• In strcat( ) operation, null character of destination string is overwritten by source
string’s first character and null character is added at the end of new destination
string which is created after strcat( ) operation.
Program: The following program is an example of strcat() function
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = “ ftl” ;
char target[ ]= “ welcome to” ;
printf (“\n Source string = %s”, source ) ;
printf ( “\n Target string = %s”, target ) ;
strcat ( target, source ) ;
printf ( “\n Target string after strcat( ) = %s”, target ) ;
}
Output:
Source string = ftl
Target string = welcome to
Target string after strcat() = welcome to ftl
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] =”" ftl” ;
char target[ ]= “welcome to” ;
printf ( “\n Source string = %s”, source ) ;
printf ( “\n Target string = %s”, target ) ;
strncat ( target, source, 3 ) ;
printf ( "”\n Target string after strncat( ) = %s”, target ) ;
}
Output :
Source string = ftl
Target string = welcome to
Target string after strncat()= welcome to ft
strcmp( ) Function : strcmp( ) function in C compares two given strings and returns
zero if they are same. If length of string1 < string2, it returns < 0 value. If length
of string1 > string2, it returns > 0 value.
Syntax: int strcmp ( const char * str1, const char * str2 );
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different
characters.
Example:
char city[20] = “Madras”;
char town[20] = “Mangalore”;
strcmp(city, town);
This will return an integer value “-10‟ which is the difference in the ASCII values of
the first mismatching letters “D‟ and “N‟.
* Note that the integer value obtained as the difference may be assigned to an
integer variable as follows:
int n;
n = strcmp(city, town);
6) strcmpi() function :
strcmpi( ) function in C is same as strcmp() function. But, strcmpi( ) function is
not case sensitive. i.e., “A” and “a” are treated as same characters. Whereas,
strcmp() function treats “A” and “a” as different characters.
• strcmpi() function is non standard function which may not available in standard
library.
• Both functions compare two given strings and returns zero if they are same.
• If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it
returns > 0 value.
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different
characters.
Syntax: int strcmpi ( const char * str1, const char * str2 );
Example:
m=strcmpi(“ DELHI ”, “ delhi ”); m = 0.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = “MODIFY This String To Lower”;
printf(“%s\n”, strlwr (str));
return 0;
}
Output:
modify this string to lower
8) strupr() function : strupr() function converts a given string into
uppercase.
Syntax : char *strupr(char *string);
strupr() function is non standard function which may not available in standard library
in C.
Program : In this program, string ”Modify This String To Upper” is converted into
uppercase using strupr( ) function and result is displayed as “MODIFY THIS
STRING TO UPPER”.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = “Modify This String To Upper”;
printf(“%s\n”, strupr(str));
return 0;
}
Output:
MODIFY THIS STRING TO UPPER
9) strrev() function : strrev() function reverses a given string in C
language.
Syntax: char *strrev(char *string);
strrev() function is non standard function which may not available in standard library
in C.
Example:
char name[20]=”ftl”; then
strrev(name)= ltf
Program:
In below program, string “Hello” is reversed using strrev( ) function and output is
displayed as “olleH”.
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = “Hello”;
printf(“String before strrev( ) : %s\n”, name);
printf(“String after strrev( ) : %s”, strrev(name));
return 0;
}
Output:
String before strrev( ) : Hello
String after strrev( ) : olleH
10) strchr() function : strchr() function returns pointer to the first
occurrence of the character in a given string.
Syntax: char *strchr(const char *str, int character);
Program:
In this program, strchr( ) function is used to locate first occurrence of the character
‘i’ in the string ”This is a string ”. Character ‘i’ is located at position 3 and pointer
is returned at first occurrence of the character ‘i’.
#include <stdio.h>
#include <string.h>
int main ()
{
char string[25] =”This is a string “;
char *p;
p = strchr (string,'i');
printf (“Character i is found at position %d\n”,p-string+1);
printf (“First occurrence of character \”i\” in \”%s\” is” \” \”%s\””,string, p);
return 0;
}
Output:
Character i is found at position 3
First occurrence of character “i” in “This is a string” is “is is a string”
11) strstr() function : strstr( ) function returns pointer to the first
occurrence of the string in a given string.
Syntax: char *strstr(const char *str1, const char *str2);
Program: In this program, strstr( ) function is used to locate first occurrence of the
string “test” in the string ”This is a test string for testing”. Pointer is returned at
first occurrence of the string “test”.
#include <stdio.h>
#include <string.h>
int main( )
{
char string[55] =”This is a test string for testing”;
char *p;
p = strstr (string, ”test”);
if(p)
{
printf(“string found\n” );
printf (“First occurrence of string \”test\” in \”%s\” is”\” \”%s\””,string, p);
}
else
printf(“string not found\n” );
return 0;
}
Output:
String found
First occurrence of ”test” in “this is a test string for testing” is “testing string for
testing”
14) atof() function : converts a floating point text format value to double
value.
These functions take three arguments, the numeric value, target string address in
which the value to be stored and radix value. Finally returns the target string
address, so that function-call can be used as argument/expression.
Syntax: char* itoa(int value, char *targetstringaddress, int radix );
Example:
Char temp[50];
Printf(“output=%s”, itoa(45,temp,2));
Output : 101101
Program: Write a C program to count the number of vowels present in a sentence.
# include<stdio.h>
# include<conio.h>
# include<string.h>
main( )
{
char st[80], ch;
int count = 0, i;
clrscr( );
printf(“ \n Enter the sentence: \n”);
gets(st);
for( i=0; i<strlen(st); i++)
switch(st [i ])
{
case ‘A’:
case ‘E’:
case ‘I’:
case ‘O’:
case ‘U’:
case ‘a’:
case ‘e’:
case ‘I’:
case ‘o’:
case ‘u’:
count ++;
break;
}
printf(“\n %d vowels are present in the sentence”, count);
getch( );
}
• When this program is executed, the user has to enter the sentence.
• Note that gets( ) function is used to read the sentence because the string has
white spaces between the words.
• Note that a count++ statement is given only once to execute it for the cases in
the switch statement.
Output:
Enter the sentence:
This is a book
5 vowels are present in the sentence.
# include<stdio.h>
# include<string.h>
# include<conio.h>
main()
i=0;
i--;
st[ i ] = ‘\0’;
i=0;
while(txt[ i ]!=’$’)
{
switch(txt[ i ])
{
case ‘,’:
case ‘!’:
case ‘\t’:
case ‘ ‘:
{
wds ++;
chs ++;
break;
}
case ‘?’:
case ‘.’:
{
wds ++;
chs ++;
break;
}
default:
chs ++;
break;
}
i++;
}
printf(“\n\n no of char (incl.blanks) = %d”, chs);
printf(“\n No. of words = %d”, wds);
printf(“\n No of lines = %d”, ins);
getch() ;
}
Output:
∙ Be precise
∙ Be unambiguous
∙ Not even a single instruction must be repeated infinitely.
∙ After the algorithm gets terminated, the desired result must be obtained.
3. What are the qualities of an algorithm? (CO1)(K2)
The following are the primary factors that are used to judge the quality of an algorithm,
∙ Time
∙ Memory
∙ Accuracy
∙ Sequence
4. List out the ways to represent an algorithm. (CO1)(K2)
∙ Flowchart
∙ Pseudocode
∙ Programming languages
5. What are the various control flow structures in an algorithm? (CO1)(K2)
∙ Sequence
∙ Selection
∙ Repetition
6.What is sequence control flow? (CO1)(K2)
In sequence construct, statements are executed one by one in the order from top to
bottom.
7.What is selection control flow? (CO1)(K2)
∙ Statements are used when the outcome of the process depends on some condition.
∙ A condition in this context may evaluate either to a true or false value.
8.What is repetition? (CO1)(K2)
∙ It is used to execute a block of code or a part of the program several times.
∙ In other words, it iterates a code or group of code many times.
9.Write the guidelines for preparing flowcharts. (CO1)(K2)
Looping is a sequence of instructions that is continually repeated until a certain condition is reached.
Step1: Start
Step2: Read the two numbers as a and b
Step3: set c=a Step4: set a=b Step5: set b=c Step6: print a, b Step7: Stop
End if
Step4: Stop
Step 1: START
Step 5: STOP
C=5
31.List out the Operators in C? (CO1)(K2)
Arithmetic Operators
Relational operators
Assignment Operators
Logical operators
Bitwise Operators
Conditional or Ternary Operators
Increment and Decrement operators
Special operators
32. Write Syntax of the Conditional operators with example. (CO1)(K2)
Syntax :exp1 ? exp2
:exp3; Example x =
(a>b) ? a : b
Work : exp1 is evaluated first .if it is true , then the expression exp2 is evaluated and
becomes the value of the expression. If exp1 is false, exp3 is evaluated.
33. Evaluate the following Expressions.
i) 4+8/2*7+4
=4+4*7+4
=4+28+4
=32+4
=36
ii) 4%3*5/2+(5*5)
=4%3*5/2+25
=1*5/2+25
=5/2+25
=2.5+25
=27.5
34. Define formatted input and output functions? (CO1)(K2)
• scanf( )
Example: scanf(“%d”,&a);
∙ printf( )
❖ C – Sololearn
❖ https://swayam.gov.in/
❖ https://www.coursera.org/
❖ https://www.udemy.com/
❖ https://unacademy.com/
❖ https://www.sololearn.com/
❖ https://www.tutorialspoint.com/cprogramming/index.htm
❖ https://www.w3schools.in/c-tutorial/
❖ https://www.geeksforgeeks.org/c-language-set-1-introduction/
❖ https://www.programiz.com/c-programming
14. Real Time Applications
15. Content beyond syllabus
Preprocessors Directives:
The C Preprocessor is not a part of the compiler, but is a separate
step in the compilation process. In simple terms, a C Preprocessor is just a text
substitution tool and it instructs the compiler to do require pre-processing before
the actual compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first
nonblank character, and for readability, a preprocessor directive should begin in
the first column. The following section lists down all the important preprocessor
directives.
Preprocessors Examples
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use
#define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to
the current source file. The next line tells CPP to get myheader.h from the local
directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
It tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if
you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will
define DEBUG, so you can turn debugging on and off on the fly during compilation.
irectiveescription
S.No. Directive & Description
#define
1
Substitutes a preprocessor macro.
#include
2
Inserts a particular header from another file.
#undef
3
Undefines a preprocessor macro.
#ifdef
4
Returns true if this macro is defined.
#ifndef
5
Returns true if this macro is not defined.
#if
6
Tests if a compile time condition is true.
#else
7
The alternative for #if.
#elif
8
#else and #if in one statement.
#endif
9
Ends preprocessor conditional.
#error
10
Prints error message on stderr.
#pragma
11 Issues special commands to the compiler, using a
standardized method.
16. Assessment Schedule
Name of the
S.NO Start Date End Date Portion
Assessment
Text Books:
1. Herbert Schildt, “The Complete Reference C++”, 4th edition, MH, 2015.
(Unit 1 & 2)
2. E Balagurusamy,”Object Oriented Programming with C++”, 4th Edition,
Tata McGraw-Hill Education, 2008. (Unit 3, 4 & 5)
Reference Books:
1. Nell Dale, Chip Weems, “Programming and Problem Solving with C++”,
5th Edition, Jones and Barklett Publishers, 2010.
2. John Hubbard, “Schaum's Outline of Programming with C++”, MH,
2016.
3. Yashavant P. Kanetkar, “Let us C++”, BPB Publications, 2020
4. ISRD Group, “Introduction to Object-oriented Programming and C++”,
Tata McGraw-Hill Publishing Company Ltd., 2007.
5. D. S. Malik, “C++ Programming: From Problem Analysis to Program
Design”, Third Edition, Thomson Course Technology, 2007.
6. https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_012
97200240671948837_shared/overview
18. Mini Project Suggestions
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.