POPC Lab Manual 24-25
POPC Lab Manual 24-25
Department of CSE/ISE/CSE-DS/AI/IOT
Laboratory Manual
BPOPS103
1st Semester
Vision
Establish and develop the Institute as the Centre of higher learning, ever abreast with expanding
horizon of knowledge in the field of Engineering and Technology with entrepreneurial thinking,
leadership excellence for life-long success and solve societal problems.
Mission
1. Provide high quality education in the Engineering disciplines from the undergraduate
through doctoral levels with creative academic and professional programs.
2. Develop the Institute as a leader in Science, Engineering, Technology, Management and
Research and apply knowledge for the benefit of society.
3. Establish mutual beneficial partnerships with Industry, Alumni, Local, State and Central
Governments by Public Service Assistance and Collaborative Research.
4. Inculcate personality development through sports, cultural and extracurricular activities and
engage in social, economic and professional challenges.
BANGALORE INSTITUTE OF TECHNOLOGY
(Autonomous Institute, Affiliated to VTU )
K.R. Road, V.V. Puram, Bengaluru – 560 004. Phone: 26613237/26615865
DEPARTMENT OF CSE/ISE/CSE-DS/AI/IOT
VISION:
To be a center of excellence in computer engineering education, empowering graduates as
highly skilled professionals.
MISSION:
1. To provide a platform for effective learning with emphasis on technical excellence.
2. To train the students to meet current industrial standards and adapt to emerging
technologies.
3. To instill the drive for higher learning and research initiatives.
4. To inculcate the qualities of leadership and Entrepreneurship.
1. The graduates of the program will have the ability to build software products by
applying theoretical concepts and programming skills.
2. The graduates of the program will have the ability to pursue higher
Program Outcomes
BPOPS103 CO1 2
CO2 3 2 2
CO3 2 3 2
CO4 2 2 2 2
Principles of Programming Using C Laboratory
LIST OF PROGRAMS
10. Implement structures to read, write and compute average- marks of the students, list
the students scoring above and below the average marks for a class of N students
11. Compute the sum, mean and standard deviation of all elements stored in an array of
N real numbers using pointers
12. Copy a text file to another file, read both the input file name and target file name.
Principles of Programming Using C BPOPS103
SCHEDULE OF EXPERIMENTS
5 Display the pascal triangle by reading the number of rows as input. Week5
BIT, Bengaluru - 04 1
Principles of Programming Using C BPOPS103
BIT, Bengaluru - 04 2
Principles of Programming Using C BPOPS103
Introduction to C
A computer, in simple terms, can be defined. As an electronic device. That is designed to accept
data, perform their arithmetical mathematical and logical operations at high speed, and output
the result.
➢ Input.
• This is a process of entering data instruction into the computer.
• The data and instructions can be entered by using different input devices such as
keyboard, most common scanner, The track ball, Etc.
• Note that computers understand binary languages, which consist of only two symbols,
0 and 1. So it is the responsibility of the input device to convert the input data into
binary codes.
BIT, Bengaluru - 04 3
Principles of Programming Using C BPOPS103
➢ Storage.
Storage is the process of saving data and instructions permanently in the computer so
that they can be used for processing new line A computer has two type of storage areas.
1. Primary storage
• Primary storage, also known as main memory, is the storage area that is directly
accessible by the CPU at very high speed.
• Drawback of main memory is that it is volatile in nature, that is, as soon as the
computer is switched off, the information stored gets erased.
• RAM and ROM are the examples of primary storage.
2. Secondary storage.
Also known as axillary memory. This is just the opposite of primary storage. It basically
overcomes all the drawbacks of the primary storage area.
It is cheaper, non volatile and used to permanently store data and programs of those
jobs that are not being currently executed by the CPU.
➢ Processing.
• The process of performing operation on the data as per the instructions specified by the
user is called processing.
• Data and instructions are taken from primary memory and transfer to the arithmetic and
logic unit, which performs all sorts of calculations.
• The intermediate results of processing may be stored in main memory as they may be
required again.
• When processing completes, the final result is then transfered to the main memory.
Hence the data may move from main memory to ALU multiple times before the
processing is over.
➢ Output.
• Output is the processing of the giving the result of data processing to the outside world.
• The results are given through output devices such as monitor, Printer, Etc.
• The output devices Therefore convert the result available in binary code into a human
readable language before displaying it to the user.
1. Control unit.
The control unit is the central nervous system of the entire computer system. It manages
and controls all the components of the computer system.
BIT, Bengaluru - 04 4
Principles of Programming Using C BPOPS103
BIT, Bengaluru - 04 5
Principles of Programming Using C BPOPS103
3. Pseudocodes:
• Pseudocode is a compact and informal high-level description of an algorithm that uses
the structural conventions of a programming language
• An ideal pseudocode must be complete, describing the entire logic of the algorithm.
• Pseudocodes are an outline of a program that can easily be converted into programming
statements.
• They consist of short English phrases that explain specific tasks within 4 program's
algorithm.
• They should not include keywords in any specific computer language.
Types of Errors:
• Errors if not removed will either give erroneous output or will not let the compiler to
compile the program.
• Errors are broadly classified under four groups namely - a) Runtime error, b) Linker error,
c) Compile-time error, d) Logical error.
a) Runtime error:
Run-time errors occur when the program is being run executed. Such errors occur when
the program performs some illegal operations like:
• Dividing a number by zero
• Opening a file that already exists
• Lack of free memory space
• Finding square or logarithm of negative number
Run-time errors may terminate program execution, so the code must be written in such
a way that it handles all sorts of unexpected errors rather terminating it unexpectedly.
b) Compile-time error:
compile-time errors occur at the time of compilation of the program. Such errors can
BIT, Bengaluru - 04 6
Principles of Programming Using C BPOPS103
Structure of a C Program:
C program is composed of processor command, global declarative section and one or more
function blocks.
The preprocessor directives are instructions that indicate
how the program has to be compiled. include is one the
preprocessor command through which the compiler include
the needed information from the specified header file to the
particular code.
In Global variables or constants can be declared in the global
declaration part.
C program contains one or more functions. Functions are
defined as a group of statements that are executed together.
Function can be either system defined or user defined
functions. All functions are divided into two parts:
a) Local declaration section: Data will be visible only
within that function. Stated in other terms, the life-time of the
data will be only till the function ends.
b) Statement section: Contains the code that manipulates
the data to perform a specified task.
BIT, Bengaluru - 04 7
Principles of Programming Using C BPOPS103
2) Header File: Header file have the extension “.h”. Subroutines of one program can be
included in the other with the help of the header file i.e., program containing the
subroutine can be compiled and the generated o/p file can be included as the header file.
Note: If the subroutine has been changed then the program has to be recompiled to
include the changed in the current working program.
Standard Header file are:
o string.h – for string handling functions.
o stdlib.h – for some miscellaneous functions.
o stdio.h – for standard input and output function.
o math.h – for mathematical function.
o alloc.h – for dynamic memory allocation.
o conio.h – for clearing the screen.
3) Object File: Object files are generated by the compiler as a result of processing the
source code file. Object files contain compact binary code of the function definitions.
Linker uses these object files to produce an executable file (.exe file) by combining the
object files together. Object files have a *.o” extension, Windows and MS-DOS have a
‘.obj’ extension for the object file.
4) Binary Executable File: The binary executable file is generated by the linker. The
linker links the various object files to produce a binary file that can be directly executed.
On Windows operating system, the executable files have a ‘.exe’ extension.
BIT, Bengaluru - 04 8
Principles of Programming Using C BPOPS103
• The compiler translates the source code into an object code. The object code contains the
machine instructions for the CPU, and calls to the operating system API.
• the object file is not an executable file. Therefore, in the next step, the object file is processed
with another special program called a linker.
• The linker combines the object file with library routines (supplied with the compiler) to
produce the final executable file
• In modular programming, the source code is divided into two or more source files. All these
source files are compiled separately thereby producing multiple object files, These object
files are combined by the linker to produce an executable file.
Using of Comments:
It is a good programming practice to place some comments in the code to help the reader
understand the code clearly. C supports two types of comments.
• ‘//’ is used to comment a single statement. This is known as a line comment. End of the
line specifies the end of the comment line.
• ‘/*’ multiline commnent, a ‘/*’ is ended with ‘*/’, all the statement b/w these symbol
are comments. This is also known as block comment.
C Tokens:
Tokens are the basic building blocks in C language. A program is constructed using a
combination of these tokens, There are six main types of tokens in C.
Token in C
BIT, Bengaluru - 04 9
Principles of Programming Using C BPOPS103
Keywords:
• C has a set of reserved words often known as keywords.
• All keywords are basically a sequence of characters that have a fixed meaning.
• All keywords must be written in lowercase (small) letters.
• C language has 32 keywords as listed below.
Basic Datatypes in C:
BIT, Bengaluru - 04 10
Principles of Programming Using C BPOPS103
Variables:
A variable is defined as a meaningful name given to a data storage location in computer
memory. Variable actually refer to address of the memory where the data is stored.
C language supports two basic kinds of variables—numeric and character.
a) Numeric Variables: Numeric variables can be used to store cither integer values or
floating point values. It can also be associated with modifiers like short, long, signed,
unsigned.
b) Character Variables: Character variables are just single characters enclosed within
single quotes, These characters could be any character from the ASCII character set—
letters (‘a’, ‘A’), numerals (‘2’), or special characters (‘&’).
Declaration of variables:
• Each variable to be used in the program must be declared.
• To declare a variable, specify the data type (specifies what kind of value a variable will
store) of the variable followed by its name.
• In C, variable declaration always ends with a semicolon, for example:
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;
Initialization of variables:
• While declaring variables, we can also initialize them with some value. For example,
int emp_num = 7;
float salary = 2156.35;
char grade = ‘A’;
double balance_amount = 100000000;
• The initializer applies only to the variable defined immediately before it, Therefore, the
statement
“int count, flag = 1;” initializes the variable flag and not count.
• When variables are declared but not initialized they usually contain garbage values.
Input/Output Statement in C:
➢ printf() [Output Statement]:
▪ The printf function (stands for print formatting) is used to display information
required by the user and also prints the values of the variables.
▪ The printf function takes data values, converts them to a text stream using
formatting specifications in the control string and passes the resulting text
stream to the standard output.
▪ The syntax of printf() is as given below:
printf ("control string", variable list);
Control String: C string that contains the text that has to be written on to the
standard output device. As part of control string printf() the function can have
as many additional arguments (known as format specifiers) as specified in the
prototype.
BIT, Bengaluru - 04 11
Principles of Programming Using C BPOPS103
➢ scanf() [Input statement]:The scanf() function stands for scan formatting and is used to
read formatted data from the keyboard.
The scanf function takes a text stream from the keyboard, extracts and formats data from
the stream according to a format control string and then stores the data in specified program
variables,
The syntax of the scanf() function can be given as:
scanf("control string", argl, arg2, arg3,……., argn);
Control string specifies the type and format of the data that has to be obtained from the
keyboard and stored in the memory locations pointed by arguments arg1, arg2,.., argn, i.e,,
the arguments are actually the variable addresses where each piece of data is to be stored.
BIT, Bengaluru - 04 12
Principles of Programming Using C BPOPS103
Sample Programs:
Program 1
Simulation of a Simple Calculator.
Algorithm: To implement Commercial calculator.
Step 1: Start
Step 2: [Enter first number]
read num1
Step 3: [Enter Second number]
read num2
Step 4: [Enter Choice]
read choice
Step 5: [To perform addition]
if choice is equal to plus
add num1 and num2
print result
Step 6: [To perform subtraction]
if choice is equal to minus
subtract num2 from num1
print result
Step 7: [To perform multiplication]
if choice is equal to
multiplication multiply num1 and num2
print result
Step 8: [To perform division]
if choice is equal to division
divide num1 by num2
print result
Step 9: [To perform Modulus]
if choice is equal to modulus
divide num1 by num2
print result (remainder)
Step 10: Stop
Source Code:
#include<stdio.h>
void main()
{
float sum, sub, mul, div, a, b;
int choice,mod;
printf("Enter the values of a&b\n");
scanf("%f%f", &a,&b);
printf("Enter 1 for Addition,\n2 for Sutraction,\n3 for Multiplication,\n4 for Division,\n5 for
Mod\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("addition\n");
printf(“sum of %d and %d is:”, a,b);
sum=a+b;
printf("%f ",sum);
break;
case 2: printf("subtraction\n");
printf(“Difference of %d and %d is:”, a,b);
sub=a-b;
printf("%f",sub);
break;
case 3: printf("Multiplication\n");
printf(“Product of %d and %d is:”, a,b);
mul=a*b;
printf("%f",mul);
break;
case 4: printf("Division\n");
if(b==0)
printf("Divide by zero error! please enter non-zero number");
else
{
printf(“Division of %d and %d is:”, a,b);
div=a/b;
printf("%f",div);
}
break;
case 5: printf("Modulus\n");
if(a<b)
mod=a;
else
mod=(int)a%(int)b;
printf(“Modulus of %d and %d is:”, a,b);
printf("%d",mod);
break;
Department of CS&E, BIT 15
Principles of Programming Using C BPOPS103
Sample Outputs:
1. Enter the values of a & b
53
Enter 1 for Addition,
2 for Sutraction,
3 for Multiplication,
4 for Division,
5 for Mod
1
addition
sum of 5 and 3 is 8.000000
2. Enter the values of a&b
42
Enter 1 for Addition,
2 for Sutraction,
3 for Multiplication,
4 for Division,
5 for Mod
4
Division
Division of 4 and 2 is 2.000000
Program 2
Compute the roots of a quadratic equation by accepting the coefficients. Print
appropriate messages.
Algorithm: To compute all possible roots of the quadratic equation
Step 1: Start
Step 2: [Input the values of a, b, c]
read a, b, c
Step 3: [Calculate the determinant]
determinant = b*b-4*a*c
Step 4: [Check for validity]
If a is equal to 0 and b is equal to 0
print “Invalid Inputs”
Step 5: [Check for different roots]
If a is equal to 0
print “Linear equation”Root1=-c/b
print “Root1”
Step 6: [Check for real and equal roots]
If determinant is equal to 0
print “Roots are real and equal”
Root1= -b/(2*a)
Root2 = -b/(2*a)
Print “Root1 & Root2”
Step 7: [Check for real and distinct roots]
If determinant is greater than 0
Then print “Roots are real and distinct”
Root1= (-b+ (sqrt (fabs (determinant))))/(2*a)
Root2= (-b-(sqrt (fabs (determinant))))/(2*a)
Print “root1 and root2”
End if
Step 8: [Check for imaginary roots]
print “Roots are imaginary”Real=-b/ (2*a)
Imaginary=sqrt (fabs (determinant))/ (2*a)
print “Root1 and Root2”
Step 9: Stop
Source Code
#include<stdio.h>
#include<math.h>
void main()
{
float a, b, c, disc, re, img, x1, x2;
printf("Enter thevalues for a,b,c\n");
scanf("%f%f%f", &a, &b, &c);
if((a==0)&&(b==0))
{
printf(“Roots cannot be determined\n”);
}
else if(a==0)
{
printf(“Linear Equation\n”);
x1=-c/b;
printf(“Root1=%.3f\n”,x1);
}
else
{
disc=b*b-(4*a*c);
if(disc==0)
{
x1=x2=-b/(2*a);
printf("Roots are equal\n");
printf("x1=%f\n x2=%f",x1,x2);
}
else if(disc>0)
{
x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
printf("Roots are real and distinct\n");
printf("x1=%f \nx2=%f",x1,x2);
}
else
{
re=-b/(2*a);
img = sqrt(fabs(disc))/(2*a);
printf("Roots are imaginary\n");
printf("x1 =%f+%fi\n",re,img);
printf("x2=%f-%fi\n",re,img);
}
}
}
Sample Output:
Note: Use “-lm” option for compiling if “math.h” library has been included
Program 3
Find the Armstrong Number between 1 to 1000.
Step 1: Start
Step 2: [Declare the variables of type int] I, sum, num, count
Step 3: for i 1 to 1000
count ← log10(i) + 1
num ← i
sum ← 0
loop till num != 0
sum ← (num%10) ^ count
num ← num / 10
if sum ← i
print i
end if
count ← 0
Step 4: Stop
Source code
#include<math.h>
#include<stdio.h>
void main()
{
int i, sum, num, count = 0;
printf("Armstrong number between 1 and 1000 are:\n");
Sample Output:
Program 4:
Display the pascal triangle by reading the numbers of rows as input,
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
-----------------------------------------------------------------------------
nth row
Step 1: Start
Step 2: [Input the number of rows to display]
Read n
Step 3: for i 0 to n
for j 1 to n-1
print “ “
for j 1 to i
print ”j”
for j i-1 to 1
print ”j”
Start 4: Stop
Source code
#include <stdio.h>
void main()
{
int i,j,n;
printf("Input number of rows : ");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
/* print blank spaces */
for(j=1;j<=n-i;j++)
printf(" ");
/* Display number in ascending order upto middle*/
for(j=1;j<=i;j++)
printf("%d",j);
/* Display number in reverse order after middle */
for(j=i-1;j>=1;j--)
printf("%d",j);
printf("\n");
}
}
Sample Output:
Program 5:
Implement Binary Search on Integers .
Algorithm: To search a key element using Binary search
Step 1: Start
Step 2: Initialize found 0
Step 3: [Input the number of elements]
read n
Step 4: [ Input the array items]
for i 0 to n-1
read a[i]
end for
Step 5: [Input the key]
read key
Step 6: [Initialize low to zero and high to last element]
Low 0
Highn-1
Step 7: [Calculate mid element and compare with key]
while(low<=high && !found)
mid (low+high)/2
if a[mid] = key then
found 1
goto step 7
else if a[mid]<key then
lowmid+1
else
highmid-1
end if
end while
Step 8: [Print a message for successful or not successful]
if found ==1 then
print “search successful, print in mid+1 location”
else
print “search unsuccessful key not present in the list”
endif
Step 9: Stop
Source Code:
#include<stdio.h>
#include<string.h>
void main()
{
int a[10], key, n, i, low, high, mid, found=0;
printf(“Enter the number of elements to read, n=”);
scanf(“%d”,&n);
printf(“Enter the elements in ascending order\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter the key to search\n”);
scanf(“%d”,&key);
low=0;
high=n-1;
while(low<=high&&!found)
{
mid=(low+high)/2;
if(a[mid]==key)
found=1;
else if(a[mid]<key)
low=mid+1;
else
high=mid-1;
}
if(found==1)
printf(“Key found in position:%d”,mid+1);
else
printf(“Key not found”);
}
Sample Output:
Program 6
Implement Matrix multiplication and validate the rules of multiplication.
Algorithm: To compute product of two matrices
Step 1: Start
Step 2: [input order of matrix A]
read m, n
Step 3: [input order of matrix B]
read p, q
Step 4: [check for compatibility]
if(n!=p)
print “multiplication not possible”
go to step 11
end if
Step 5: [input elements of matrix A]
for i0 to m-1
for j0 to n-1
read a[i][j]
end for
end for
Step 6: [input elements of matrix B]
for i0 to p-1
for j0 to q-1
read b[i][j]
end for
end for
Step 7: [find product of 2 matrices]
for i0 to m-1
for j0 to q-1
c[i][j]0;
for k0 to n-1
c[i][j]c[i][j]+a[i][k]*b[k][j]
end for
end for
end for
Step 8: [print matrix A]
for i0 to m-1
for j0 to n-1
print a[i][j]
end for
end for
Step 9: [print matrix B]
for i0 to p-1
for j0 to q-1
print b[i][j]
Department of CS&E, BIT 26
Principles of Programming Using C BPOPS103
end for
end for
Step 10: [print resultant matrix C]
for i0 to m-1
for j0 to q-1
print c[i][j]
end for
end for
Step 11: Stop
Source code:
#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p,q;
printf("Enter the order of matrix A\n");
scanf("%d %d",&m,&n);
printf("Enter the order of matrix B\n");
scanf("%d %d",&p,&q);
if(n!=p)
{
printf("Matrix multiplication not possible\n");
}
else
{
printf(“enter the values for matrix A\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;i++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the values for matrix B\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
Department of CS&E, BIT 27
Principles of Programming Using C BPOPS103
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf(“the elements of matrix A\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("The elements of matrix B\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
printf("The resultant matrix C\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
}
Sample Output:
Program 7
Compute sin(x)/cos(x) using Taylor series approximation. Compare your result
with the built-in library function. Print both the results with appropriate
inferences.
Algorithm: To compute sin(x) using Taylor series
Step 1: Start
Step 2: Input value of degree; Read degree
Step 3: [Convert degree to radians]
x=(degree *PI)/180
Step 4: [Initialise]
term =x
sum=term
Step 5: [Calcuate each term and add]
term=-term*x*x/((i-1)*i);
sum=sum+term;
Step 6: [Print the output]
Print the sine value for the given degree
Step 7: Stop
Source code:
#include<stdio.h>
#include<math.h>
void main()
{
int degree,i=2;
double x,nume,denom,sum=0,term;
printf("Enter the value of degree\n");
scanf("%d",°ree);
x=(degree*3.142)/180;
nume=x;
denom=1;
do
{
term=nume/denom;
nume=- nume*x*x;
denom=denom*i*(i+1);
sum=sum+term;
i=i+2;
}
while(fabs(term)>0.00001);
printf("without using library functions in(%d)=%lf",degree,sum);
printf("\nUsing the library functions in(%d)=%lf",degree,sin(x));
}
Sample Output:
Program 8
Sort the given set of N numbers using Bubble sort.
Algorithm: To sort N integer numbers using Bubble sort
Step 1: Start
Step 2: [Input the number of elements]
read n
Step 3: [Input unsorted elements in array]
for i0 to n-1
read a[i]
Step 4: [Output the original elements]
for i0 to n-1
print a[i]
Step 5: [Sort the elements in ascending order]
for i 0 to n-1
for j0 to n-i
if a[j] > a[j+1] then
temp a[j]
a[j] a[j+1]
a[j+1] temp
end if
end for
end for
Step 6: [Output the sorted elements]
for i0 to n-1
print a[i]
Step 7: Stop
Source code:
#include<stdio.h>
void main()
{
int a[10],n,i,j,temp;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the values\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("The original elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\nThe sorted elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
Sample Output:
Program 9
Write functions to implement string operations such as compare, concatenate and
string length. Use the parameter passing parameters.
Algorithm: To implement the string operations
Step 1: Start
Step 2: [Store two strings in Str1 and Str2]
Str1=String1 and Str2=String2
Step 3: [To find String Length]
initialize i to 0
while(str[i] not equal to 0)
increment i by 1
Step 4: [To Compare two Strings]
initialize i to 0
while (str1[i] is equal to str2[i])
if (str1[i] is equal to null)
break;
increment i by 1
return str1[i]-str2[i];
Step 5: [To Concatenate two Strings]
initialize i to 0 and j to 0
while (str1[i] not equal to null)
increment i by 1
while (str2[j] not equal to null)
str1[i++]=str2[j++];
Step 6: [Output the results]
The length of the String
res1=Comparison of two Strings
res2= Concatenated String
Step 7: stop
Source Code
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void stringcompare(char s1[ ],char s2 [])
{
int l1=0,l2=0,i,p=0;
l1=strlen(s1);
l2=strlen(s2);
if(l1!=l2)
{
p=1;
}
else
{
for(i=0;s1[i]!='\0';i++)
{
if(s1[i]!=s2[i])
p=1;
}
}
if(p==1)
printf("strings are different\n");
else
printf("Strings are same\n");
}
s1[i]='\0';
printf("Concatenated string is : ");
printf("%s\n",s1);
}
void main()
{
char s1[50],s2[50];
int choice;
printf("Enter a string\n");
scanf("%s",&s1);
printf("Enter another string\n");
scanf("%s",&s2);
printf("Enter\n1 for comparing,\n2 for length,\n3 for concatenation\n");
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("Strings compared\n");
stringcompare(s1,s2);
break;
case 2 : printf("Strings length\n");
printf("For first string\n");
stringlength(s1);
printf("For second string\n");
stringlength(s2);
break;
case 3 : printf("String concatenation\n");
stringconcatinate(s1,s2);
break;
default:printf("Invalid input\n");
}
}
Sample Output:
1. Enter a string
hello
Enter another string
world
Enter
1 for comparing,
2 for length,
3 for concatenation
2
Strings length
For first string
Length of the string is 5
Department of CS&E, BIT 36
Principles of Programming Using C BPOPS103
Program 10
Implement structures to read, write and compute average- marks and the students
scoring above and below the average marks for a class of N students.
Algorithm: To read, write and compute average- marks and the students scoring above and below the
average marks for a class of N students using structures
Step 1: Start
Step 2: [input number of students]
Read n
Step 3: [input details of students ie.name and marks]
Read name,m1,m2,m3
Step 4: [ Calculate total and average]
fori=0 to n
s[i].total=(s[i].m1+s[i].m2+s[i].m3);
T=T+s[i].total;
AVG=T/N;
Step 5: [Find students above and below average]
for i0 to n
Above avg[j]=i;
j++;
else
below avg[k]=i;
k++;
Step 6: Stop
Source Code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student
{
char usn[10],name[20];
int marks;
};
void main()
{
struct student s[100];
int n,i;
float sum=0.0,avg;
printf("Enter the number of students\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the student %d details\n",i);
printf("Enter USN:");
scanf("%s",&s[i].usn);
printf("Enter Name:");
scanf("%s",&s[i].name);
printf("Enter marks:");
scanf("%d",&s[i].marks);
sum=sum+s[i].marks;
}
avg=sum/n;
printf("Class Average is %f\n",avg);
printf("Details of students scoring above class average\n");
printf("USN\tName\tMarks\n");
for(i=1;i<=n;i++)
{
if(s[i].marks>avg)
printf("%s\t%s\t%d\n",s[i].usn,s[i].name,s[i].marks);
}
printf("Details of students scoring below class average\n");
printf("USN\t Name\t Marks\n");
for(i=1;i<=n;i++)
{
if(s[i].marks<avg)
printf("%s\t%s\t%d\n",s[i].usn,s[i].name,s[i].marks);
}
}
Sample Output:
Program 11
Compute the sum, mean and standard deviation of all elements stored in an array
of N real numbers using pointers.
Algorithm: To find sum, mean and standard deviation for ‘n’ number of elements
Step 1: Start
Step 2: [Input the no. of elements]
Read n
Step 3: [Input the ‘n’ number of elements]
for i0 to n-1
read a[i]
end for
Step 4: [Assign the array elements to pointer ‘ptr’]
Ptra
Step 5: [Calculate sum]
for i0 to n-1
sumsum+ptr[i]
end for
Step 6: [Calculate mean]
Meansum/n
Step 7: [Calculate sumstd]
for i0 to n-1
sumstdsumstd + pow((pow(ptr[i]-mean),2)
end for
Step 8: [Calculate standard deviation std]
Stdsqrt(sumstd/n)
Step 9: [Output sum,mean and standard deviation]
print sum,mean,std
Step 10: Stop
Source Code
#include<stdio.h>
#include<math.h>
void main()
{
float a[10],*ptr, mean, std,sum=0,sumstd=0;
int i,n;
printf("enter the no of elements\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+ptr[i];
}
mean=sum/n;
for(i=0;i<n;i++)
{
sumstd=sumstd+pow((ptr[i]-mean),2);
}
std=sqrt(sumstd/n);
printf("sum=%.3f\n",sum);
printf("mean=%.3f\n",mean);
printf("standard deviation=%.3f\n",std);
}
Sample Output:
Program 12
Copy a text file to another file, read both the input file name and target file name.
Algorithm: To copy a text from one file to another
Step 1: Start
Step 2: enter the file to open for read
Read file1
Step 3: fopen file1 for reading
Step 4: if fptr1==null
Print “cannot open the file”
Step 5: enter the file to open for writing
Read file2
Step 6: fopen file2 for writing
Step 7: if fptr2==null
Print “cannot open the file”
Step 8: while fptr1 != EOF
fputc(c to ptr2)
c = fgetc(ptr1)
Step 9: print “content copied”
Step 10: fclose fptr1;
fclose fptr2;
Step 11: Stop
Source Code
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
c = fgetc(fptr1);
while (c!= EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename); fclose(fptr1);
fclose(fptr2);
return 0;
}
Sample Output: