0% found this document useful (0 votes)
92 views

CO-102 FILE: BY:-Piyush Chouhan 2k19/a5/51

This program takes a 5 digit number as input from the user and prints the reverse of that number. It uses the modulus (%) operator to extract individual digits of the number. A while loop is used to repeatedly extract the last digit, store it, and divide the number by 10 to remove the last digit. After the loop, the stored digits will be in reverse order, giving the reversed number.

Uploaded by

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

CO-102 FILE: BY:-Piyush Chouhan 2k19/a5/51

This program takes a 5 digit number as input from the user and prints the reverse of that number. It uses the modulus (%) operator to extract individual digits of the number. A while loop is used to repeatedly extract the last digit, store it, and divide the number by 10 to remove the last digit. After the loop, the stored digits will be in reverse order, giving the reversed number.

Uploaded by

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

CO-102 FILE

BY:-
Piyush chouhan
2k19/A5/51
Program -1
AIM :
W.A.P. to calculate sum and average of 2 numbers.

DESCRIPTION :
A natural number is a number that occurs commonly and obviously in nature. As such, it is a
whole, non-negative number. The set of natural numbers, denoted N, can be defined in the
following way-
N = (1, 2, 3, 4, ...}
In colloquial language, an average is the sum of a list of numbers divided by the number of
numbers in the list. In mathematics and statistics, this would be called the arithmetic mean.
In statistics, mean, median, and mode are all known as measures of central tendency.
The arithmetic mean, often simply called the mean, of two numbers, such as 2 and 8, is
obtained by finding a value A such that 2 + 8 = A + A. One may find that A = (2 + 8)/2 = 5.
Switching the order of 2 and 8 to read 8 and 2 does not change the resulting value obtained
for A. The mean 5 is not less than the minimum 2 nor greater than the maximum 8. If we
increase the number of terms in the list to 2, 8, and 11, the arithmetic mean is found by
solving for the value of A in the equation 2 + 8 + 11 = A + A + A. One finds that A = (2 + 8 +
11)/3 = 7.

Algorithm –

1.Create two variables ‘a’ and ‘b’.

2.Ask user to enter values in them.

3.Store the value of sum of ‘a’ and ‘b’ in sum.

4.Calculate the average by dividing sum by 2.

5.Print sum and average .

CODE :
#include<stdio.h>
#include<conio.h> void
main()

{ float a,b;
float avg,sum; clrscr();
printf("Enter any 2 no.s\n");
scanf("%f%f",&a,&b);
sum=a+b; avg=sum/2;

printf("Sum = %f and Average = %f",sum,avg); getch();


}

OUTPUT :

FINDING :
Print the sum and the average of the two entered number.

LEARNING :
This program will read two floating points literals from the user and will
calculated and print the sum and average of the two to give us a desired output
(up to 2 decimal place).
Program -2
AIM :
W.A.P. to find greatest of 10 numbers.

DESCRIPTION :
The program will prompt user to input ten integer numbers and based on the input, it would
compare and display the greatest number as output. In this program num1, num2, num3
upto num10 are ten int variables that represents number1, number2 , number3 upto
number10 consecutively.

ALGORITHM:
1.Entered values are 12,54,64,72,09,32,51,23,71,77.
2.They are stored in an array of size 10. let a[] be an array holding these values.
/* how the greatest among ten numbers is found */
3.Let us consider a variable 'greatest'. At the beginning of the loop, variable 'greatest' is
assigned with the value of the first element in the array greatest=a[0]. Here variable
'greatest' is assigned 2 as a[0]=2.
Below loop is executed until the end of the array 'a[]';.
for(i=0; i<10; i++){
if(a[i]>greatest){ greatest=
a[i];

}
}

4.For each value of 'i', value of a[i] is compared with value of variable 'greatest'. If any value
greater than the value of 'greatest' is encountered, it would be replaced by a[i]. After
completion of 'for' loop, the value of variable 'greatest' holds the greatest number in the
array. In this case, 88 is the greatest of all the numbers.

CODE :
#include<stdio.h>
#include<conio.h> void
main()
{
int a[10],max; clrscr();
printf("Enter any 10 no.s\n");
for(int i=0;i<10;i++) {
scanf("%d",&a[i]); }
max=a[0]; for(i=0;i<9;i++)
{
if(a[i]<a[i+1])
max=a[i+1];
}
printf("Greatest no. is %d",max); getch();
}

OUTPUT :

FINDING :
Greatest number among the 10 inputs by user.
LEARNING :
Execution of the program helps us to understand the concept of
array, relational operator and looping .

Program -3
AIM :
W.A.P. to find Simple Interest.

DESCRIPTION :
The program will prompt user to input principle amount, rate per annum, time in year and
based on the input, it would compute the simple interest by using SI = (P*R*T)/100 and
display simple interest as output. In this program P, R, T, SI int variables that represents
principle amount, rate per annum, time in year, simple interest respectively.

ALGORITHM:

1.Create variables ‘p’, ’r’, ’t’ and “si”.

2.Ask user to enter values in them.

3.Put si=p*r*t/100.
4.Print “si”.

CODE :
#include<stdio.h>
#include<conio.h> void
main()
{
float P,R,T,SI=0; clrscr();
printf("Enter Principle Amount = "); scanf("%f",&P);

printf("\nEnter Rate per Annum = "); scanf("%f",&R);


printf("\nEnter Time in Years = ");
scanf("%f",&T); SI=((P*R*T)/100);
printf("\nSIMPLE INTEREST is = %f",SI); getch();
}

OUTPUT :
FINDING :
Print the simple interest from the principle amount, rate per annum, time in
years input by user.

LEARNING :
Execution of the program helps us to understand the use of
multiplication and division arithmetic operator and scanf function to
enter the values from the user.

Program -4
AIM :
W.A.P. to print following patterns.
* ***** *

** **** ***

*** *** *****

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

* *********

DESCRIPTION :
In this type of program the user decides how many lines he wants to print in a triangular
pattern. Let user decides N number of lines to be printed, then we will run two loops one
outer and a nested loop and print the star(*) character according to the pattern for each
iteration of the nested loop(inner loop).

ALGORITHM :
1. Input number from the user as ‘n’.

2. Initialise two integer variables i and j.

3. For pattern 1, run a loop from i=1 to i=n and a nested loop from j=1 to j=i and print “*”
for each value of j.

4. For pattern 2, Run a loop from i=1 to i=n and a nested loop from j=i to j=n and print ‘*’
for every value of j.

5. For pattern 3, run a loop from i=1 to n-1 and a nested loop from j=i to j=n-1 and print
“ “.

6. Again run the loop from i=1 to n and a nested loop from j=1 to j= 2*i - 1 and print “*”.

CODE :
#include<stdio.h>

#include<conio.h>

int main(){ int n;

printf("Enter a no.:");

scanf("%d",&n);

int i,j;

for(i=1;i<=n;i++){

for(j=1;j<=i;j++){

printf("*");

printf("\n");

printf("\n"); for(i=1;i<=n;i++){

for(j=i;j<=n;j++){

printf("*");

}
printf("\n");

for(i=1;i<=n;i++){

for(j=n;j>i;j--){

printf(" ");

for(j=1;j<=2*i-1;j++){

printf("*");

printf("\n");

return 0;

OUTPUT :

FINDING :
Print the pattern of the right angled triangle, inverted right angled triangle and
a pyramid.

LEARNING :
Execution of the program helps us to understand concept of the
nested for loop.
Program -5
AIM :
W.A.P. to find if given no. is prime or not.

DESCRIPTION :
PRIME NUMBER - Every Prime number has two factors and these are 1 and the number
itself. If N is Prime Number then its factors will be 1 and N. Thus a Prime Number is divisible
by 1 and itself. Example of Prime Numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43
and so on. The smallest Prime Number is 2 and it is an Even Number. Except 2 all Prime
Numbers are Odd Numbers.

ALGORITHM:
1. Input the number from the user as n.

2. Initialise integer variable flag and i and set flag = 0.

3. Run a loop from i =2 to n-1, if ‘n’ mod ‘i’ is 0 set f=1 and break the loop.

4. After the loop ends, if flag is 1 then print “Number is not prime” else print “Number is Prime”.

CODE :
#include<stdio.h>
#include<conio.h> void
main()
{ int a,i,flag=0; clrscr();
printf("Enter any no.\n");
scanf("%d",&a); for(i=2;i<=a/2;i++)

{ if(a%i==0)

{
flag=1;

break;

}
}
if(flag==1)
printf("\n%d is not a PRIME NO.",a);
else printf("\n%d is a PRIME NO.",a); getch();
}

OUTPUT :

FINDING :
Print the number entered by the user is prime or not.

LEARNING :
This program familiarizes us with the basic use of break statement of
the C program and various basic statements used in C
PROGRAMMING like header files, standard input output etc.
We can use printf function to display output on the screen.
Program -6
AIM :
W.A.P. to find sum of a 5 digit number.

DESCRIPTION :
This program sum up the digits of the five digit number entered by the user and then prints
the sum on the screen. For example if user enter 652 as input then 13 is printed as output.
In our program we use modulus(%) operator to obtain the digits of a number. Used the logic
sum=sum+(digit of the number obtain by the %)

ALGORITHM :
1. Input number from the user as ‘a’.

2. Initialise two integer variables ‘b’ and sum=0.

3. In a loop make ‘b’ equal to ‘a’ mod 10, sum = sum+ b and a= a/10.

4. Run the loop until ‘a’ becomes ‘0’.

5. Print sum.

CODE :
#include<stdio.h>
#include<conio.h> void
main()
{ long int a,b,sum=0;
clrscr();
printf("Enter any five digit no.\n");
scanf("%ld",&a); printf(“\nGiven
no. is %ld”,a); while(a!=0) {
b=a%10; sum=sum+b;
a=a/10;
}
printf(“\nThe sum of digits is equal to %ld”,sum); getch();
}

OUTPUT :

FINDING :
Print sum of digits of five digit number.

LEARNING :
For the calculation of the sum of digit of number we will use modulus
operator to extract individual digits and keep on adding them.
Program -7
AIM :
W.A.P. to find the reverse of a 5 digit number.

DESCRIPTION :
This program reverse the number entered by the user and then prints the reversed number
on the screen. For example if user enter 123 as input then 321 is printed as output. -In our
program we use modulus(%) operator to obtain the digits of a number. To invert number
look at it and write it from opposite direction or the output of code is a number obtained by
writing original number from right to left. -To reverse or invert large numbers use long data
type or long long numbersdata type if compiler supports it, if we still have large then use
strings or other data structure.
ALGORITHM:

1. Start.

2. Declare integer data type variables a, b & d and set d=0.

3. Take input and store it in ‘a’.

4. Run a while loop for ‘a’ not equals to zero.

5. In the loop, divide ‘a’ by 10 and store the remainder in ‘b’, d=(d*10)+b and a=a/10.

6. Print d.

7. Stop.

CODE :
#include<stdio.h>
#include<conio.h> void
main()
{ long int a,b,d=0;
clrscr();
printf("Enter any five digit no.\n");
scanf("%ld",&a); printf(“\nGiven
no. is %ld”,a); while(a!=0) {
b=a%10; d=(d*10)+b;
a=a/10;
}
printf(“\nThe reverse of the number is %ld”,d); getch();
}

OUTPUT :
FINDING :
Print the reverse of the 5 digit number.

LEARNING :
The entered is n we declare a variable “a” initially 0 which will store
the reverse number then e run a loop till n is not 0 as with each
iteration we are taking a digit from the n and adding it at the
beginning of the current value of “a” and simultaneously removing
that n digit from the current n. Hence at last when n = 0 that’s when
no digit recites in n the loop will end and the value in “a” will be
reverse of original number.
Program -8
AIM :
W.A.P. to convert decimal to binary and vice-versa.

DESCRIPTION :
This program is for conversion of decimal number entered by the user into its equivalent
binary number.
The method for converting a decimal number to binary is one that can be used to convert
from decimal to any number base. It involves using successive division by the radix until the
dividend reaches 0. At each division, the remainder provides a digit of the converted
number, starting with the least significant digit.
An example of the process:

Convert 3710 to binary

37 / 2 = 18 remainder 1 (least significant digit)


18 / 2 = 9 remainder
0 9 / 2 = 4 remainder
1 4 / 2 = 2 remainder
0 2 / 2 = 1 remainder
0 1 / 2 = 0 remainder 1 (most significant digit)
The resulting binary number is: 100101
And binary to decimal
(100101)2 = 1*2^5+0*2^4+0*2^3+1*2^2+0*2^1+1*2^0 = 3710

ALGORITHM:

Step1: Start.
Step2: User inputs his choice.
Step3: Store the choice in a variable say n.
Step4: If n is 1 call a function bintodec.
Step5: If n is 2 call a function dectobin.
Step6: If n is anyhting else print wrong input.
Step7: Do step 4,5,6 till user enter no.
Step8: Stop.
CODE:

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

void bintodec(); void


dectobin(); void
main()

int n, flag=1;
char ans; do{
clrscr();
printf("\nMENU: \n 1.Binary to Decimal \n 2.Decimal to Binary
\n\n Enter your choice\n"); scanf("%d",&n);

if(n==1) bintodec();
else if(n==2) dectobin();
else
{
printf("You entered the wrong choice"); flag=1;
}
printf("\nDo you want to continue y/n");
scanf(" %c",&ans); if(ans=='y')

flag=1;
else flag=0;

}while(flag==1);

getch();
}

void dectobin()
{ clrscr(); int n,c=-
1,rem,a[100]; printf("Enter
the number\n");
scanf("%d",&n); while(n>0)
{
rem=n%2;
c++;
a[c]=rem;
n=n/2;

}
printf("\n");
for(int i=c;i>=0;i--) printf("%d",a[i]);
}

void bintodec()
{ clrscr(); int n,i=0,dec=0,rem;
printf("Enter the number in binary\n");
scanf("%d",&n); while(n>0)
{
rem=n%10;
dec+=rem*pow(2,i)
; i++; n=n/10;
}
printf("\nCDecimal number : \n%d",dec);
}

OUTPUT:
FINDING :
Print Binary to Decimal and Decimal to Binary.

LEARNING :
here we use the basic method of conversion of binary to decimal that is we in a
single loop take out each digit of binary number from the end of the number
and multiply it with 2 raise to the power i the loop variable starting from 0
which also represent the index of selected digit.

Program -9
AIM :
W.A.P. to implement switch case.
DESCRIPTION :
A switch statement tests the value of a variable and compares it with multiple cases. Once the
case match is found, a block of statements associated with that particular case is executed.

Each case in a block of a switch has a different name/number which is referred to as an


identifier. The value provided by the user is compared with all the cases inside the switch
block until the match is found.

If a case match is found, then the default statement is executed, and the control goes out of
the switch block.

ALGORITHM:
Step1: Start.
Step2: User inputs a character.
Step3: Store the character in a variable say ch.
Step4: If ch is a,e,i,o,u,A,E,U,I,O then follow step 5 otherwise step 6.
Step5: Print vowel.
Step6: Print consonant.
Step7: Stop.

CODE:

//IMPLEMENTING SWITCH CASE

#include<stdio.h>
#include<conio.h>
void main()
{

clrscr();

char ch; printf("Enter the


letter\n");
scanf("%c",&ch);

switch(ch)
{
case 'a':
printf("Vowel");
break; case 'e':
printf("Vowel");
break; case 'i':
printf("Vowel");
break; case 'o':
printf("Vowel");
break; case 'u':
printf("Vowel");
break; case 'A':
printf("Vowel");
break; case 'E':
printf("Vowel");
break; case 'I':
printf("Vowel");
break; case 'O':
printf("Vowel");
break; case 'U':
printf("Vowel");
break; default:
printf("Consonant
"); break;
}
getch();
}

OUTPUT :

FINDING :
Print the case which is true.

LEARNING :
After executing the program name of the day is printed corresponding to the
given number the switch statement is a multi-way branch statement it
provides an easy way to dispatch execution to different part of code based on
the value of execution.

Program -10
AIM :
W.A.P to print Fibonacci series.

DESCRIPTION :
Fibonacci series is defined as a sequence of numbers in which the first two numbers are 1
and 1 and each subsequent number is the sum of the previous two. So, in this series, the nth
term is the sum of (n-1)th term and (n-2)th term. Mathematically, the nth term of the
Fibonacci series can be represented as: tn = tn-1 + tn-2
The Fibonacci sequence upto certain term can be represented as: 1, 1, 2, 3, 5, 8, 13, 21, 34,
55,89 144, ….

ALGORITHM:

Step1: Start
Step2:Declare variables n,term_1,term_2,req_term,i.
Step3: Initialize the variables, term_1=0, term_2=1,i=1.
Step4: Enter the number of terms of Fibonacci series to be printed
and store in n.
Step5: Print First two terms of series.
Step6: Use loop for the following steps til i<=n-2.
-> Store sum of term_1 and term_2 in req_term.
-> Print req_term.
-> Now store term_2 in term_1.
-> Now store req_term in term_2.
-> Increment in value of i by 1.
Step7: End

CODE:

//FIBONACCI SERIES

#include<stdio.h>

int main()
{
//clrscr();
int term_1=0,term_2=1,req_term,n;
printf("\nEnter the number of terms :\n");
scanf("%d",&n);
printf("\n Required Fibonacci series:\n");
printf("%d",term_1); printf("
%d",term_2);

for(int i=1;i<=n-2;i++)
{
req_term=term_1+term_2;
printf(" %d",req_term);
term_1=term_2;
term_2=req_term;

getch();
}

OUTPUT :

FINDING :
Print the number of elements of Fibonacci series input by user.

LEARNING :
Execution of the program helps us to understand concept of for loop.
Program -11
AIM :
W.A.P to find exponential function.

DESCRIPTION :
The program below takes two integers from the user (a base number and an exponent)
and calculates the power.

For example: In case of 2 3


● 2 is the base number
● 3 is the exponent
● And, the power is equal to 2*2*2

ALGORITHM:
1. Start.
2. Declare integer data type variables ‘base’, ‘exponent’ , long long data type
‘result’ and set it to 1.
3. Run a while loop for ‘exponent’ not equals to zero.
4. In the loop, set result = result*base and do the decrement of exponent.
5. Print result 6. Stop.

CODE :
#include <stdio.h> int
main()
{
int base, exponent; long long
result = 1; printf("Enter a base
number: "); scanf("%d",
&base);

printf("Enter an exponent: ");


scanf("%d", &exponent);

while (exponent != 0)
{
result *= base;
--exponent;
}
printf("Answer = %lld", result);

return 0;
}

OUTPUT :

FINDING :
Print answer by taking input as base number and exponent by the user.
LEARNING :
Execution of the program helps us to understand concept of power
function contained in math.h header file.

Program -12
AIM :
W.A.P to search a number from an array using linear search.

DESCRIPTION :
C program to implement linear search (Searching algorithm), which is used to find whether a
number is present in an array and if it is present, then at what location it occurs. It is also
known as sequential search. It is straightforward and works as follows: we compare each
element with the element to search until it is found or the list ends. Linear search in C
language for multiple occurrence s and using functio n.

ALGORITHM
Step 1: Create an int variable c.
Step 2:Take ‘search’ from the user.
Step 2: if c > n then go to step 7.
Step 3: if array[i] = search then go to step 6.
Step 4: Increment value of i to i + 1
Step 5: Go to Step 2
Step 6: Print “Element is present at location” and go to step 8
Step 7: Print “Element isn’t present in the array”
Step 8: Exit
CODE :
#include<stdio.h> int
main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++) scanf("%d",
&array[c]); printf("Enter a number to
search\n"); scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

return 0;
}

OUTPUT :
FINDING:
Print the searching result by using linear search.

Learning
While writing and executing the above program we’ve learnt and understood
the concept of linear search. Here scanning is done one item at a time
sequentially. Because of this, it is considered to be slower than other methods
of searching elements in an array.

Program -14
AIM :
W.A.P to search a number from an array using binary search.
DESCRIPTION :
C program for binary search: This code implements binary search in C language. It can
only be used for sorted arrays, but it's fast as compared to linear search. If you wish to
use binary search on an array which isn't sorted, then you must sort it using some
sorting technique, say merge sort and then use the binary search algorithm to find the
desired element in the list. If the element to be searched is found then its position is

printed. The code below assumes that the input numbers are in ascending order
.

ALGORITHM
Step 1: Create a variable c and set it to 0.

Step 2: Find the ‘middle’ element in the array.


Step 3: Read the ‘search’ element from the user and compare it with the ‘middle’
element in the sorted list.

Step 4 - If array[middle]=search, then display "Found at location" and terminate the


function.

Step 5 - If both are not equal, then check whether the search element is smaller or
larger than the middle element.

Step 6 - If the search element is smaller than the middle element, find the new ‘middle’
element for the left subarray and go to Step 4.

Step 7 - If the search element is larger than the middle element,find the new ‘middle’
element for the right subarray and go to step 4t.

Step 8 - Repeat the same process until we find the search element in the list or until
the sublist contains only one element.

Step 9 - If that element also doesn't match with the search element, then display "Not found!
Element isn't present in the list." and terminate the function.

CODE :
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n"); scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);

printf("Enter value to find\n");


scanf("%d", &search);
first = 0;
last = n - 1;
middle =
(first+last)/2;
while (first <=
last) { if
(array[middle
] < search)
first = middle
+ 1;
else if
(array[middle
] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return 0;
}

OUTPUT :

FINDING :
Print the element if found in the entered array by binary search.

LEARNING:
This code implements binary search in C language. Here, We basically ignore half of
the elements just after one comparison. It is because of this reason this method is faster

as compared to other methods of searching an element in an array.


Program -15
AIM :
W.A.P to sort an array using Bubble sort .

DESCRIPTION :
C program for bubble sort: C programming code for bubble sort to sort numbers or arrange
them in ascending order. You can modify it to print numbers in descending order.You can also
sort strings using Bubble sort, it is less efficient as its average and worst case complexity is
high, there are many other fast sorting algorithms like quick-sort, heap-sort, etc. Sorting

simplifies problem-solving in computer programming


.

Algorithm:
1. Input n.

2. Input array.

3. Starting with the first element (index = 0), compare the current element with the

next element of the array.

4. If the current element is greater than the next element of the array, swap them.
5. If the current element is less than the next element, move to the next element.

6. Repeat from step 2 to 5 (n – 1) times.

7. Print the sorted array.

CODE :
#include <stdio.h> int
main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n); printf("Enter %d
integers\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

for (c = 0 ; c < n - 1; c++)


{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++) printf("%d\n",
array[c]); return 0;
}

OUTPUT :

FINDING :
Print sorted array in ascending order by bubble sorting.

LEARNING :
C programming code for bubble sort to sort numbers or to arrange them in
ascending order you can modify it to print number in descending order you can
also sort strings using bubble sort it is less efficient as its average and worst
case complexity is high.
Program -16
AIM :
W.A.P to sort an array using selection sort .

DESCRIPTION :
Selection sort in C: C program for selection sort to sort numbers. This code implements
selection sort algorithm to arrange numbers of an array in ascending order. With a little
modification, it will arrange numbers in descending order.

Algorithm:
1. Input n.
2. Input array.

3. Starting from the first element, search the smallest element in the array, and swap it

with the element in the first position.

4. Then move on to the second position, and look for smallest element present in the

subarray, starting from index 1, till the last index.


5. Swap the element at the second position in the array with the second smallest

element.

6. This is repeated, until the array is completely sorted i.e. (n- 1) times.

7. Print the sorted array.

CODE :
#include <stdio.h> int
main()
{
int array[100], n, c, d, position, swap;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]); for
(c = 0; c < (n - 1); c++)
{
position = c;
for (d = c + 1; d < n; d++)
{
if (array[position] > array[d])
position = d;
}
if (position != c)
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++) printf("%d\n",
array[c]); return 0;
}

OUTPUT :

FINDING :
Print sorted array in ascending order by selecting sorting.

LEARNING :
Selection sort is sorting algorithm known by its simplicity unfortunately it lacks
efficiency on huge list of items and also does not stop until the number of
iteration is achieved.

Program -17
AIM :
W.A.P to sort an array using insertion sort .

DESCRIPTION :
Insertion sort in C: C program for insertion sort to sort numbers. This code implements
insertion sort algorithm to arrange numbers of an array in ascending order. With a little
modification, it will arrange numbers in descending order. Best case complexity of insertion
sort is O(n), average and the worst case complexity is O(n2).

Algorithm:
1. Input n.

2. Input array.

3. Make the second element of the given array, i.e. element at index 1, the key.

4. Compare the key element with the element(s) before it, in this case, element at

index 0:

1. If the key element is less than the first element, insert the key element before

the first element.

2. If the key element is greater than the first element, then insert it after the

first element.

5. Then, make the third element of the array as key and compare it with elements to it's

left and insert it at the right position.

6. Repeat the step 3 to 5 (n- 1) times.

7. Print the sorted array.

CODE :
#include <stdio.h> int
main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]); for (c =
1 ; c <= n - 1; c++) { d = c;
while ( d > 0 && array[d-1] > array[d]) {
t = array[d]; array[d] = array[d-1];
array[d-1] = t; d--;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++) { printf("%d\n",
array[c]);

return 0;
}

OUTPUT :
FINDING :
Print sorted array in ascending order by insertion sorting.

LEARNING :
Insertion sort works best with small number of elements the worst case run
time complexity of the insertion sort is similar to that of bubble sort however
insertion sort is considered better then bubble sort.

PROGRAM 18
AIM:
Program to find factorial of a number using recursion.

DESCRIPTION:
Factorial of a non-negative integer, is multiplication of all integers smaller
than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.

Recursive Solution:

Factorial can be calculated using following recursive formula. n!=n*(n-1)!

n!=1 for n=0 or n=1


ALGORITHM:
1.START

2.take input of number n whose factorial is to be calculated

3.Define a function fact which accepts an integer n as parameter and returns


1 if n==0 or it returns n*fact(n-1)

4.Call the function fact and pass the value n

5.Print the calculated factorial

6.STOP

CODE:
#include <stdio.h>

long int fact(long int

n)

if(n==0)

return 1;

return n*fact(n-1);

int main()

{ long int n; printf("Enter number :");

scanf("%Id",&n); long int ans=fact(n);

printf("Factorial of %Id is : %Id",n,ans);

return 0;

}
OUTPUT:

LEARNING:
In this program we learned about calculating factorial of a number recursively.Recursion is a
technique which is breaking a problem into a sub problem of similar type.In recursion a function
calls itself in its definition body.

Progrm-19
AIM :
W.A.P to find length of the string without using strlen and then pass a character to string .

DESCRIPTION :
You can use standard library function strlen( ) to find the length of a string but,
this program computes the length of a string manually without using strlen()
funtion.

ALGORITHM:
1.Read string s
2.Initiaise a variable i with value 0
3.Increment i by 1
4.If s[i]!=’\0’ then go to step 3 else go to step 5
5.Print length of the string i
6.Enter one more character to the string
7.Print the string after adding one more character
8.stop

CODE :
#include <stdio.h> int
main()
{
char ch,s[1000];
int i;

printf("Enter a string: ");


scanf("%s", s);

for(i = 0; s[i] != '\0'; ++i);


printf("Length of string: %d\n", i);

printf("Enter any character \n");


scanf("%s",&s[i]);

printf("New STRING");
puts(s); return 0;
}

OUTPUT :
FINDING :
Print the length of the string without using strlen and then pass a character to
string .

LEARNING :
In the following C program we are counting the number of characters in a
given string without using strlen function and display its length on console this
increases the run time of the program and makes it a bit complex and tedious
for the program.

Program -20
AIM :
W.A.P to count number of vowels in a string.

DESCRIPTION :
English alphabets 'a', 'e', 'i', 'o', 'u' both lowercase and uppercase are known as
vowels and alphabets other than vowels are known as consonants.
There are two ways to build this program :
1. By using the switch statement. 2. By using the OR (||) operator
Here we are going to use the OR operator to check whether the entered alphabet
is a vowel.

ALGORITHM:
1.START
2.Read string s
3.Declare a variable count and a variable i both with the value 0
4.if s[i] is equal to A,a,E,e,I,i,O,o,U or u then increment count by 1
5.Increment i by 1
6.if s[i]!=’\0’ then go to step 4 else go to step 7
7.Print number of vowels in the string
8.STOP

CODE :
#include<stdio.h>
#include<conio.h>
void main() { char
s[50]; int
count=0; clrscr();
printf("Enter any character\n");
scanf("%s",&s); for(int
i=0;s[i]!='\0';i++)
{if(s[i]=='A'||s[i]=='a'||s[i]=='E'||s[i]=='e'||s[i]=='I'||s[i]=='i'||s[i]=='O'||s[i]=='
o'||s[i]=='U'||s[i]=='u') count++;
}
printf("No.of vowel in the string %d\n",count); getch();
}

OUTPUT :

FINDING :
Print number of vowels in the user entered string.

LEARNING :
Here’s a program to count the number of vowel present in an entered
sentence here variable ‘vowel’ is incremented whenever a vowel found in
tracing,logic being that comparing each character to the set of vowels, pre
defined in array if this character is in the set of vowels then it implies that
character is a vowel so we increment the count by one.
Program -21
AIM :
W.A.P to check if a given string is a palindrome or not.

DESCRIPTION :
C program to check if a string or a number is palindrome or not. A palindrome
string is one that reads the same backward as well as forward. It can be of odd
or even length. A palindrome number is a number that is equal to its reverse.
Our program works as follows: at first, we copy input string into a new string
(strcpy function), and then we reverse (strrev function) it and compare it with
the original string (strcmp function). If both of them have the same sequence
of characters, i.e., they are identical, then the string is a palindrome otherwise
not. C program to check palindrome without using string function s. Some
palindrome strings are: "C", "CC", "madam", "ab121ba", "C++&&++C".
ALGORITHM:
1. Initialize two strings a and b
2. Ask user to input a string
3. Input a string a by the user
4. Copy this string to string b using strcpy() function
5. Reverse the string b using strrev() function
6. Now compare the strings a and b using strcmp() function
7. If the strings are same then print “The string is a palindrome” 8. If the strings
are not same then print “The string is not a palindrome” CODE :
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
printf("Enter a string to check if it is a palindrome\n");
gets(a);
strcpy(b, a); // Copying input string
strrev(b); // Reversing the string
if (strcmp(a, b) == 0) // Comparing input string with the reverse string
printf("The string is a palindrome.\n"); else
printf("The string isn't a palindrome.\n");

return 0;
}

OUTPUT :

FINDING :

Print if a given string is a palindrome or not.

LEARNING :
Here we have simply used the iterative way to check for the palindrome
number each digit is extracted in an iteration and formed the reverse number
and finally, whether it is same as the original number.
Program -22
AIM :
W.A.P to string concatenation.

DESCRIPTION :
C program to concatenate two strings, for example, if the first string is "C
programming" and the second string is " language" (note space before language) then
on concatenating these two strings we get the string "C programming language." To
concatenate two strings we use strcat function of string.h, to concatenate without
using library function see another code below which uses pointers.

ALGORITHM:
1. Initialize two strings a and b
2. Ask user to enter two strings
3. Concatenate the two strings using the strcat() function
4. Print the concatenated string on the output screen

CODE :
#include <stdio.h>
#include <string.h>
#include<conio.h> int
main()
{
char a[1000], b[1000];
printf("Enter the first string\n");
gets(a);
printf("Enter the second string\n");
gets(b);

strcat(a, b);
printf("String obtained on concatenation: %s\n", a);
getch(); return 0;
}

OUTPUT :

FINDING :

Print concatenate of two string.

LEARNING :
Cancatenation is a process of combining two body of senteces to form a
paragraph or a new sentence everytime a screen concatenation changes we
are not manipulating another value instead all the characters inside of the
previous string (on the left hand side) copied and added onto a new screen.
Program -23
AIM :
W.A.P to string comparison.

DESCRIPTION :

C program to compare two strings using strcmp functio n, withou t


strcmp function and using pointer s. Function strcmp is case
sensitive and returns 0 if both the strings are same.
ALGORITHM:
1. Initialize two strings a and b
2. Ask user to enter two strings
3. Compare the two strings using the strcmp() function
4. If the function returns 0 then goto 5 else goto 6
5. Print “Both the strings are same” 6. Print “Both the strings are not same”
CODE :
#include <stdio.h>
#include <string.h>
#include<conio.h> int
main()
{
char a[1000], b[1000];
clrscr();
printf("Enter the first string\n");
gets(a);
printf("Enter the second string\n");
gets(b); if(strcmp(a, b)==0)
printf("Both the Strings are same \n");
else printf(“The strings are not same”)
getch(); return 0;
}

OUTPUT :

FINDING :
Compare the input strings and print result .

LEARNING :
Comparing strings is a process of analysing and outputting the differences or
similarities between the two strings. Comparing strings has many uses like
checking differences or similarities in a user response. Two variables may
typically have differences in character.

Program -24
AIM :
W.A.P to string reverse.

DESCRIPTION :
C program to reverse a string that a user inputs. If the string is "hello" then, the
output is "olleh." C program to reverse a string using strrev, without using
strrev, recursion and pointers. A string which remains the same on reversal is a
palindrome string.

ALGORITHM:
1.Declare an array to get the string input from user.
2.use string reverse function(strrev()) to reverse the string.
3.print the reversed string.

CODE :
#include <stdio.h>
#include <string.h>
int main()
{
char arr[100];
printf("Enter a string to reverse\n");
gets(arr); strrev(arr);
printf("Reverse of the string is \n%s\n", arr);
return 0;
}

OUTPUT :

FINDING :

Print string reverse.

LEARNING :
First we calculate the length of the string using strlen function and assigns
character of input string in reverse order to create a new string using for loop
so this program reverses the string entered by the user.

Program -25
AIM :
W.A.P to convert a string from lower case to upper case and vice-versa.

DESCRIPTION :
C program to convert a string elements from lower case to upper case and
vice-versa. Strlwr function converts a string to lower case, and strupr function converts a
string to upper case. Here we will change string case with and without strlwr and strupr
functions. These functions convert the case of alphabets and ignore other characters that
may be present in a string.

ALGORITHM:
1.Declare an array to get the string input from the user.

2.Take each character of a string.

3.Check for each character whether it is uppercase or lowercase.

4.If a character is uppercase then add 32 to character to convert it to lower.

5.If a character is lowercase then subtract 32 from character to convert it to upper.

6.Repeat the steps 2,3,4 and 5 till it reaches null.

7.Print the array.

CODE :
#include<stdio.h> int main
() { int c = 0; char ch,
s[1000]; printf("Input a
string\n"); gets(s);
while (s[c] != '\0') { ch =
s[c];
if (ch >= 'A' && ch <= 'Z')
s[c] = s[c] + 32; else if (ch >=
'a' && ch <= 'z') s[c] = s[c] -
32; c++;
}

printf("%s\n", s);
return 0;}

OUTPUT :

FINDING :

Print to convert a string elements from lower case to upper case and vice-

versa..

LEARNING :
For converting lower case to upper case and vise versa one employs the header
file ctype.h in order to use the pre defined function to upper and lower that
perform the respective functions of conversion.

Program -26
AIM :
W.A.P for the addition of two 3 x 3 matrices.

DESCRIPTION :
Matrix addition in C: C program to add two matrices, i.e., compute the sum of two
matrices and then print it. Firstly a user will be asked to enter the order of matrix
(number of rows and columns) and then two matrices. For example, if a user input
order as 3, 3, i.e., two rows and two columns and matrices as First matrix:
124
345
389

Second matrix:
546

852 9

64

then the output of the program (Summation of the two matrices) is: 6
68
11 9 7

11 14 13
Matrices are frequently used in programming to represent graph data structure, in
solving equations and in many other ways.

ALGORITHM:
1.Declare a three two-dimensional array with 3,3 dimensions i.e. first[3][3] ,second[3][3] and
sum[3][3].

2.Take two variables c and d and initialise them 0.

3.From c equal to 0 to c less than 3.

4.From d equal to 0 to d less than 3.

5.Input elements of matrix first[c][d].

6.Repeat steps from 3 to 5 for second[3][3] matrix.

7.Now repeat step 3 and 4.


8.Use sum[c][d] =first[c][d] +second[c][d].

9.Repeat step 3 and 4.

10.Print sum[c][d].

CODE :
#include<stdio.h> int
main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++) for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++) for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]); printf("Sum of
entered matrices:-\n"); for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}

OUTPUT :
FINDING :

Print the addition of two 3 x 3 matrices.

LEARNING :
The two dimensional array can be defined as an array of arrays. The 2D array is
organised as matrices which can be represented as the collection of rows and
columns. However,2D arrays are created to implement a relational database
lookalike data structure.It provides ease of holding the bulk data at once which
can be passed to any number of functions wherever required
Program -27
AIM :
W.A.P to multiply two 3 x 3 matrices.

DESCRIPTION :
Matrix multiplication in C language: C program to multiply two matrices (two-
dimensional arrays) which will be entered by a user. The user will enter the order of a
matrix and then its elements and similarly inputs the second matrix. If the orders of
the matrices are such that they can't be multiplied by each other, then an error
message is displayed. You may have studied the method to multiply matrices in
Mathematics.

Multiplication is Possible iff –

No. of Columns of Matrix 1 = No of Columns of Matrix 2

ALGORITHM:

Step1: Start

Step2: Initialize Three Matrices of 3X3

Step3: row = 0

Step4: Repeat the steps 5 to 9 from until row<3

Step5: col = 0

Step6: Repeat the steps 7 and 8 until col<3

Step7: take input a[row][col]

Step8: Increase col by 1

Step9: Increase row by 1

Step10: row = 0

Step11: Repeat the steps 12 to 16 from until row<3

Step12: col = 0

Step13: Repeat the steps 14 and 15 until col<3

Step14: take input b[row][col]

Step15: Increase col by 1

Step16: Increase row by 1

Step17: row = 0

Step18: Repeat the steps 19 to 28 from until row<3


Step19: col = 0

Step20: Repeat the steps 21 to 27 until col<3

Step21: sum = 0

Step22: k = 0

Step23: repeat step 24 and 25 till k is less than 3

Step24: sum = sum + a[row][k] * b[k][col];

Step25: increase k by 1

Step26: c[row][col] = sum

Step27: Increase col by 1

Step28: Increase row by 1

Step29: print Matrix C

Step30: Stop.

CODE :
# #include<stdio.h> int main() {

int a[3][3], b[3][3], c[3][3], i, j, k;

int sum = 0;

printf("\nEnter First Matrix : ");

for (row = 0; row < 3; row++) {

for (col = 0; col < 3; col++) {

scanf("%d", &a[i][j]);

}
}

printf("\nEnter Second Matrix:

"); for (row = 0; row < 3; row++)

{ for (col = 0; col < 3; col++)

{ scanf("%d", &b[i][j]);

//Multiplication Logic for (row

= 0; row <= 2; row++) { for (col

= 0; col <= 2; col++) {

sum = 0;

for (k = 0; k <= 2; k++) { sum = sum +

a[row][k] * b[k][col];

c[row][col] = sum;

} printf("\nMultiplication Of Two Matrices :

\n"); for (i = 0; i < 3; i++) { for (j =

0; j < 3; j++) { printf(" %d ",

c[i][j]);

}
printf("\n");

return 0;

OUTPUT :

FINDING :

Print the multiply two 3 x 3 matrices.

LEARNING :
Matrices are frequently used in programming and are used to represent the
graph data structure in solving a system of linear equations and have many
other application a lot of research is being done on how to multiply matrices
using a minimum number of operations you can also implement this program
using pointers.We also learned how to do programs involving matrix operation
by accessing their elements indiviually.

Program -28

AIM :
W.A.P to swap two numbers using pointers.

DESCRIPTION :
The pointer in C language is a variable which stores the address of
another variable. This variable can be of type int, char, array, function, or
any other pointer.
Swapping means interchanging. For example, if in a C program we have
two variables a and b where a = 4 and b = 5, then before swapping a = 4, b
= 5 after swapping a = 5, b = 4. In the first C program, we use a temporary
variable to swap two number
ALGORITHM:
1.Start
2.take x and y from the user
3. Intialize two pointers a and b
4. Make pointers a and b pointing to x and y respectively
5.temp = *b
6.*b = *a
7. *a = temp
8. Stop.
CODE :
#include <stdio.h> int
main()
{
int x, y, *a, *b, temp; printf("Enter
the value of x and y\n");
scanf("%d%d", &x, &y);

printf("Before Swapping\nx = %d\ny = %d\n", x, y);


a = &x; b = &y; temp = *b;
*b = *a;
*a = temp;

printf("After Swapping\nx = %d\ny = %d\n", x, y);


return 0;
}

OUTPUT
FINDING :

Print the swaped form of two numbers using pointers..

LEARNING :
There are 2 ways of sending parameters for a swaping function : by value and
by pointers. If we send by value,the function will operate in local copies are
discarded and the variables still have their initial values. To make sure that the
changes that the function makes to its parameters propagate back into
variables sent to the function you need to pass them by pointers.

Program 29
Aim:
Program to generate the employee details using structure.

Introduction:
What is a structure? A structure is a user defined data type in C.A struct in the
C programming language (and many derivatives) is a composite data type (or
record) declaration that defines a physically grouped list of variables under one
name in a block of memory, allowing the different variables to be accessed via
a single pointer or by the struct declared name which returns the same
address. The struct data type can contain other data types so is used for mixed-
data-type records such as a hard-drive directory entry (file length, name,
extension, physical address, etc.), or other mixed-type records (name, address,
telephone, balance, etc.).
The C struct directly references a contiguous block of physical memory, usually
delimited (sized) by word-length boundaries.
Because the contents of a struct are stored in contiguous memory, the sizeof
operator must be used to get the number of bytes needed to store a particular
type of struct, just as it can be used for primitives. The alignment of particular
fields in the struct (with respect to word boundaries) is
implementation-specific and may include padding, although modern compilers
typically support the #pragma pack directive, which changes the size in bytes
used for alignment.

Algorithm:
1)Start
2)Create a structure employee
3)Create data members of the structure like Id, name, salary
4)Create an object of the structure employee emp
5) Take employe id, name , salary from the user 6)
Print the employe details using the object emp 7)
Stop.

Code: #include
<stdio.h> struct
employee{ char
name[30]; int
empId; float
salary;
};

int main()
{
struct employee emp;

printf("\nEnter details :\n");


printf("Name ?:");
gets(emp.name);
printf("ID ?:");
scanf("%d",&emp.empId);
printf("Salary ?:");
scanf("%f",&emp.salary);

printf("\nEntered detail is:");


printf("Name: %s" ,emp.name);
printf("Id: %d" ,emp.empId);
printf("Salary: %f\n",emp.salary);

return 0;
}

Output:

Learning:
This program tought us to use structures in a way that is practical and very
much relevant in the life. Here user can store data and print the properties of
the employees in a very effective manner that can be easy to access for the
future purposes.

Program-30
Aim:

WAP to find the area and perimeter of a circle, rectangle, square and triangle
using functions.

Description:
This program takes input from the user for the figure he intends to find the
area and perimeter for, and also the dimensions of the same figure.

The formulas used to calculate the areas and perimeters of the figures are as
follows:-
1) Circle ( input for radius taken in ‘r’)-
· Perimeter= 2*π*r

· Area= π*r*r

2) Rectangle( inputs for length and breadth taken in ‘l’ and ‘b’)-

· Perimeter= 2*( l+b)

· Area = l*b

3) Square ( input for side is taken in ‘s’)-

· Perimeter = 4*s

· Area = s*s

4) Triangle ( input taken for base and height in ‘b’ and ‘h’, and the sides in
‘a’, ‘c’ and ‘d’)
· Perimeter=a+c+d

