PPS Material-2023
PPS Material-2023
UNIT-1
Introduction to Programming:
Computer Languages, Compilers, Compiling and executing a program,
Representation of Algorithms and Flowcharts with examples.
Introduction to C Programming Language:
Structure of a C Program, I/O: Simple input and output with scanf() and printf(), C
Tokens- Keywords, Identifiers, Constants, Variables, Data types, Operators,
Expressions and precedence, Expression evaluation, Type conversion.
Computer languages are the languages through which the user can communicate with
the computer by writing program instructions.
It is also called as binary language which is nothing set of instructions given to the
computer in the forms of 0’s and 1’s.This is the language of computers.
Advantages:
Disadvantages:
It is also called as symbolic language which is nothing but the set of instructions given to
the computer in the form of symbolic names or mnemonic codes.
Example:-
Advantages:
1. Easy to remember the symbolic names and there is no need to remember the
machine code.
2. Program understanding, modification is relatively easier when compared to
machine language.
3. The execution speed of a program written in assembly language is same as that
of the equivalent program written in machine language.
Disadvantages:
1. There is a need for translating the assembly language program into machine
language program.
2. Like machine language, the assembly language is also machine dependent.
3. It is unstructured language.
4. Difficult to understand and debug when compared to high level language.
Advantages:
1. Easy to understand.
2. Easy to read write and modify.
3. The code is very compact.
4. It is structured language.
5. They are machine independent programs.
3|Page Programming for Problem Solving
Disadvantages:
1. Take more time to execute when compared with machine language or assembly
language.
2. Translator is required to convert the programs written in high-level language to
machine language.
2. Write a short note on compilers. Write the various steps involved in compiling
and executing a C program?
Compiler:
A C program has to pass through many phases for its successful execution and to
achieve the desired output.
1. Editing phase
2. Compilation phase
3. Linking phase
4. Execution phase
1. Editing Phase:
In the editing phase, the C program is entered into a file through a text editor. The file is
saved on the disk with an extension of ‘C’. Corrections in the program at later stages are
done through these editors. Once the program has been written, it requires to be
translated into machine language.
2. Compilation Phase:
4|Page Programming for Problem Solving
This phase is carried out by a program called as compiler. Compiler translates the
source code into the object code. The compilation phase cannot proceed successfully
until and unless the source code is error-free. The compiler generates messages if it
encounters syntactic errors in the source code. The error-free source code is translated
into object code and stored in a separate file with an extension ’.obj’.
3. Linking Phase:
In this phase, the linker links the files and functions with the object code under
execution. The result of this linking process produces an executable file with an
extension of ‘.exe’. Now the object code is ready for next phase.
4. Execution Phase:
In this phase, the executable object code is loaded into the memory and the program
execution begins. We may encounter errors during the execution phase even though
compilation phase is successful. The errors may be run-time errors and logical errors.
3. What is an algorithm? Write the various criteria used for judging an algorithm
with an example?
Algorithm:
An algorithm is a step by step process to solve a problem.
The algorithm which is written in English is known as pseudo code.
Properties of an Algorithm:
Every algorithm should have the following 5 properties.
1. Input: An algorithm may take one or more inputs.
2. Output: An algorithm should produce at least one output.
3. Finiteness: An algorithm should end after a fixed number of steps.
4. Definiteness: Each instruction of an algorithm must be clear and well defined.
5. Effectiveness: The operations must be simple and each step of an algorithm must be
easily convertible into program statement.
1. Documentation section:
It is a set of comment lines that describes the name of the program.
Examples: // Write a C program to find the sum of 2 numbers
7|Page Programming for Problem Solving
2.Link section:
It tells the compiler to link functions from the system library.
Examples:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include is a pre-processor directive command.
stdio is a standard input & output.
.h is an extension of header file.
3. Definition section:
It defines all the symbolic constants and assigns them some value.
Example: #define PI 3.14
Here #define is a pre-processor directive command which tells the compiler whenever
PI is found in the program replace it with 3.14.
The program execution begins at the opening brace and ends with closing brace.
1. Keywords/Reserved words
2. Identifiers
3. Constants/Literals
4. Strings
5. Special symbols
6. Operators
2. Identifiers: Identifiers are names given to the variables, functions and arrays defined
by the user. Identifier is a sequence of letters, digits and one special character i.e., _
(Underscore).
Ex:- a, b, abc , abc _123,a123,_xyz etc.
Rules for declaring Identifiers:-
1. Identifiers must be start with a letter or _ (Underscore).
2. Identifiers should not start with a digit.
3. No special symbols other than _ (Underscore) are allowed within
the identifiers.
4. Identifiers are case sensitive i.e., the uppercase and lowercase
letters are different.
5. Identifiers should not be declared as keywords.
6. Identifiers can be a length of first 31 characters.
3.Constant/Literals:-
Constants are the fixed values that do not change during the execution of
a program.
Constant are divided into two types.
1. Numeric constants
2. Non-Numeric /Character constants
1.Single character constants:- Any single letter or digit enclosed within single quotation
marks is called single character constant.
Ex:- ‘A’,’5’
2.String character constant:- String is a group of characters enclosed
within the double quotation marks is called string character constants.
Declaration/Syntax of a variable:-
datatype variable1,variable 2, . . . . ,variable n;
Ex1:- int a, b, c;
Ex2:- float x, y,z;
11 | P a g e Programming for Problem Solving
Declaration/Syntax:-
datatype variable =constant;
Ex1:- int a=10,b=34,c=43;
Ex2:- float x=10.3,y=34.15;
1) When the given value is greater than the double range then long
double is used.
2) The control string of long double is “%Lf”.
3) It occupies 10 bytes of the memory location i.e., 80bits.
4) The range of long double is 3.4E-4932 to 1.1E+4932.
Ex: long double a,b;
scanf(“%Lf%Lf”,&a,&b);
1.Arithmetic operator:-
1. Arithmetic operators are used to perform basic arithmetic
operations between the operands.
2. There are 5 types of Arithmetic operators in C language they are +,
-,* ,/ ,%.
3. Division operator(/) gives the result in quotient.
4. Modulus operator(%) gives the result in remainder.
5. % operator cannot be worked with the real constants.
2.Relational operators:-
1. Relational operators are used to compare the relation between the
operands.
15 | P a g e Programming for Problem Solving
3.Logical operators:-
1. Logical operators are used to combine two or more relational
conditions.
2. Logical operators gives the result either in 1 (true) or 0 (false).
3. There are 3 types of Logical operators in c language
1. Logical AND (&&).
2. Logical OR (||).
3. Logical NOT (!).
4.sizeof operator:- This operator can be used to find the number of bytes
occupied by a variable or data type.
Syntax:- sizeof(operand);
1. Pre-increment operator
2. Post-increment operator
3. Pre-decrement operator
4. Post-decrement operator
1.Pre-increment operator:
1. ++ operator is placed before the operand is called pre-increment
operator. Ex: ++x,++a
2. Pre-increment operator specifies first increment the value of the
variable by 1 and then assigns the incremented value to other
variable.
2.Post-increment operator:
1. ++ operator is placed after the operand is called post-increment
operator. Ex: x++,a++
2. Post-increment operator specifies first assigns the value of the
variable to other variable and then increments the value of the
variable by1.
3.Pre-decrement operator:
1. -- operator is placed before the operand is called pre-decrement
operator. Ex: --x,--a
2. Pre-decrement operator specifies first decrement the value of
the variable by 1 and then assigns the decremented value to
other variable.
4.Post-decrement operator:
1. -- operator is placed after the operand is called post-decrement
operator. Ex: x--,a--
2. Post-decrement operator specifies first assigns the value of the
variable to other variable and then decrements the value of the
variable by1.
Operator Precedence:
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.
1. Type Conversion
2. Type Casting
1. Type Conversion
The type conversion is the process of converting a data value from one data type to
another data type automatically by the compiler. Sometimes type conversion is also
called implicit type conversion. The implicit type conversion is automatically performed
by the compiler.
For example,
int i=10;
float x=15.5;
char ch=’A’;
2. Type Casting
It is also called explicit type conversion and it is used to convert from one data type to
another data type. To convert data from one type to another, we specify the new type in
parentheses before the value we want converted.
(float) a;
UNIT-2
Ex: Write a C program to check whether the given number is greater than 25.
#include<stdio.h>
int main()
{
int n;
printf("Enter any number\n");
scanf("%d",&n);
if (n>25)
printf("The given number is greater than 25");
}
2.if-else statement: It can be used to execute either if or else block of statements based
on the condition.
It is a two way branching statement in C language.
Syntax:
if (condition)
{
statement1;
}
else
{
statement2;
}
next statement;
Operation: First the condition is checked if the condition is true then statement1 will be
executed and it skips statement2 and then control is transferred to the next statement
in the program.
if the condition is false then statement1 is skipped and statement2 will be executed and
then control is transferred to the next statement in the program.
Ex: Write a C program to check whether the given number is even or odd.
#include<stdio.h>
int main()
{
int n;
printf("Enter any number\n");
22 | P a g e Programming for Problem Solving
scanf("%d",&n);
if (n%2==0)
printf("The given number is even");
else
printf("The given number is odd");
}
3.nested if-else statement: If we want to check more than one condition then nested if
else is used.
It is multi way branching statement in C language.
Syntax:
if (condition1)
{
if (condition2)
{
statement1;
}
else
{
statement2;
}
}
else
{
statement3;
}
next statement;
Operation: First the condition1 is checked if it is false then statement3 will be executed
and then control is transferred to the next statement in the program.
If the condition1 is true then condition2 is checked, if it is true then statement1 will be
executed and then control is transferred to the next statement in the program.
If the condition2 is false then statement2 will be executed and then control is
transferred to the next statement in the program.
Ex: Write a C program to find the largest number among three numbers using nested if
else.
23 | P a g e Programming for Problem Solving
#include<stdio.h>
int main()
{
int a,b,c;
printf("Enter the values of a,b,c\n");
scanf("%d%d%d",&a,&b,&c);
if (a>b)
{
if (a>c)
printf("a is largest number");
else
printf("c is largest number");
}
else
{
if(b>c)
printf("b is largest number");
else
printf("c is largest number");
}
}
4.if-else-if ladder statement: If we want to check the multiple conditions then if-else-if
ladder statement is used.
It is multi way branching statement in C language.
Syntax:
if(condition1)
{
statement1;
}
else if(condition2)
{
statement2;
}
else if(condition3)
{
24 | P a g e Programming for Problem Solving
statement3;
}
else if(condition n)
{
statement n;
}
else
{
default statement;
}
next statement;
Operation: This type of structure is known as the else-if ladder. This chain generally
looks like a ladder hence it is also called as an else-if ladder. The test-expressions are
evaluated from top to bottom. Whenever a true test-expression if found, statement
associated with it is executed. When all the n test-expressions becomes false, then the
default else statement is executed.
Ex: Write a C program to calculate percentage and grade based on input marks of five
subjects.
#include <stdio.h>
int main()
{
int phy,chem,eng,math,comp;
float per;
printf("Enter five subjects marks of a student\n");
scanf("%d%d%d%d%d",&phy,&chem,&eng,&math,&comp);
per=(phy+chem+eng+math+comp)/5.0;
printf("Percentage=%f\n",per);
if(per>=70)
{
printf("Distinction");
}
else if(per>=60)
{
printf("First Class");
}
25 | P a g e Programming for Problem Solving
else if(per>=40)
{
printf("Second Class");
}
else
{
printf("Fail");
}
}
5.switch statement: If we want to select one statement from more number of statements
then switch statement is used.
It is a multi way branching statement in C language.
Syntax:
switch(expression)
{
case value1:block1;
break;
case value2:block2;
break;
--------
--------
case valuen:blockn;
break;
default :default block;
}
next statement;
Operation: First the expression value (integer constant/character constant) is
compared with all the case values in the switch. if it is matched with any case value then
the particular case block will be executed and then control is transferred to the next
statement in the program.
If the expression value is not matched with any case value then default block will be
executed and then control is transferred to the next statement in the program.
Ex: Write a C program to perform all arithmetic operations between 2 operands using
switch statement.
26 | P a g e Programming for Problem Solving
#include<stdio.h>
int main()
{
int x,y,sum,sub,mul,div,mod,choice;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Enter your choice
1.Addition\n2.Subtraction\n3.Product\n4.Quotient\n5.Remainder\n”);
scanf("%d",&choice);
switch(choice)
{
case 1:sum=x+y;
printf("The sum of x and y is %d",sum);
break;
case 2:sub=x-y;
printf("The sub of x and y is %d",sub);
break;
case 3:mul=x*y;
printf("The mul of x and y is %d",mul);
break;
case 4:div=x/y;
printf("The div of x and y is %d",div);
break;
case 5:mod=x%y;
printf("The mod of x and y is %d",mod);
break;
default :printf("Invalid Choice");
break;
}
}
2. do while
3. for
1.while loop statement: It is used when a group of statements are executed repeatedly
until the specified condition is true.
It is also called entry controlled loop.
The minimum number of execution takes place in while loop is 0.
Syntax:
while(condition)
{
body of while loop;
}
next statement;
Operation: First the condition is checked if the condition is true then control enters into
the body of while loop to execute the statements repeatedly until the specified condition
is true.
if the condition is false, the body of while loop is skipped and control comes out of the
loop and continues with the next statement in the program.
3.for loop statement:- It is used when a group of statements are executed repeatedly
until the specified condition is true.
It is also called entry controlled loop.
The minimum number of execution takes place in for loop is 0.
Syntax:-
29 | P a g e Programming for Problem Solving
for (initialization;condition;increment/decrement )
{
body of for loop;
}
next statement;
Operation: First initial value will be assigned. Next condition is checked if the condition
is true then control enters into the body of for loop to execute the statements. After the
execution of statements the initial value will be incremented/decremented. After initial
value will be incremented/decremented the control again checks for the condition. If
the condition is true then the control is again enters into the body of for loop to execute
the statements repeatedly until the specified condition is true.
if the condition is false, the body of for loop is skipped and control comes out of the loop
and continues with the next statement in the program.
1.goto statement:
goto is an unconditional statement used to transfer the control from one statement to
another statement in the program.
Syntax:-
goto label;
label:
Statements;
Ex: Write a C program to check whether the given number is even or odd using goto
statement.
#include<stdio.h>
int main()
{
int n;
printf("Enter any number\n");
scanf("%d",&n);
if(n%2==0)
goto even;
else
goto odd;
even:
printf("The given number is even");
goto end;
odd:
printf("The given number is odd");
goto end;
end:
}
2.break statement:
break is an unconditional statement used to terminate the loops or switch statement.
When it is used in loops (while,do while,for) control comes out of the loop and
continues with the next statement in the program.
When it is used in switch statement to terminate the particular case block and then
control is transferred to the next statement in the program.
Syntax:-
31 | P a g e Programming for Problem Solving
statement;
break;
Ex: Write a C program based on break statement.
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==4)
break;
printf(“%d\t”,i);
}
}
#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,d,root1,root2;
printf(" Enter the values of a,b,c\n");
scanf(" %f %f %f ", &a, &b, &c);
d= (b * b) - (4 * a * c);
if(d > =0)
{
root1=-b+sqrt(d)/(2*a);
root2 =-b-sqrt(d)/(2*a);
printf(“root1=%f,root2=%f”,root1,root2);
}
else
printf("Roots are imaginary");
}
int main()
{
int digit,n,sum=0;
printf("Enter any number\n");
scanf("%d",&n);
while(n!=0)
{
digit=n%10;
sum=sum+digit;
n=n/10;
}
printf("The sum of individual digits of a given number is %d",sum);
}
scanf("%d",&n);
temp=n;
while(n!=0)
{
digit=n%10;
reverse=reverse*10+digit;
n=n/10;
}
if(temp==reverse)
printf("The given number is Palindrome");
else
printf("The given number is not a Palindrome");
}
10. Write a C program to find GCD of two given numbers using while loop?
#include<stdio.h>
35 | P a g e Programming for Problem Solving
int main()
{
int a,b,c;
printf("Enter the two numbers\n");
scanf("%d%d",&a,&b);
while(a%b!=0)
{
c=a%b;
a=b;
b=c;
}
printf("The GCD of a,b is %d",b);
}
scanf("%d",&n);
printf(“Multiplication table of a given number is\n”);
for(i=1;i<=20;i++)
{
printf(“%d * %d=%d\n”,n,i,n*i);
}
}
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; i++)
{
for(j=1; j<=i; j++)
{
printf("* ");
}
printf("\n");
}
}
12345
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; i++)
{
for(j=1; j<=i; j++)
{
printf("%d ",j);
}
printf("\n");
}
}
17. Define array and explain how one dimensional array is declared and
initialized in C with an example?
Array:
1. Array is a collection of elements of the same data type.
2. Arrays can be used to store multiple values.
3. Arrays are the derived data type in C which can store the primary type of data such as
int, char, double, float, etc.
4. Array range starts from 0 to n-1.
5. Array elements are stored in contiguous memory locations or consecutive memory
locations or successive memory locations.
1.One Dimensional arrays (1DA) :-
If an array contains one subscript then it is called one dimensional array.
Declaration/Syntax of 1DA:
datatype arrayname[size];
In the above syntax data type maybe any basic data type such as int,float, etc.
arrayname is any valid identifier.
size indicates number of elements can be stored in an array name.
Example: int arr[10];
39 | P a g e Programming for Problem Solving
Here int is the data type, arr is the name of the array and 10 is the size of array. It means
array arr can only contain 10 elements of int type. Index of an array starts from 0 to
size-1 i.e first element of arr array will be stored at arr[0] address and last element will
occupy arr[9].
printf("%d\n",a[i]);
}
}
18. Write a C program to find both the largest and smallest elements using 1DA?
#include<stdio.h>
int main()
{
int x[5],i,large,small;
printf(“ Enter any five integer array elements\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&x[i]);
}
large=x[0];
small=x[0];
for(i=1;i<5;i++)
{
if(x[i]>large)
large=x[i];
if(x[i]<small)
small=x[i];
}
printf(“The largest element from the given array is %d”,large);
printf(“The smallest element from the given array is %d”,small);
}
19. Write a C program to sort a given list of integers in ascending order using
1DA?
#include<stdio.h>
int main ()
{
int a[100],i,j,n,temp;
printf("Enter size of an array\n");
scanf("%d",&n);
41 | P a g e Programming for Problem Solving
20. Explain how two dimensional arrays are declared and initialized in C with an
example?
Two Dimensional Arrays (2DA):
If an array contains two subscripts then it is called two dimensional arrays.
It is also called multi dimensional arrays.
Two dimensional array elements are stored in consecutive memory locations.
Two dimensional arrays are mainly used for performing matrix operations like matrix
addition, subtraction,multiplication,transpose,etc.
42 | P a g e Programming for Problem Solving
Example:
int a [3][4];
Example: Program to Reading and Storing elements in a matrix and printing it.
#include<stdio.h>
int main()
{
43 | P a g e Programming for Problem Solving
int a[3][3],i,j;
printf("Enter the elements of matrix a\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Printing the elements\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
}
{
Transpose[i][j]=A[j][i];
}
}
printf(‘The Transpose of matrix A is\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,Transpose[i][j]);
}
printf(“\n”);
}
}
22. Write a C program to perform addition of two matrices and print the result in
another matrix of order 3*3?
#include<stdio.h>
int main()
{
int A[3][3], B[3][3], C[3][3],i,j;
printf(“Enter the elements of matrix A\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&A[i][j]);
}
}
printf(“Enter the elements of matrix B\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&B[i][j]);
}
45 | P a g e Programming for Problem Solving
}
for(i =0;i <3;i++)
{
for(j= 0;j <3;j++)
{
C[i][j]=A[i][j]+B[i][j];
}
}
printf(“The result in C matrix is \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,C[i][j]);
}
printf(“\n”);
}
}
23. Write a C program to perform multiplication of two matrices and print the
result in another matrix of order 3*3?
#include<stdio.h>
int main()
{
int A[3][3], B[3][3], C[3][3],i,j,k;
printf(“Enter the elements of matrix A\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&A[i][j]);
}
}
printf(“Enter the elements of matrix B\n”);
for(i=0;i<3;i++)
{
46 | P a g e Programming for Problem Solving
for(j=0;j<3;j++)
{
scanf(“%d”,&B[i][j]);
}
}
for(i =0;i <3;i++)
{
for(j= 0;j <3;j++)
{
C[i][j]=0;
for(k= 0;k<3; k++ )
{
C[i][j]=C[i][j]+(A[i][k]*B[k][j]);
}
}
}
printf(“The result in C matrix is \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,C[i][j]);
}
printf(“\n”);
}
}
UNIT-3
Designing Structured Programs using Functions:
Functions - Declaring a function, Categories of functions, passing parameters to
functions: call by value, call by reference, passing arrays to functions, Scope-
Local Vs Global, Storage classes, Recursion with example programs.
1. Define a function and explain the different types of functions with an example
program?
47 | P a g e Programming for Problem Solving
Function:
1. A Function is a sub program/self-contained block of one or more statements that
performs a special task when called.
2. Every C program execution starts with main().
3. main() calls other functions to share the work.
4. The large programs can be divided into small programs using functions. Hence, a
large project can be divided among many programmers.
5. Data reusability is the main achievement of C functions.
How function works: Whenever a function is called, control passes to the called function
and working of the calling function is temporarily stopped. When the execution of the
called function is completed, then control return back to the calling function and executes
the next statements in a program.
Types of functions:
There are two types:
1) Library functions/Standard functions
2) User defined functions
1.Library functions:Library functions are fixed and pre defined meaning in C language.
Ex: printf(),scanf(),sqrt(),pow() etc.
2.User defined functions:These functions are developed by the user at the time of
writing a program.
Eg: main(),MRCET(),add(),factorial() etc.
3. Function Definition
2. Function Call:
The function call tells the compiler when to execute the function definition. When a
function call is executed, the execution control jumps to the function definition where
the actual code gets executed and return to the same function call once the execution
completes.
Syntax:
functionname(parameters list);
3. Function Definition:
The function definition provides the actual code of that function. The function definition
is also known as the body of the function. The actual task of the function is implemented
in the function definition. The function definition is performed before the main function
or after the main function.
Syntax:
returntype functionname(datatype argument1,datatype argument2,...datatype
argument n )
{
body of a function;
return(expression);
}
In the above syntax returntype may be any basic data type such as int, float, char etc.
return statement is used to send a value back to the calling function.
Example:
main() //calling function
{
MRCET(A,B,C); //called function
}
49 | P a g e Programming for Problem Solving
MRCET(X,Y,Z)
{
body of a function;
}
Actual arguments/Actual parameters: The arguments of the calling function are called
actual arguments. In the above example A,B,C are actual arguments.
Formal arguments/Formal parameters: The arguments of the called function are called
formal arguments. In the above example X,Y,Z are called formal arguments.
Example: Write a C program to find the addition of two numbers using functions.
#include<stdio.h>
int add(int x, int y);
int main()
{
int a,b,c;
printf("Enter the values of a,b \n");
scanf(" %d%d",&a,&b);
c=add(a,b);
printf("The sum of a,b is %d",c);
}
int add(int x, int y)
{
return (x+y);
}
2. Explain the categories of functions based on the arguments and return values?
Function Categories based on Arguments and Return Values:
There are 4 types
1. Functions with arguments and functions with return values.
2. Functions without arguments and functions with no return values.
3. Functions with no arguments and functions with return value.
4. Functions with arguments and functions with no return values.
Function with return values i.e. calling function receives the value from the called
function.
In effect there is a data transfer between calling and called function.
Example program
#include<stdio.h>
int add(int x, int y);
int main()
{
int a,b,c;
printf(“enter the values of a,b\n”);
scanf(“%d%d”,&a&b);
c=add(a,b);
printf(“the sum is %d”,c);
}
int add(int x , int y)
{
return(x+y);
}
Example program
#include<stdio.h>
void add();
int main()
{
add();
}
void add()
{
51 | P a g e Programming for Problem Solving
int a,b;
printf(“Enter the values of a,b\n”);
scanf(“%d%d”,&a&b);
printf(“the sum is %d”,a+b);
}
Example program
#include<stdio.h>
int add();
int main()
{
int c;
c=add();
printf(“the sum is %d”,c);
}
int add()
{
int a,b;
printf(“Enter the values of a,b\n”);
scanf(“%d%d”,&a,&b);
return(a+b);
}
In effect there is a data transfer from calling function to called function, but there is no
data transfer from the called function to calling function.
Example program
#include<stdio.h>
void add(int x, int y);
int main()
{
int a,b;
printf(“Enter the values of a,b\n”);
scanf(“%d%d”,&a&b);
add(a,b);
}
void add(int x,int y)
{
printf(“The sum is %d”,x+y);
}
1.Call by value:
Sending or passing the values as actual arguments to the called function is known as call
by value.
In this method the changes are made in formal arguments of the called function does
not effect the actual arguments of the calling function.
Ex: Write a C program to interchange the values of two variables using call by value.
#include<stdio.h>
int swap(int x, int y);
int main()
{
53 | P a g e Programming for Problem Solving
int a=10,b=20;
printf("Before swapping a=%d, b=%d \n", a,b);
swap(a,b);
printf(" After swapping a=%d, b=%d", a,b);
}
int swap(int x, int y)
{
int temp;
printf(" Before swapping x=%d, y=%d \n",x,y);
temp=x;
x=y;
y=temp;
printf(" After swapping x=%d, y=%d \n",x,y);
}
2.Call by address:
Sending or passing addresses as an actual arguments to the called function is known as
call by address.
In this method changes are made in formal arguments of the called function effect the
actual arguments of the calling function.
Ex: Write a C program to interchange the value of two variable using call by address.
#include<stdio.h>
int swap(int *x, int *y);
int main()
{
int a =10,b=20;
printf("Before swapping a=%d, b=%d \n",a,b);
swap(&a,&b);
printf(" After swapping a=%d, b=%d",a,b);
}
int swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
54 | P a g e Programming for Problem Solving
Scope:
Variables can be accessed based on their scope. The scope of a variable decides the
portion of a program in which the variable can be accessed. The variable scope defines
the visibility of variable in the program. There are 2 types of variables.
1. Local Variables
2. Global Variables
1. Local variables:
1.The variables which are declared within the body of a function are called local
variables.
2.Local variables are also called internal variables.
3.Local variables are cannot be accessed by other functions in a program.
4.The default value of a local variable is garbage value.
5.Local variables are used to store the data values temporarily.
6.The life time of a local variable is till the control remains within the function.
2. Global variables:
1.The variables which are declared outside the main() function are called global
variables.
2.Global variables are also called external variables.
3.Global variables are accessed by all the functions in the program.
4.The default value of a global variable is zero.
5.Global variables are used to store the data values permanently.
6.The life time of a global variable is till the program terminates.
Ex: Write a C program to give an example based on local and global variables.
#include<stdio.h>
int x=50,y =100;
int main()
{
int a =10,b=20;
printf("Local variables are a=%d,b=%d \n", a,b);
printf(" Global variables are x=%d,y=%d\n",x,y);
MRCET();
}
MRCET()
{
int a,b;
56 | P a g e Programming for Problem Solving
7. Define recursion and write a C program to find factorial of a given number using
recursion?
Recursion:
When a called function in turn calls the same function then chaining occurs. Recursion is
a special case of this process or a repetitive process where a function calls itself. Any
function which calls itself in the function definition part then it is called recursive
function, and such function calls are called recursive calls. Recursive functions are very
useful to solve many mathematical problems in a simpler way.
Example:
main()
{
recursion( );
}
recursion( )
{
recursion( );
}
Example: C program to find the factorial of a given number using recursion.
#include<stdio.h>
int factorial(int x);
58 | P a g e Programming for Problem Solving
int main()
{
int r,n;
printf("Enter any number\n");
scanf("%d",&n);
r=factorial(n);
printf("the factorial of the given number is %d",r);
}
int factorial(int x)
{
int fact;
if(x==0)
return(1);
else
fact=x*factorial(x-1);
return(fact);
}
UNIT-4
1. Define string and explain how strings are declared and initialized in C with
example program?
String:
1. String is a group of characters enclosed within double quotation marks.
2. String is also called array of characters or character arrays.
3. Character Array elements are stored in contiguous memory locations or consecutive
memory locations or successive memory locations.
4. The string should end with ‘\0’ (null character) in C language.
5. The size of the string is equal to no.of characters in the string + 1 (required for null
character(‘\0’)).
(or)
char city[6]={‘D’,’E’,’L’,’H’,’I’,’\0’};
city[0] refers to 1st character in string i.e. D
city[1] refers to 2ndcharacter in string i.e. E
city[2] refers to 3rdcharacter in string i.e. L
city[3] refers to 4thcharacter in string i.e. H
city[4] refers to 5thcharacter in string i.e. I
city[5] refers to 6thcharacter in string i.e. ‘\0’.
Example:
#include<stdio.h>
int main()
{
char name[50];
printf("Enter your name\n ");
gets(name);
printf("Your name is\n ");
puts(name);
}
2. puts( ):
puts( ) is a output function in strings used to print the string on the monitor.
Syntax:
puts(arrayname);
Example Program:
#include <stdio.h>
int main()
{
61 | P a g e Programming for Problem Solving
char name[30];
printf("Enter any name:");
gets(name); // read string
printf("Name: ");
puts(name); // display string
}
1.strcpy( ):-
This function is used to copy one string into another string.
Syntax: strcpy(string1,string 2);
Here, string 2 is copied into string 1 and after copying both the contents of string 1 and
string 2 are same.
Example: C program to copy one string into another string using strcpy().
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char name1[20],name2[20];
printf(“Enter the first name\n”);
gets(name1);
62 | P a g e Programming for Problem Solving
2.strcat():-
This function is used to combine two strings.
Syntax: strcat (string1,string2);
Here, string2 is added to the end of the string1.
Example : C program to combine two strings using strcat().
#include<stdio.h>
#include<string.h>
int main()
{
char name1[20],name2[20];
printf(“Enter the first name\n”);
gets(name1);
printf(“Enter the second name\n”);
gets(name2);
strcat(name1,name2);
printf(“After concatenation the name is %s”,name1);
}
3.strrev() :-
This function is used to reverse a given string.
Syntax: strrev(string);
Example: C program to find the reverse of given string using strrev().
#include<stdio.h>
#include<string.h>
int main()
{
char name[20];
printf(“Enter any name\n”);
gets(name);
strrev(name);
63 | P a g e Programming for Problem Solving
4.strlen():-
This function is used to find the length of the given string.
This function does not include the ‘\0’(null character).
Syntax: strlen(string);
Example: C program to find the length of a given string using strlen().
#include<stdio.h>
#include<string.h>
int main()
{
char name[20];
int x;
printf(“Enter any name\n”);
gets(name);
x=strlen(name);
printf(“The length of a given string is %d”,x);
}
5.strlwr():-
This function is used to convert any uppercase letters into lowercase letters.
Syntax: strlwr(string);
Example: C program to convert any uppercase letters into lowercase letters using
strlwr().
#include<stdio.h>
#include<string.h>
int main()
{
char name [20];
printf(“Enter any name\n”);
gets(name);
strlwr(name);
printf(“The converted name is %s”,name);
}
64 | P a g e Programming for Problem Solving
6.strupr():-
This function is used to convert any lowercase letters into uppercase letters.
Syntax: strupr(string);
Example: C program to convert any lowercase letters into letters uppercase using
strupr().
#include<stdio.h>
#include<string.h>
int main()
{
char name [20];
printf(“Enter any name\n”);
gets(name);
strupr(name);
printf(“The converted name is %s”,name);
}
7.strcmp():-
This function is used to compare two strings character by character based on ASCII
values (American Standard Code for Information Interchange) and returns zero when
both the strings are equal.
Syntax: strcmp(string1,string2);
Example : C program to check whether the two strings are equal or not.
#include<stdio.h>
#include<string.h>
int main()
{
char name1[20],name2[20];
printf(“Enter the first name\n”);
gets(name1);
printf(“Enter the second name\n”);
gets(name2);
if(strcmp(name1,name2)= =0)
printf(“Both the given strings are equal”);
else
printf(“Both the given strings are not equal”);
}
65 | P a g e Programming for Problem Solving
Example: Write a c program to read and print any 5 names on the monitor.
#include<stdio.h>
int main()
{
char name[5][20];
int i;
printf(“Enter any 5 names”);
for(i=0;i<5;i++)
{
scanf(“%s”,name[i]);
}
printf(“Entered 5 names are\n”);
for(i=0;i<5;i++)
{
printf(“%s\n”,name[i]);
}
}
char name[10][20],temp[20];
int n,i,j;
printf("Enter the number of strings\n");
scanf("%d",&n);
printf("Enter the strings\n");
for(i=0;i<n;i++)
{
scanf("%s",name[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1;j++)
{
if(strcmp(name[j],name[j+1])>0)
{
strcpy(temp,name[j]);
strcpy(name[j],name[j+1]);
strcpy(name[j+1],temp);
}
}
}
printf("The sorted order of strings are\n") ;
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
}
7. Define a pointer and explain how the pointer variable is declared and
initialized in C?
Pointer:
Declaration of a pointer:
68 | P a g e Programming for Problem Solving
datatype *variable;
Example1: int *p;
Here p is a pointer variable which always points to integer data type.
Initialization of a pointer:
The way of allocating the address of a variable to a pointer variable is known as pointer
initialization.
Syntax:
pointerVariableName = &variableName ;
Example:
int *p,x;
p=&x;
& is called reference operator/address operator which specifies where the value would
be stored.
Example: C program to print the values and its corresponding addresses using pointers.
#include<stdio.h>
main()
{
int *p,x=10;
p=&x;
69 | P a g e Programming for Problem Solving
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the
five elements will be stored as follows
Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
int *p;
p = &arr[0];
70 | P a g e Programming for Problem Solving
Now we can access every element of array arr using p++ to move from one element to
another.
Example: Write a c program to read and print any 5 integer array elements using
pointers.
#include<stdio.h>
int main()
{
int x[5],*p,i;
p=&x[0];
printf(“ Enter any five integer array elements\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&x[i]);
}
printf(“ The 5 integer array elements are \n”);
for(i=0;i<5;i++)
{
printf(“%d is stored at address %u\n”,*p,p);
p++;
}
}
9. Write a C program to find the sum of all elements stored in array using
pointers?
#include<stdio.h>
int main()
{
int x[5],*p,i,sum=0;
p=&x[0];
printf(“ Enter any 5 integer array elements\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&x[i]);
}
for(i=0;i<5;i++)
71 | P a g e Programming for Problem Solving
{
sum=sum+*p;
p++;
}
printf(“ The sum of array elements using pointers is %d”,sum);
}
Syntax:
struct tagname *variable;
Selection operator/arrow operator( -> )
To access the each member of a structure using pointer variable we have use arrow
operator ( -> ) in c language.
Syntax:
Pointer variable ->structure member
Example: Define a structure type student that would contain roll number,name,branch
and marks.Write a c program to read this information from keyboard and print the
same on monitor using structure pointer or ( -> )operator.
#include<stdio.h>
struct student
{
int rno;
char name[20];
char branch[20];
float marks;
};
int main()
{
struct student s,*p;
p=&s;
printf(“Enter the student rno,name,branch and marks\n”);
scanf(“%d%s%s%f”,&s.rno,s.name,s.branch,&s.marks);
printf(“%d\t%s\t%s\t%f”,p->rno,p->name,p->branch,p->marks);
}
int main()
{
/* ... */
73 | P a g e Programming for Problem Solving
The arguments can be passed from operating system command prompt to main( ).
They are parameters/arguments supplied to the program when it is invoked.
To pass command line arguments, we typically define main( ) with two arguments :
first argument is an integer value, that specify “the number of command line arguments”
and second is “list of command-line arguments”. Therefore they are called as Command
line arguments.
Syntax:
int main(int argc, char *argv[])
{
Example: To find the sum of two integer numbers using command line arguments in C.
#include <stdio.h>
int main(int argc, char *argv[])
{
int a,b,sum;
if(argc!=3)
{
printf("please use in specified format\n");
printf("please use \"prg_name value1 value2 \"\n");
exit(1);
}
a = atoi(argv[1]);
74 | P a g e Programming for Problem Solving
b = atoi(argv[2]);
sum = a+b;
printf("Sum of %d, %d is: %d\n",a,b,sum);
}
Syntax:
enum enumerartiontype{ identifier1,identifier2,….,identifier n };
Example: Consider 12 months of a year.
In the above example month is a user defined data type or enumeration type
and jan,feb,……dec are the identifiers and their values starts from zero(0)
so jan refers to 0,feb refers to 1,mar refers to 2,…dec refers to 11.
Example:
enum year { Jan, Feb, Mar, Apr, May, Jun, Jul,
Aug, Sep, Oct, Nov, Dec};
int main()
{
int i;
for(i=Jan; i<=Dec; i++)
{
75 | P a g e Programming for Problem Solving
14. Explain briefly about dynamic memory management functions with example
programs?
Dynamic Memory Allocation:
The process of allocating memory during program execution is called dynamic memory
allocation. All the memory management functions are found in standard library file
(stdlib.h).
1. malloc()
2. calloc()
3. realloc()
4. free()
1.malloc( ) function
malloc() is the short name for memory allocation and is used to dynamically allocate a
single large block of contiguous memory according to the size specified.
It does not initialize the memory allocated during execution. It carries a garbage value.
Syntax:
ptr=(void *)malloc(number*sizeof(int));
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n,*ptr;
printf("Enter the no. of integers:");
scanf("%d",&n);
ptr=(int *)malloc(n*sizeof(int));
if(ptr==NULL)
{
76 | P a g e Programming for Problem Solving
2.calloc( ) function
calloc() is the short name for contiguous allocation and is used to dynamically allocate
multiple blocks of memory according to the size specified.
Syntax:
ptr=(void *)calloc(number,sizeof(int));
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n,*ptr;
printf("Enter the no. of integers:");
scanf("%d",&n);
ptr=(int *)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("Memory is not available");
exit(1);
}
77 | P a g e Programming for Problem Solving
for(i=0;i<n;i++)
{
printf("Enter an integer:");
scanf("%d",ptr+i);
}
for(i=0;i<n;i++)
{
printf("%d\t",*(ptr+i));
}
}
3.realloc( ) function
realloc ( ) function modifies the allocated memory size by malloc ( ) and calloc ( )
functions to new size.
If enough space doesn’t exist in memory of current block to extend, new block is
allocated for the full size of reallocation, then copies the existing data to new block and
then frees the old block.
Syntax
4.free( ) function
free ( ) function frees the allocated memory by malloc ( ), calloc ( ), realloc ( ) functions
and returns the memory to the system.
Syntax
UNIT-5
Files: Text and Binary files, Opening and Closing files, File input /output
functions, Creating and Reading and writing text files, Appending data to existing
files.
Example:
struct student s;
Initialization of a structure variable:-
Syntax:-
struct tagname variable={member1,member2,…member n};
Example:
struct student s={501,”Dinesh”,”cse”,100.5};
Member operator or dot operator( . ):-
To access the each member of a structure using the structure variable we have to use
dot operator ( . ) in c language.
Syntax:-
Structure variable.Structure member
Example Program:
Example: Define a structure type student that would contain roll number,name,branch
and marks. Write a C program to read this information from the keyboard and print the
same on the monitor.
#include<stdio.h>
struct student
{
int rno;
char name[20];
char branch[20];
float marks;
};
int main()
{
struct student s;
printf(“Enter the student rno,name,branch and marks\n”);
scanf(“%d%s%s%f”,&s.rno,s.name,s.branch,&s.marks);
printf(“the student details are\n”);
printf(“%d\t%s\t%s\t%f”,s.rno,s.name,s.branch,s.marks);
}
80 | P a g e Programming for Problem Solving
{
int rno;
char name[20];
char branch[20];
float marks;
};
int main()
{
struct student s[5];
int i;
printf(“Enter any 5 student details \n”);
for(i=0;i<5;i++)
{
printf(“Enter the student rno,name,branch,marks\n”);
scanf(“%d%s%s%f”,&s[i].rno,s[i].name,s[i].branch,&s[i].marks);
}
printf(“the 5 students details are\n”);
for(i=0;i<5;i++)
{
printf(“%d\t%s\t%s\t%f\n”,s[i].rno,s[i].name,s[i].branch,s[i].marks);
}
};
In the above syntax union is a keyword that declares/stores the members or fields of a
union.
tag name is name of the union.
datatype maybe any basic datatype such as int,float,char etc.
member1,member2,…………….,member n are union members or fields of a union.
The body of a union should be end with semicolumn(;).
Example:
union student
{
int rno;
char name[20];
char branch[20];
float marks;
};
Declaration of a union variable:-
Syntax:-
union tagname variable;
Example:
union student s;
Initialization of a union variable:-
Syntax:-
union tagname variable={member1,member2,…member n};
Example:
union student s={501,”Dinesh”,”cse”,100.5};
Member operator or dot operator( . ):-
To access the each member of a union using the union variable we have to use dot
operator ( . ) in c language.
Syntax:-
union variable. union member
Example Program:
#include<stdio.h>
union student
{
int rno;
83 | P a g e Programming for Problem Solving
char name[20];
float marks;
};
int main()
{
union student s;
printf(“enter the student rollno\n”);
scanf(“%d”,&s.rno);
printf(“the rno=%d”,s.rno);
printf(“enter the student name\n”);
scanf(“%s”,s.name);
printf(“name of the student is %s”,s.name);
printf(“enter the marks of the student\n”);
scanf(“%f”,&s.marks);
printf(“marks of the student is %f”,s.marks);
}
Structure Union
1. Structure is a collection of elements of 1. union is a collection of elements of
different data types. different data types.
4.The body of a structure should be end 4.The body of a union should be end with
with semicolumn(;). semicolumn(;).
5.Example:- 5.Example:-
struct student union student
{ {
int rollno; int rollno;
char name[20]; char name[20];
char branch[20]; char branch[20];
float marks; float marks;
}; };
10. Structure can contain any numbers of 10. Union can contain any numbers of
members and it can handle all the members but it can handle one member
members at the same time. at a time.
6. Define file and its types and explain how to opening and closing a file?
Files in C:
86 | P a g e Programming for Problem Solving
A File is collection of related data stored permanently in computer. Using files we can
store our data in Secondary memory (Hard disk).
Types of Files
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using notepad or any simple
text editors.
When you open those files, you will see all the contents within the file as plain text. You
can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security
and takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better
security than text files.
File Operations in C:
There are 5 basic operations on files, They are
1. Naming a file
2. Opening a file
3. Reading data from a file
4. Writing data to a file
5. Closing a file
Data structure of file is defined as FILE in the standard I/O function. So all files should
be declared as type FILE.
Declaration/Syntax of a file:
FILE *fp;
fp=fopen("filename", "mode");
Here fp declare a variable as a pointer to the data type FILE.
In the above syntax mode specifies purpose of opening a file.
87 | P a g e Programming for Problem Solving
3 a Appending Open the file for appending (or adding) data to it.
Reading +
6 a+ To new data is appended at the end of file.
Appending
Closing a File
A file must be close after completion of all operations related to a file. For closing a file
we need fclose() function.
Syntax:
fclose(filepointer);
1) fopen( ): This can be used to create a new file or open an existing file.
88 | P a g e Programming for Problem Solving
Syntax: fp=fopen(“filename”,”mode”):
Syntax: fclose(fp);
3) getc( )/fgetc( ): This function can be used to read a character from a file.
Syntax: c=getc(fp);
Syntax: putc(c,fp);
Syntax: n=getw(fp);
Syntax: putw(n,fp);
7) fscanf( ): This can be used to read a set of data values from a file.
8. Write a C program to read the data from the keyboard, write it to a file called
“INPUT” and again read the same data from that file and print it on monitor?
#include<stdio.h>
89 | P a g e Programming for Problem Solving
int main( )
FILE *f1;
char ch;
f1=fopen(“INPUT”,”w”);
printf(“Enter the data to the INPUT file and press ctrl Z to stop\n”);
while((ch=getchar())!=EOF)
putc(ch,f1);
fclose(f1);
f1=fopen(“INPUT”,”r”);
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(f1);
9. Write a C program to copy the contents of one file into another file?
#include<stdio.h>
int main( )
FILE *f1,*f2;
char ch;
f1=fopen(“source.txt”,”w”);
printf(“Enter the data to the source.txt file and press ctrl Z to stop\n”);
90 | P a g e Programming for Problem Solving
while((ch=getchar())!=EOF)
putc(ch,f1);
fclose(f1);
f1=fopen(“source.txt”,”r”);
f2=fopen(“target.txt”,”w”);
while((ch=getc(f1))!=EOF)
putc(ch,f2);
fclose(f1);
fclose(f2);
f2=fopen(“target.txt”,”r”);
while((ch=getc(f2))!=EOF)
putchar(ch);
fclose(f2);
10. Write a C program to merge the contents of two files into third file?
#include<stdio.h>
int main( )
FILE *f1,*f2,f3;
91 | P a g e Programming for Problem Solving
char ch;
f1=fopen(“file1.txt”,”w”);
printf(“Enter the data to the file1.txt file and press ctrl Z to stop\n”);
while((ch=getchar())!=EOF)
putc(ch,f1);
fclose(f1);
f1=fopen(“file1.txt”,”r”);
f3=fopen(“file3.txt”,”w”);
while((ch=getc(f1))!=EOF)
putc(ch,f3);
fclose(f1);
fclose(f3);
f2=fopen(“file2.txt”,”w”);
printf(“Enter the data to the file2.txt file and press ctrl Z to stop\n”);
while((ch=getchar())!=EOF)
putc(ch,f2);
fclose(f2);
f2=fopen(“file2.txt”,”r”);
f3=fopen(“file3.txt”,”w”);
while((ch=getc(f2))!=EOF)
92 | P a g e Programming for Problem Solving
putc(ch,f3);
fclose(f2);
fclose(f3);
f3=fopen(“file3.txt”,”r”);
while((ch=getc(f3))!=EOF)
putchar(ch);
fclose(f3);