0% found this document useful (0 votes)
33 views60 pages

22bpops103 203 Lab Manual

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

22bpops103 203 Lab Manual

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

Principles of Programming Using C (BPOPS103)

Visvesvaraya Technological University


“Jnana Sangama”, Belagavi-590 018

************************************************
APS College of Engineering
Somanahalli, Kanakapura Road, Bangalore-82
Department of Computer Science and Engineering

First Year B.E. (2022 Scheme) Principles of


programming using C BPOPS103
Programming assignments

Name

USN

Section

Lab Batch

Day / Time

************************************************

APSCE, Dept. of CSE 2022-23


Principles of Programming Using C (BPOPS103)

Lab Program 1: 1 Simulation of a Simple Calculator.


Objective: To understand the decision making constructs and arithmetic operators to simulate a
commercial calculator.
Input: Two numbers and operator.

Expected output: The program performs the operation based on the given operator and prints the
result of addition, subtraction, multiplication & division.
Algorithm

Step1: [Begin]
Start
Step 2: [Input two numbers]
Read num1, num2
Step 3: [Input operator]
Read operator
Step 4: [Switch to the relevant case]
case ‘+’: result num1+num2
display result
goto step 4
case ‘-’: result num1-num2
display result
goto step 4
case ‘*’: result num1*num2
display result
goto step 4
case ‘/’: if(num2!=0)
result num1/num2
display result
else
div 1
end if
goto step 4
default: Display “ Error in Operation”

APSCE, Dept. of CSE 2022-23


Principles of Programming Using C (BPOPS103)

goto step 4

if (div equals 1)
display “Divide by Zero Error”
end if
Step 5: [Finished]
Stop

Flowchart

APSCE, Dept. of CSE 2022-23


Program

#include<stdio.h>
void main()
{
char operator;
float num1,num2,result,div;
printf("Simulation of a Simple Calculator\
n");
printf("*********************************\n");
printf("Enter two numbers \n"); scanf("%f
%f",&num1,&num2);
printf("Enter the operator [+,-,*,/] \
n"); scanf("%s",&operator);
switch(operator)
{
case '+': result = num1 + num2;
printf("\n %5.2f %c %5.2f = %5.2f\n", num1, operator, num2,
result); break;
case '-': result = num1 - num2;
printf("\n %5.2f %c %5.2f = %5.2f\n", num1, operator, num2,
result); break;
case '*': result = num1 * num2;
printf("\n %5.2f %c %5.2f = %5.2f\n", num1, operator, num2,
result); break;
case '/': if(num2!=0)
{
result = num1 / num2;
printf("\n %5.2f %c %5.2f = %5.2f\n", num1, operator, num2, result);
}
else
{
div=1;

}
break;
default : printf("Error in operation\n");
}
if(div==1)
{
printf("Divide by Zero Error\n");
}
}

Lab Program 2: Compute the roots of a quadratic equation by accepting the coefficients. Print
appropriate messages.
Objective: To understand the decision making constructs and find the roots of a quadratic equation

Input: Three coefficients of quadratic equation ax2+bx+c=0: a, b, c

Expected output: This program computes all possible roots for a given set of coefficients with
appropriate messages. The possible roots are: Linear equation and its roots, Real & equal roots, Real &
distinct roots and Imaginary roots.
Algorithm

Step 1: [Begin]
Start
Step 2: [Input the coefficients of quadratic equation]
Read a, b, c.
Step 3:[Check if a equals 0 and b equals
0] Display “invalid Coefficients”
goto step8
Step 4: [Check if a equals 0]
Display “ Linear Equation”
root1 -c/b
display root1
goto step8
step 5: [Compute disc]
disc b*b - (4*a*c)
Step 6: [Check whether disc is equal to 0]
if disc equals 0
display “ Roots are real and equal”
compute root1 root2 -b/(2*a)
display “ root1 and root2”
goto step8
Step 7: [Check whether disc is greater than 0]
if disc greater than 0
Display “ Roots are real and distinct”
compute root1 (-b+sqrt( disc))/(2*a)
compute root2 (-b-sqrt( disc))/(2*a)
Display “ root1 and root2”
goto step8
Step 8: [Otherwise display imaginary roots]
Display “ Roots are imaginary”
compute real -b/(2*a)
compute imag sqrt(fabs( disc))/(2*a)
Display “ root1 and root2 with real and imaginary values in a+bi format”
goto step8

Step 9: [Finished]
Stop
Flowchart

Program //Program to calculate the roots of quadratic equation.

#include<stdio.h>
#include<math.h>
void main()
{ float a,b,c,disc,root1,root2,real,imag;
printf("Enter value for a : ");
scanf("%f",&a);
printf("Enter value for b : ");
scanf("%f",&b);
printf("Enter value for c : ");
scanf("%f",&c);
if((a==0)&&(b==0))
{
printf("Invalid coefficients \n");
printf("\n Try again with valid inputs");
}
else if(a==0)
{

}
else
{ printf("Linear equation\n");
root1=-c/b;
printf("Root = %.3f\n",root1);

disc=b*b-(4*a*c);
if(disc==0)
{
printf("The roots are real and equal \n");
root1=root2=-b/(2*a);
printf("Root 1 = %.3f\n Root 2 = %.3f\n",root1,root2);
}
else if(disc>0)
{
printf("The roots are real and distinct \n");
root1=(-b+sqrt(disc))/(2*a);
root2=(-b-sqrt(disc))/(2*a);
printf("Root 1 = %.3f\n Root 2 = %.3f\n ",root1,root2);
}
else

{ printf("The roots are real and imaginary\n");


real=-b/(2*a);
imag=sqrt(fabs(disc))/(2*a);
printf("Root 1 = %.3f + i %.3f\n",real,imag);
printf("Root 2 = %.3f - i %.3f\n",real,imag);
}
}
printf("\n\t\t\t Press any key to EXIT\n");
Lab Program 3: An electricity board charges the following rates for the use of electricity: for the first
200 units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per unit. All
users are charged a minimum of Rs. 100 as meter charge. If the total amount is more than Rs 400, then
an additional surcharge of 15% of total amount is charged. Write a program to read the name of the
user, number of units consumed and print out the charges.
Objective: To use decision making statements

Input: Customer name & Units consumed

Expected Output: Total amount charged for electricity consumption

Algorithm

Step 1: [Start]

Begin

Step 2: [Input customer


name] Read name
Step 3: [Input unit consumed]
Read n
Step 4: [Check units consumed to calculate the amount]
if n < = 200
calculate amount n*80

otherwise check if n > 200 and n <= 300 then calculate


amount 200 * 80
amount amount +(n-200) *90
otherwise calculate
amount (n-300)*100
amount amount+100*90
amount amount+200*80
end if

Step 5:[Calculate the amount]


amount amount/100
amount amount+100
Step 6: [Check if amount is greater than 400 then calculate additional charge of 15%]
if amount > 400 then
calculate amount amount + amount * 15/100
end
if
Step 7: [Print total amount to be paid by the customer]
Display amount
Step 8: [Finished]
Stop

Flowchart
#include<stdio.h>
void main()
{
char name[20];
int n;
float amount;
printf("Enter the consumer name\n");
scanf("%s", &name);
printf("Enter no. of units consumed \n");
scanf("%d",&n);
if (n<=200)
{
amount=n*80;
}
else if(n>200 && n<=300)
{
amount=200*80;
amount=amount+(n-200)*90;
}
else
{
amount=(n-300)*100;
amount=amount+100*90;
amount=amount+200*80;
}

amount=amount/100; //To convert into Rupees


amount=amount+100; // Additional 100 Rupees to be added
if(amount>400)
{
amount=amount+amount*15/100;
}
printf("Total amount to be paid is %.2f Rs\n",amount);
}
Lab Program 4 Write a C Program to display the following by reading the number of rows as input,
1
121
12321
1234321

#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");
}
}
Lab Program 5 Implement Binary Search on Integers
Start

Step 2: [Input number of names to be read]


Read n
Step 3: [Input the number in ascending
order]for i 0 to n do
Read name[i]

end for

Step 4: [Input the name to be searched]


Read key
Step 5: [Initialize]

low 0
high n-1
Step 6: [Do until low<=high]

Check while (low <= high) do


mid (low+high)/2
check if (strcmp (name[mid], key)==0) true
display name and its position
exit 0

else check if (strcmp (name[mid], key) < 0 ) true


low mid+1
else
high mid-1
end
if end while

Step 7: [Print name not found]


Display “number not
found”

Step 8: [Finished]
Stop
Program

#include<stdio.h>
#include<string.h>
#include <stdlib.h>
void main()
{
Int number[10]
[20],key[20]; int
n,i,low,high,mid;
printf("\nEnter the number of names to read : ");
scanf("%d",&n);
printf("\nEnter the number in ascending order
\n");for(i=0;i<n;i++)
scanf("%s",&number[i]); printf("\
nEnter the number to be searched :
");scanf("%s",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if (strcmp(number[mid],key)==0)
{
printf("\nnumber found in position :
%d\n",mid+1);exit (0);
}
else if(strcmp(number
[mid],key)<0)low=mid+1;

else
}

high=mid-1;
printf("\n Number not found. \n");
}
Lab Program 6 Implement Matrix multiplication and validate the rules of multiplication
Objective: To find the product of two matrices

Input: Two matrices A(m x n) and B(p x q)

Expected Output: C(m x q) (Product of matrix A and B)

Algorithm

Step1: [Initialize]

Start

Step 2: [Input the no. of rows and columns of matrix a]


Read m and n
Step 3: [Input the no. of rows and columns of matrix b]
Read p and q
Step 4: [Check the compatibility for multiplication of matrices a and b] if(n!
=p) true
display “Matrix multiplication not possible as Columns of A not equal to Rows of B”
goto step 11
otherwise
goto step 5
end if
Step 5: [Input the elements of matrix a in row major order]
for i 0 to i<m in step 1 do
for j 0 to j<n in step 1 do
read a[i][j]
end for

end for

Step 6: [Input the elements of matrix b in column major order]


for j 0 to j<q in step 1
for i 0 to i<p in step 1

read b[i][j]

end for

end for
Step 7: [Perform multiplication of matrix a and b]

for i 0 to i<m in step 1 do

for j 0 to j<q in step 1 do


c[i][j] 0
for k 0 to k<n in step 1 do
c[i][j] c[i][j]+a[i][k]*b[k][j]
end for

end for
end for
Step 8: [Print matrix A]

for i 0 to i<m in step 1 do

for j 0 to j<n in step 1 do


display a[i][j]
end for

end for

Step 9: [Print matrix B]

for i 0 to i<p in step 1 do

for j 0 to j<q in step 1 do


display b[i][j]
end for

end for

Step 10: [Print resultant matrix C]

for i 0 to i< m in step 1

do

for j 0 to j<q in step 1 do


display c[i][j]
end for
end for
Step 11: [Finished]
APSCE, Dept. of CSE 2022-23
Stop

APSCE, Dept. of CSE 2022-23


Flowchart

APSCE, Dept. of CSE 2022-23


#include<stdio.h>
void main()
{
int m,n,p,q,i,j,k,a[10][10],b[10][10],c[10][10];
printf("\n Enter the number of rows & columns of matrix A : "); scanf("%d
%d",&m,&n);
printf("\n Enter the number of rows & columns of matrix B : "); scanf("%d
%d",&p,&q);
if(n!=p)
{

}
else
{
printf("Matrix multiplication not possible as Columns of A not equal to Rows of B.\n");

printf("\t\t Enter elements for matrix A in Row Major order\n");for(i=0;i<m;i++)


{

for(j=0;j<n;j++)
{
printf("Enter the element for A[%d][%d] : ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\t\t Enter elements for matrix B in Column Major order.\n");
for(j=0;j<q;j++)
{
for(i=0;i<p;i++)
{

APSCE, Dept. of CSE 2022-23


printf("Enter the element for B[%d][%d] : ",i,j);
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0; for(k=0;k<n;k+
+)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf(" The Matrix A is : \n ");
for(i=0;i<m;i++)

{
for(j=0;j<n;j++)
{
printf(" %d \t",a[i][j]);
}
printf("\n ");
}
printf("The Matrix B is : \n ");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf(" %d \t",b[i][j]);
}
printf("\n ");
}
APSCE, Dept. of CSE 2022-23
printf(" The multiplied Matrix C is :\n ");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf(" %d \t",c[i][j]);
}
printf("\n ");
}
}
printf(" \n \t\t....Press Any Key to EXIT ... \n\n");
}

Lab 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.
Objective: To understand the implementation of sin(x) series using Taylor series

Input: Integer number degree

Expected Output: Sin(x), where x is the value of degree in radian

Algorithm
Step 1: [Begin]
Start
Step 2: Set pi to 3.142
Step 3: [Initialize sum to 0]
Sum 0
Step 4: [Input
degree]
Read degree
Step 5: [Convert degree to
radian] x
degree*(pi/180)
Step 6: [Assign x value to numerator]
nume x

APSCE, Dept. of CSE 2022-23


Step 7: [Set denominator to 1]
deno 1

APSCE, Dept. of CSE 2022-23


Step 8: [Set i to 2]

i 2
Step 9: [Repeat until true]
term nume/deno
nume -nume *x*x
deno deno * i * (i+1)
sum sum+term
i i+2
do until while (fabs(term)>=0.00001)
Step 10: [Print sin of degree]
Display sum
Step 11: [Print sin(degree) using built-in function for comparison]
Display sin(x)
Step 12: [Finished]
Stop

Flowchart

APSCE, Dept. of CSE 2022-23


Program

#include <stdio.h>
#include <math.h>
#define pi 3.142
void main()
{
int i,degree;
float x,sum=0,term,nume,deno;
printf("\n Enter the value of degree : ");
scanf("%d", &degree);
x=degree*(pi/180);
nume=x;
deno=1;
i=2;
do
{
term=nume/deno;
nume=-nume*x*x;
deno=deno*i*(i+1);
sum=sum+term;
i=i+2;
}while(fabs(term)>=0.00001);
printf("\n The sine of %d is %f",degree,sum);
printf("\n The sine of %d using inbuilt function sin(%d) is %f",degree,degree,sin(x)); printf("\
nPress any key to EXIT...\n");

Lab Program 8 Sort the given set of N numbers using Bubble sort.

APSCE, Dept. of CSE 2022-23


Objective: To demonstrate NESTED FOR loop.

Input: Number of Elements-n

Output: An array of sorted elements –a[ ]

Expected Output: An array of sorted elements –a[ ]

Algorithm

Algorithm: Bubble sort technique to sort N integer numbers in to ascending order.


Step 1: [Start]
Begin
Step 2: [Input the number of elements in the array]
Read n
Step 3: [Input the n integer numbers]
For i 0
to n-1 in steps of
1 Read num[i]
End for
Step 4: [Display the original array]
For i 0 to n-1 in steps of
1
Print num[i]
End for
Step 5: [Repeat step 5 for i varies from 0 thru n-
1]For i 0 to n-1 in steps of 1
For j 0 to n-i-1 in steps of 1
IF (num [j] > num [j + 1]) then
temp= num[j]
num[j] = num[j + 1]
num[j+1] = temp
End if
End for
End for
Step 6: [Output the sorted array]

APSCE, Dept. of CSE 2022-23


For i 0 to n-1 in steps of
1
Print num[i]

APSCE, Dept. of CSE 2022-23


End for
Step 7: [Stop]
End

Flowchart
Program

#include<stdio.h>
int main()
{
int num[20],n,i,j,temp;
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter the numbers one by one: ");
for(i=0;i<n;i++)
scanf("%d",&num[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(num[j]>num[j+1])
{
temp=num[j];
num[j]=num[j+1];
num[j+1]=temp;
}
}
}
printf("The Sorted items are: \n");
for(i=0;i<n;i++)
printf("%d\t",num[i]);
printf("\n");
return 0;
}
Lab Program 9 Write functions to implement string operations such as compare, concatenate, and find
string length. Use the parameter passing techniques.
Objective: To compare two strings, to concatenate two strings and to find string length using
functions.
Input: Choice of the user to perform string operations and two strings.

Output: Based on users choice programs outputs two strings and displays whether they are equal or
not, programs concatenates two strings, programs finds the length of the given string.

Algorithm: Find String


LengthStep 1: Function
stringlength()
Start
Step 2: [Initialize]
Length = 0
Step 3: [Compare whether character is not NULL]
Repeat step 4 while S [Length] ≠ NULL
Step 3: [Increment Length]
Length = Length + 1
Step 4: [Print Length of the given string]
Display Length

Algorithm: Concatenate two strings


Step 1: Function concatenation (p,q)
Start
Step 2: [Initialize]
Length1 = 0, Length2 = 0
Step 3: [Compare whether character is not NULL]
Repeat step 4 while S1 [Length1] ≠ NULL
Step 4: [Increment Length]
Length1 = Length1 + 1
Step 5: [Compare whether character is not NULL]
Repeat step 5 while S2 [Length2] ≠ NULL
Step 6: [Assign character from S2 to S1 & Increment length1, length2]
S1 [Length1] = S2 [Length2]
Length1 = Length1+1
Length2 = Length2+1
Step 7: [Assign Null as last character]
S1 [Length1] = NULL
Step 8: Return

Algorithm: Comparison of two strings


Step 1: [Initialize]
i=0;
Step 2: [Compare whether characters are same]
Repeat step 3 while S1 [i] = S2 [i]
Step 3: [Compare if any string reached end]
if S1 [i]=NULL OR S2 [i]=NULL then
goto Step 4

else

endif

i=i+1

Step 4: [Compare last character of each string]


if S1 [i]=NULL AND S2 [i]=NULL then
return 0
else

return -1

endif
Flowchart

Program

#include <stdio.h>
void stringlength(char []);
void concatenate(char [], char []);
int stringcmp(char [], char []);

int main()
{
char p[100], q[100],temp;
int choice;
printf("Enter Your Choice\n1-String Length\n2-String Concatenate\n3-String Comparision\n");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("Input a string to find its length:");
scanf("%s",p);
stringlength(p);
break;
case 2:printf("Input a string:");
scanf("%s",p);
printf("Input a string to concatenate:");
scanf("%s",q);
concatenate(p, q);
printf("String obtained on concatenation: \"%s\"\n", p);
break;
case 3:printf("Comparision of two strings\n");
printf("Input string1\n");
scanf("%s",p);
printf("Input string2 \n");
scanf("%s",q);
if (stringcmp(p,q) == 0)
printf("The strings are equal.\n");
else
printf("The strings are not equal.\n");
break;
default: printf("Invalid Choice");
}
return 0;
}
void stringlength(char p[])
{
int len=0;
while (p[len] != '\0')
len++;
printf("The Length of the given String is %d\n",len);
}
void concatenate(char p[], char q[])
{
int c, d;
c = 0;
while (p[c] != '\0')
{
c++;
}
d = 0;
while (q[d] != '\0')
{
p[c] = q[d]; d+
+;
c++;
}
p[c] = '\0';
}

int stringcmp(char a[], char b[])


{
int i = 0;
while (a[i] == b[i]) {
if (a[i] == '\0' || b[i] == '\0')
break;
i++;
}

if (a[i] == '\0' && b[i] == '\0')


return 0;

else

return -1;
Lab Program 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.

Objective: To understand the structures concept.

Input: Students Details- rollno, name & marks

Expected Output: Average marks of the student, students scoring above & below the average marks.

Algorithm

Algorithm:
Step 1: [Initialize]
Total_marks=0
Step 2: [Read number of students]
Read n
Step 3: [Input the n Students details-rollno,name&marks]
For i
0 to n-1 in steps of 1
Read s[i].rollno,s[i].name,s[i].marks
End for
Step 4: [Find average marks]
For i 0
to n-1 in steps of 1
Total_marks=Total_marks+1
End for
Avg=Total_marks / n

Step 5: [Students scoring above average marks]


For i
0 to n-1 in steps of 1
if s[i].marks>=Avg
print “Student Details”
End for

Step 6: [Students scoring below average marks]


For i 0
to n-1 in steps of 1
APSCE, Dept. of CSE 2022-23
i
f

s
[
i
]
.
m
a
r
k
s
<
A
v
g

APSCE, Dept. of CSE 2022-23


print “Student Details”
End for
Step 7:
[Finished]
STOP

Flowchart
Program

#include<stdio.h>
struct student
{
int rollno,marks;
char name[20];
};
int main()
{
int i,n;
float total=0,avg;
struct student s[10];
char sname[20];
printf("\n Enter the number of students : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter details of student %d ",i+1);
printf("\n\n Enter the roll number : ");
scanf("%d",&s[i].rollno);
printf("\n Enter the name: ");
scanf("%s",s[i].name);
printf("\n Enter the marks : ");
scanf("%d",&s[i].marks);
total=total+s[i].marks; printf("\
n");
}
avg=total/n;
printf("\nThe average marks is %f\n",avg);
printf("\n Details of students scoring above average marks are : \n\n");
printf("\n Roll no.\tName\t\tMarks\n");
for(i=0;i<n;i++)
{
if(s[i].marks>=avg)
printf("\n %d\t\t%s\t\t%d\n",s[i].rollno,s[i].name,s[i].marks);
}
printf("\n Details of students scoring below average marks are : \n\n");
printf("\n Roll no.\tName\t\tMarks\n");
for(i=0;i<n;i++)
{
if(s[i].marks<avg)
printf("\n %d\t\t%s\t\t%d\n",s[i].rollno,s[i].name,s[i].marks);
}
return 0;

Lab Program 11 Develop a program using pointers to compute the sum, mean and standard deviation of
all elements stored in an array of N real numbers.

Mean: is the average of the numbers. i.e. the sum of a collection of numbers divided by the number of
numbers in the collection
Standard deviation (SD): measure the amount of variation or dispersion from the average. For a finite
set of numbers, the standard deviation is found by taking the square root of the average of the squared
differences of the values from their average value.

Objective: To demonstrate the use of pointers.

Input: No. of elements n, array of elements a[ ]

Expected Output: Compute and display sum, mean & standard deviation

Algorithm

Step 1: [Start]
Begin
Step 2:
[Initialize]
sum=0, sumstd=0
Step 2: [Input the number of elements in the array]
Read n
Step 3: [Input the n real numbers]
0
For i
to n-1 in steps of 1
Read a[i]
End for
Step 4: [Compute sum, mean, standard deviation]
ptr=a
For i←0 thru n in steps of 1
Sum=sum+*ptr
ptr++
End for
Mean=sum/n
ptr=a
For i←0 thru n in steps of 1
sumstd=sumstd+pow((*ptr-mean),2)
ptr++
End for
std= sqrt(sumstd/n)
Step 5: [Output]
Print sum, mean, standard deviation
Step 6: [Stop]
End
Princip les of Progamming Using C (BPOPS103)

Flowchart

Read run. a(i)

sum=O,sumstd=-0
Plr-a

Fa For ( Tr
sum=sum+
mean=s i
lse 0 ;i<n;i+
ue
'PIT
+)wnn
ptr-a1
ptr-ptr+

F sumstd=sumst
std
For
al d +(<n;i++)
i=O ;t
sqrt(su
pow(\ptr -
s mstdln)
mean),2)
e Print
ptr-ptr+1
sum.mean,
standard
deviation

APSCE, Dept. of CSE 2022-23


Principles of Programming Using C (BPOPS103)

Program

#include<stdio.h>
#include<math.h>
void main()
{
float a[10], *ptr, mean, std, sum=0, sumstd=0;
int n,i;
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;
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0;i<n;i++)
{
sumstd=sumstd + pow((*ptr - mean),2);
ptr++;
}
std= sqrt(sumstd/n); printf("Sum=%.3f\
t",sum); printf("Mean=%.3f\t",mean);
printf("Standard deviation=%.3f\n",std);

APSCE, Dept. of CSE 2022-23


Principles of Programming Using C (BPOPS103)

Lab Program 12. Write a C program to copy a text file to another, read both the input file name and
target file name.

#include <stdio.h>
#include <stdlib.h> // For exit()

int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;

printf("Enter the filename to open for reading \n");


scanf("%s", filename);

// Open one file for reading


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

// Open another file for writing


fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

// Read contents from file

APSCE, Dept. of CSE 2022-23


Principles of Programming Using C (BPOPS103)

c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}

printf("\nContents copied to %s", filename);

fclose(fptr1);
fclose(fptr2);
return 0;
}

INTRODUCTION

OPERATING SYSTEM (OS)

An operating system is a program that controls the system’s hardware and interacts with user and
application software. The commands are translated into binary code that the machine understands. The
OS facilitates display of results on screen or printed. It manages processing, memory, devices, files and
security etc.

Some popular operating systems

Disk operating Unix / Linux Windows


system
(DOS)

APSCE, Dept. of CSE 2022-23


MS-DOS (Micro Soft disk operating system):
This is a single user single tasking operating system which was developed by Micro Soft.
Unix / Linux:
These are multi-user multitasking operating systems. These can be used for network of computers.
Windows:
This OS can be used for single user and for multi-user & multitasking purposes.
DIRECTORY: This is a list of other directories and files.

FILE: This is a record of related information.

About Linux:
Linux is an operating system, a software program that controls our computer. Most vendors
load an operating system onto the hard drive of a PC before delivering the PC, so, unless the hard
driveof our PC has failed, we may not understand the function of an operating system.
Linux is not public domain, nor is it `shareware'. It is `free' software, commonly called
freeware or Open Source Software. Linux runs on 386/486/Pentium machines. Linux is only the
kernelof the operating system, the part that controls hardware, manages files, separates processes, and
so forth. There are several combination of Linux with sets of utilities and applications to form a
complete operating system. Each of these combination is called a distribution of Linux. The word
Linux, though it in its strictest form refers specifically to the kernel, is also widely and correctly to
refer to an entire operating system built around the Linux kernel.

One thing to be aware of is that Linux is developed using an open and distributed model,
instead of a closed and centralized model like much other software. This means that the current
development version is always public, so that anybody can use it. The result is that whenever a
version with new functionality is released, it almost always contains bugs, but it also results in a very
rapid development so that the bugs are found and corrected quickly, often in hours, as many people
work to fix them.

In contrast, the closed and centralized model means that there is only one person or team
working on the project, and they only release software that they think is working well. Often this leads
to long intervals between releases, long waiting for bug fixes, and slower development. The latest
release of such software to the public is sometimes of higher quality, but the development speed is
generally much slower.

Linux Features

 Multitasking: Several programs running at the same time.

 Multiuser: Several users can use the same machine at the same time

 Multiplatform: Runs on many different CPUs.

 Multithreading: Has native kernel support for multiple independent threads of control within a
single process memory space.

Demand loads executables: Linux only reads from disk those parts of a program that are actually used.

 Shared copy-on-write pages among executables. This means that multiple process can use the same
memory to run in. When one trie7s to write to that memory, that page is copied somewhere else.
Copy-on-write has two benefits: increasing speed and decreasing memory use.

 All source code is available, including the whole kernel and all drivers, the development tools and
all user programs; also, all of it is freely distributable. Plenty of commercial programs are being
provided for Linux without source, but everything that has been free, including the entire base
operating system, is still free.

 CD-ROM file system which reads all standard formats of CD-ROMs.

 TCP/IP networking, including ftp, telnet, NFS, etc.

How Linux is Different


Linux is distinguished from many popular operating systems in three important ways.

I. Linux is a cross-platform operating system that runs on many computer models. Only Unix,
an ancestor of Linux, rivals Linux in this respect. In comparison, Windows 95 and Windows
98 run only on CPUs having the Intel architecture. Windows NT runs only on CPUs having
the Intel architecture or the DEC Alpha.

II. Linux is free, in two senses. First, We may pay nothing to obtain and use Linux. On the
other hand, we may choose to purchase Linux from a vendor who bundles Linux with
special documentation or applications, or who provides technical support. However, even
inthis case,
the cost of Linux is likely to be a fraction of what we'd pay for another operating system. So,
Linux is free or nearly free in an economic sense.

Second, and more important, Linux and many Linux applications are distributed in source
form. This makes it possible for us and others to modify or improve them. we're not free to
do this with most operating systems, which are distributed in binary form.

Example: We can't make changes to Microsoft Windows or Microsoft Word - only


Microsoftcan do that. Because of this freedom, Linux is being constantly improved and
updated, far outpacing the rate of progress of any other operating system.

Example: Linux will likely be the first operating system to support Intel's forthcoming
Merced 64-bit CPU.

III. Linux has attractive features and performance. Free access to Linux source code lets
programmers around the world implement new features, and tweak Linux to improve its
performance and reliability. The best of these features and tweaks are incorporated in the
standard Linux kernel or made available as kernel patches or applications. Not even
Microsoft can mobilize and support a software development team as large and dedicated as
the volunteer Linux software development team, which numbers in the hundreds of
thousands, including programmers, code reviewers, and testers.

LINUX COMMANDS

1.cd(Change Directory)

cd [dir]:Change the current directory to dir. The variable HOME is the default dir.

2.cd ..

To come out from the current directory.

3.mkdir (make directory)


SYNOPSIS
mkdir [directory name]

It is used to make or create a new directory.

4.ls(list directory contents)


SYNOPSIS
ls [File name]
DESCRIPTION
List information about the FILEs (the current directory by default).

5.vim (Vi IMproved, a programmers text editor)


SYNOPSIS
vim [file name]
DESCRIPTION
Vim is a text editor that is upwards compatible to Vi. It can be used to edit all kinds
of plain text. It is especially useful for editing programs.
6.:x or :wq
SYNOPSIS
:x or :wq
DESCRIPTION
To save the current file.

7. cc filename or cc -lm filename

where "cc" stands for compile current program.

option "lm" is used to link all the supporting functions(ex: pow, sqrt etc function in
math.h).

8. ./a.out

To generate a output for a program or to run a current program.

9. exit

To come out from the working window.

10. clear - To clear the screen.

11. pwd – display present working directory

12. tput clear – to clear the screen

13. Date – Displays date & Time

14. Cal – Display the current month

15. Cat – Used to display and create files.

16. cp – used to copy the files.

17. ren – used to rename the files


Editor
Linux provides an editor called vim editor to write C programs. Vim editor perates in three modes
Input mode
Command mode
Ex - mode
The input mode is used to enter the text.
The cmd mode is used to enter the commands
The Ex- mode is used for file handling & institution.

I/P Mode Ex Mode

:
esc enter
i
C
M
D

M
o
d
e

vi :
m x
,
:
She y
ll
&
^
Z
Fig 1: Switching between modes

a. i – used to switch from cmd mode to i/p mode


b. esc – used to switch from i/p mode to cmd mode
c. : - used to switch from cmd mode to Ex – mode
VIVA VOCE QUESTIONS

1. What is the output of printf(“%d”)?


2. What are the different types of storage classes?
3. Explain call by value and call by reference?
4. Why pre increment operator is faster than post increment?
5. What is the difference between calloc and malloc?
6. Can structures be passed to the functions by value?
7. Why cannot arrays be passed by values to functions?
8. What are the advantages and disadvantages of using macros over functions?
9. What is the scope of static variables?
10. What are the types of constants available in C?
11. What is the range allowed for integer constants in 16-bit computers?
12. What are the 2 ways of representing real constants?
13. What is the range for real constants expressed in exponential form?
14. What are Character constants?
15. How are Character constants treated when used in arithmetic expressions?
16. Why is C called Middle – Level Language?
17. What value does a variable assume if it is not initialized?
18. What is the default scope of if statement?
19. Which are the logical operators available in C? Why do we need them?
20. What is Conditional operator?
21. When do you use While, do-while and for loops?
22. Can you use multiple conditions in for loop?
23. What do you mean by odd loop?
24. What is the use of break statement?
25. Where do we use continue keyword?
26. Do the cases in switch statement be arranged in ascending order?
27. What is the advantage of switch over if statement?
28. Can we use expressions yielding floating point values in switch statement?
29. What is the meaning of while(1)?
30. What is a function? Why do we need them?
31. Is there any restriction on the number of times a particular function can be called?
32. What are actual arguments and formal arguments?
33. What is the use of return statement?
34. Is it possible for a function to return more than one value at a time?
35. What is the default return value of any function in C?
36. Value at address operator is also called?
37. What are pointers?
38. What is recursion? What are its applications?
39. What are the differences between recursion and iterative procedures?
40. What is a Preprocessor?
41. What is a macro?
42. What do you mean by conditional compilation?
43. Why C is called a free form language?
44. What are identifiers?
45. What are string constants?
46. What are escape sequences? Give examples.
47. Name some of the qualifiers used with the fundamental data types?
48. What is the use of comma operator in C?
49. Explain the use of sizeof() operator?
50. What do you mean by associativity property of an operator?
51. Name some of the character test functions?
52. How is left justification achieved while printing variable values?

53. What are arrays?


54. How do you initialize arrays?
55. Why is it compulsory to mention the column dimension in a 2-d array?
56. Which function is used to accept multiword strings?
57. Name some of the most commonly used string handling functions?
58. What is the difference between array of pointers to strings and 2-d array of characters?
59. What is a Structure?
60. Can a structure be assigned to another using assignment operator?
61. What are unions?
62. What are the differences between Structures and unions?
63. What are bit fields? Why are they used?
64. Can we increment or decrement pointers? If yes what actually happens?
65. What is a file?
66. What is the difference between printf() and sprintf() functions?
APSCE, Dept. of CSE 2022-23
67. What is the difference between getch() and getche()?
68. What is the difference between getchar() and fgetchar()?
69. Which are the different modes of opening a file?
70. What are command line arguments? Explain.
71. Mention the functions used in random access to files
72. What is the syntax of fseek() function?
73. Mention some of the functions used to handle the errors during I/O operations on files.
74. Mention the bitwise operators available in C
75. Can bitwise operators operate upon floats and doubles?
76. Mention the real time applications of bitwise operators.
77. What are enumerated data types?
78. What is the purpose of typedef declarations?
79. What is type casting?
80. What is dynamic memory allocation?
81. Which are the memory management functions available in C?
82. What is heap?
83. What is the difference between static and dynamic memory allocation?
84. What is the syntax of realloc ()?
85. What is searching?
86. What is sorting?
87. Where actually does the C program execution begin?
88. What is syntax error?
89. What is the difference between while loop and do-while loop?
90. What is a Computer?
91. What is CPU?
92. What is ALU?
93. What is CU?
94. What is RAM?
95. What is ROM?
96. What is PROM?
97. What is EPROM?
98. What is EEPROM?
99. Differentiate between Volatile and non-volatile memory.
100. What are the input and output devices?
APSCE, Dept. of CSE 2022-23
101. What is the need for cache memory?
102. Differentiate between main memory and second memory.
103. What is hardware?
104. Mention the different types of hardware components?
105. What are the different types of keyboards?
106. Differentiate between serial and parallel keyboard.

107. How do you classify printers?


108. Differentiate between serial and parallel printer.
109. Differentiate between impact and non-impact printers.
110. Differentiate between line and page printers.
111. Which printer do you select when high quality output is to be produced?
112. What is meant by softcopy output?
113. What is meant by hardcopy output?
114. What is printer buffer?
115. What is meant by tracks?
116. What is meant by sectors?
117. What is CD-ROM?
118. What are the different types of mouse?
119. What are the main parts of a floppy disk?
120. Differentiate between magnetic disks and optical disks.
121. What is programming?
122. What is software?
123. What are the different types of software?
124. What are the different types of programming languages?
125. Differentiate between interpreter and compiler.
126. Differentiate between loader and linker.
127. Differentiate between Application software and System software.
128. What is an operating system?
129. What are language processors?
130. Mention some operating systems.
131. Differentiae between compiler and assembler.
132. What is translator?
133. What is meant by interpretation?
APSCE, Dept. of CSE 2022-23
134. What is meant by source program?
135. What is meant by object program?
136. Give examples for High Level Languages.
137. Give examples for Assembly Level Languages.
138. Give examples for General purpose HLL.
139. Give examples for Specific purpose HLL.
140. Differentiate between Analog and Digital computers.
141. Differentiate between microcomputer & minicomputer.
142. Differentiate between internal & external DOS commands.
143. How do you classify the computers based on the size & capability?
144. How do you classify the computers based on principle of working?
145. What is computer network?
146. How do you classify the computer networks?
147. What is Batch processing?
148. What is Time Sharing?
149. Differentiate between LAN and WAN.
150. What are the different types of DOS?
151. What is DOS?
152. What is Real Time Systems?
153. What are the advantages of computer network?
154. What is BCPL?
155. Who developed BCPL?
156. Who developed B language?
157. Who developed C language?
158. How do you make comments in C program?
159. How the name C is derived?
160. What is K & R C?

161. What is preprocessor statement?


162. Differentiate between constant and variable.
163. What is data type?
164. Name the basic data types of C.
165. Differentiate between string constant and character constant.
166. What is the range of integer, char, float for a 16-bit computer?
APSCE, Dept. of CSE 2022-23
167. What is a statement?
168. What is a keyword?
169. Differentiate between keywords and identifiers.
170. What is the need for an escape sequences?
171. What is a symbolic constant?
172. How do you classify C operators?
173. What is the use of modulus operator?
174. What is meant by mixed mode operation?
175. What are bitwise operators?
176. What is unary operator?
177. What is binary operator?
178. What is typecasting?
179. What is a conditional / ternary operator?
180. What is need for type conversion?
181. Differentiate between && and &.
182. Differentiate between pre-increment/decrement & post-increment/decrement.
183. Differentiate between Unformatted and formatted i/o statements.
184. How do you classify the control statements?
185. Differentiate between while and do-while loop.
186. Differentiate between break and continue.
187. When do you prefer for loop statement?
188. What is looping?
189. What is an array?
190. Give the classification of arrays?
191. Differentiate between an array and an ordinary variable.
192. Array variable is also called as .
193. What are character arrays?
194. When do you use two-dimensional character array?
195. Name the different string handling functions?
196. What is meant by modularization?
197. Differentiate between standard functions & user-defined functions?
198. Differentiate between arguments and parameters.
199. Differentiate between local and global variables.
200. Name the different methods of parameter passing?
APSCE, Dept. of CSE 2022-23
201. How does the function definition differ from function declaration?
202. What is recursive function?
203. What is meant by scope of a variable?
204. What is a structure?
205. Differentiate between array and structure.
206. What are embedded structures?
207. How do you access the member of a structure?
208. What is union?
209. Differentiate between union and structure.
210. What is a pointer?
211. Differentiate between address operator and dereferencing operator.
212. How do you declare a pointer variable

Algorithm:
Step 1. [Initialise] Start
Step 2. [Input an integer number] Read num
Step 3. res =isprime(num)
Step 4. [Output] If (res = 1) Print(“The entered number is a prime”)
Else
Print(“The entered number is not prime”)
Step 5. [Stop] End

APSCE, Dept. of CSE 2022-23

You might also like