· Area=0.5*b*h

:
Algorithm

1) Take input for the shape the perimeter and area need to be found in
‘shape’

● If shape is 0, take input of radius in ‘r’

o Print perimeter as

2*(3.14)*r o Print area as

(3.14)*r*r

● If the shape is 1, take input for length in ‘l’ and bread in ‘b’
o Print perimeter as 2*( l+b)

o Print area as l*b

● If the shape is 2 take input of side in ‘s’

o Print perimeter as 4*s o

Print area as s*s

● If the shape is 3, take input of base in ‘b’, height in ‘h’, and sides in ‘a’,
‘d’, ‘c’

o Print perimeter as a+c+d o

Print area as 0.5*l*b

Code:

#include<stdio.h> #include<conio.h> int main(){ float

area,perimeter,a,b,c,d,l,h,s,r,shape; clrscr();

printf("Enter the shape code \n"); printf("Circle-0,


Rectangle-1, Square-2, Triagle-3 \n"); scanf(

"%f",&shape); if(shape==0){ printf("enter r");

scanf("%f",&r); perimeter=2*3.14*r; area=3.14*r*r;

printf("Perimeter is %f \n",perimeter); printf("Area

is %f", area);

else if (shape==1){ printf("enter

length and breadth"); scanf("%f

%f",&l,&b); perimeter=2*(l+b);

area=l*b; printf("Perimeter is %f

\n",perimeter); printf("Area is %f",

area);

else if (shape ==2){ printf("enter the

side"); scanf("%f",&s); area=s*s;

perimeter=4*s; printf("Perimeter is

%f \n",perimeter); printf("Area is %f",

area);

else if (shape ==3){ printf("enter the

height, base"); scanf("%f

%f",&b,&h); printf("\n enter the

sides-s1,s2,s3"); scanf("%f %f
%f",&a,&c,&d); area=0.5*b*h;

perimeter=a+c+d; printf("Perimeter

is %f \n",perimeter); printf("Area is

%f", area);

getch(); return

0;

:
Output

For circle-

For Rectangle-

For Square-

For Triangle-
Learning:

While performing the above code we learnt the various formulas for the
different shapes in order to calculate the perimeter and area of the same. We
also got to learn about the implementation of “if” and “else if” statements to
compare values and perform specific tasks after the comparison is successful.

PROGRAM -31

Aim-
Write a program to pass pointer to function hence calculate average of
an array.

DESCRIPTION-
The program calls a function to add all the element of an array and then
divide the sum obtained by length of array to get the average and passes
the array argument as a pointer.

ALGORITHM-
1. Create a static array of some fixed size, along with element
declaration.
2. Build a function with a single argument, in which we will pass array
argument.
3. Inside this function, all the elements of the array are accessed one-by-
one, adding to return the sum.
4. Return sum to the called function.
5. Calculate the average by dividing it by length of array.
6. Print the average.

CODE-
1. #include <stdio.h>
2. void main()
3. {
4. static int array[5] = { 10, 20, 60, 80, 108 };
5. float average;
6.
7. int addnum(int *ptr);
8. average = (float)addnum(array)/(float)5;
9.
10. printf("Average of all array elements = %.2f\n", average);
11.
12. }
13.
14. int addnum(int *ptr)
15. {
16. int index, total = 0;
17. for (index = 0; index < 5; index++)
18. {
19. total += *(ptr + index);
20. }
21. return(total);
22.
23. }

OUTPUT-

LEARNING-
● We learnt how to pass a pointer as argument to a function.
● We also learnt about pointer arithmetic and how it is different from
normal arithmetic.

PROGRAM -32

Aim-
Program to pass an array as pointer to a function that
calculates the sum of all elements of the array.
DESCRIPTION-
The program calls a function to add all the element of an array
and passes the array argument as a pointer.\
ALGORITHM-
1. Create a static array of some fixed size, along with element
declaration.
2. Build a function with a single argument, in which we will pass array
argument.
3. Inside this function, all the elements of the array are accessed one-by-
one, adding to return the sum.
4. Return sum to the called function and print it.

CODE-
24.
OUTPUT-
FINDING-
print the sum of numbers of arrays using pointers in a
function.

LEARNING-
There are 2 ways of sending parameters for a swaping
function : by value and by pointers. If we send by value,the
function will operate in local copies are discarded and the
variables still have their initial values. To make sure that the
changes that the function makes to its parameters propagate
back into variables sent to the function you need to pass them
by pointers.

Program -33

Aim-
Program to demonstrate the example of array of pointers.
DESCRIPTION-
The program demonstrate the array of pointers and how to initialize it
and access it's elements.
ALGORITHM-
1 Create an array of pointers having following syntax Datatype-
*ArrayName[size].
2 Initialize each element of the array of pointers and assign value to each
address.
3 Access each of element of the array by creating a loop .
4 Print each of the element of the array of pointers .

CODE-
#include<stdio.h> int
main()
{
int *arrop[3];
int a = 10, b = 20, c = 50, i;

arrop[0] = &a;
arrop[1] = &b;
arrop[2] = &c; for(i =
0; i < 3; i++)

{
printf("Address = %d\t Value = %d\n", arrop[i], *arrop[i]);
}

return 0;
}
OUTPUT -

FINDING-
How to create an array of pointers , how to initialize it and access each of
its elements .

LEARNING-
Rather than normal array , array of pointers is a continuous set of
addresses .
It is a collection of continuous address of same data type where the next
element is linked to the address of its previous member . It can't be
initialize like a normal array .

PROGRAM 34

OBJECTIVE:

Program to create a file called emp.txt and store information about a


person, in terms of his name, age and salary.

DESCRIPTION:

The program will open a file of name emp in txt format in write mode to
right some info in it. Then program will close the file.

ALGORITHM:
Step1:START

Step2: make a file pointer fptr& declare char name[20],int age Float
salary.

Step3: fptr = fopen("emp.txt", "w")

Step4: get values of name,age,salary and write them in emp.txt

Step5: END

CODE:

#include <stdio.h> int

main()

FILE *fptr; char name[20];

int age; float salary; fptr =

fopen("data.txt", "w"); if

(fptr == NULL)

printf("File does not exists \n"); return

0;

printf("Enter the name \n");

scanf("%s", name); fprintf(fptr, "Name

= %s\n\n\n", name); printf("Enter the

age\n"); scanf("%d", &age); fprintf(fptr,

"Age = %d\n\n\n", age); printf("Enter


the salary\n"); scanf("%f", &salary);

fprintf(fptr, "Salary = %f\n\n\n", salary);

fclose(fptr); return 0;

OUTPUT:
LEARNING:

While dealing with saving or taking data from an external file, “file” data
type can be which works similar to any another data type and stores an
external file.
Program-35
AIM:
WAP to copy one file contents to another file.
DESCRIPTION:
This program copies the content from the read only file and
pastes it to another file which is available for writing.
ALGORITHM:
Step1:START

Step2: make two file pointer fptr1, fptr2 and a char array -filename.

Step3: read filename from the user in fptr1 to read.

Step4: read filename from the user in fptr2 to copy.

Step5: now select the contents of the first file till the end of file.

Step6: copy it and print it to new file.

Step7: END

CODE:
#include <stdio.h> 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);
}

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);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}

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

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

OUTPUT:
LEARNING:
From this program I learned how to copy the contents of one
file to another and the use of fgetc(); fputc(); fopen(); and
fclose(); functions of c.

Program-36
AIM:
WAP to read a file and after converting all lower case to upper
case letters write it to another file.
DESCRIPTION:
This program requires to use data handling concept in which
we have to read a file and convert all the characters in lower
case to upper case letters and write it into another file .
Lower case are all the letters between ‘a’ to’z’ and Uppercase
letters are the letters between ‘A’ to ‘Z’.
ALGORITHM:
1.Create two files data.c and data2.c ,data.c will store the
lower case text which is needed to be converted into
uppercase text and stored in data2.c file.
2.Make two file pointers input and output which will point to
data.c and data2.c files respectively.
3.Check whether the file exists or not using NULL pointer if
exist proceed forward else build the files.
4.input the character from data.c file using fgetc() and convert
to uppercase and simultaneously write to data2.c
5.Repeat the step 4 until we encounter EOF in data.c file.
6.Now close both the files using fclose().

CODE:
#include<stdio.h>

#include<string.h>

#include<stdlib.h>

#include<ctype.h>

#include<process.h> void

main()

int i, j, k, n;

char ch;

FILE *input; FILE *output;

input = fopen("data.c", "r");

if (input == NULL)

{printf("Not found the file");

exit(1);

}
else

{ output = fopen("data2.c", "w");

if (output == NULL) {printf("Doesnt

Exist");

exit(2);

else
{ch = fgetc(input);

while (ch != EOF)

{ if (ch >= 'a' && ch <= 'z')

{ch = toupper(ch); fputc(ch,

output); ch = fgetc(input);

fclose(input); fclose(output);

OUTPUT:
LEARNING:
This program helped me to understand the concept of file
handling and many other functions involved in this like
fopen() fclose() FILE pointers,mode of opening files,EOF
character

Program-37
AIM:
Program to find the Size Of A Given File.

Description:
A program to read all the characters in a file already present in the
system with a .txt extension. As the characters are read we increment
our size variable by one as each character holds 1byte. Finally on
reaching end of file we break this loop and print the size.

Algorithm:
1. Start.
2. Create a function findfilesize().
3. Check for the value of fp.
4. If value of fp is null,give output as file not found and return -1.
5. Otherwise close the file.
6. Put the file pointer at the beginning of the file.
7. Declare an integer variable result and initialise it with the output of the
ftell() function.
8. Close the file pointer fp.
9. Print the result.
10.End.

CODE:
#include<stdio.h>
int findfilesize(char f_n[ ]){ FILE*
fp = fopen(f_n,”r”);
if(fp==NULL){ printf(“File Not
Found!\n”);
return -1;
}
fseek(fp,0L,SEEK_END);
int res = ftell(fp); fclose(fp);

return res;
}
int main(){ char f_n[ ] = {“b.txt”};
int result = findfilesize(f_n);
if(result != -1){
printf(“Size of the File is %1d bytes \n” , result);
}
return 0;
}

OUTPUT:

FINDING:
How to find the size of a file using file pointer.

LEARNING:
This program will help us find the size of any given file by just
calculating the number of places occupied by its contents.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy