Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views36 pages

Itp Lab Programs

Uploaded by

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

Itp Lab Programs

Uploaded by

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

WEEK 1:

i) Sum and average of 3 numbers


Program:
#include <stdio.h>
int main()
{
float num1, num2, num3;
printf("Enter three numbers: ");
scanf("%f %f %f", &num1, &num2, &num3);
float sum = num1 + num2 + num3;
float average = sum / 3;
printf("Sum: %.2f\n", sum);
printf("Average: %.2f\n", average);
return 0;
}

ii) Conversion of Fahrenheit to Celsius and vice versa


Program:
#include <stdio.h>
int main() {
float temperature;
char scale;
printf("Enter temperature: ");
scanf("%f", &temperature);
printf("Enter scale (C or F): ");
scanf(" %c", &scale);
if (scale == 'F' || scale == 'f') {
float celsius = (temperature - 32) * 5 / 9;
printf("Temperature in Celsius: %.2f\n", celsius);
}
else if (scale == 'C' || scale == 'c') {
float fahrenheit = (temperature * 9 / 5) + 32;
printf("Temperature in Fahrenheit: %.2f\n", fahrenheit);
}
else {
printf("Invalid scale. Please enter 'C' or 'F'.\n");
return 1;
}
return 0;
}

iii) Simple interest calculation Program


#include <stdio.h>
#include<math.h>
int main() {
float principal, rate, time;
printf("Enter principal amount: ");
scanf("%f", &principal);
printf("Enter rate of interest: ");
scanf("%f", &rate);
printf("Enter time in years: ");
scanf("%f", &time);
float simpleInterest = (principal * rate * time) / 100;
printf("Simple Interest: %.2f\n", simpleInterest);
return 0;
}

WEEK - 3
i) Finding the square root of a given number
#include <math.h>
#include <stdio.h>
int main()
{
int N ;
float sqroot;
printf("Enter any Number");
scanf("%d",&N);
sqroot=sqrt(N);
printf("%f ", sqroot);
return 0;
}
ii) Finding compound interest
#include <stdio.h>
#include<math.h>
int main()
{
float Amount,principal,rate,time,CI;
printf(“Enter principal,rate ,time”);
scanf(“%f%f%f”,&principal,&rate,&time);
Amount = principal * ((pow((1 + rate / 100), time)));
CI = Amount - principal;
printf("Compound Interest is : %f",CI);
return 0;
}
iii) Area of a triangle using heron’s formulae
#include <stdio.h>
#include <math.h>
int main(){
float a,b,c, s, area;
printf("Enter the length of three sides of triangle\n");
scanf("%f %f %f", &a, &b, &c);
s = (a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area of triangle : %0.4f\n", area);
return 0;
}
iv) Distance travelled by an object
#include<stdio.h>
int main() {
float u, a, d;
int t;
printf("\nEnter the value of a : ");
scanf("%f", & a);
printf("\nEnter the value of u : ");
scanf("%f", & u);
printf("\nEnter the value of t : ");
scanf("%d", & t);
d = (u * t) + (a * t * t) / 2;
printf("\n The Distance : %.2f", d);
return 0;
}
WEEK-4
Simple computational problems using the operator’ precedence and
associativity
i)Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
#include<stdio.h>
void main()
{
int A,B,C,D,E,F,G,result;
printf("Enter A,B,C,D,E,F,G");
scanf("%d%d%d%d%d%d%d",&A,&B,&C,&D,&E,&F,&G);
result=A+B*C+(D*E)+F*G;
printf("Result of Expression is=%d",result);
}

b. A/B*C-B+A*D/3
#include<stdio.h>
void main()
{
int A,B,C,D,result;
printf("Enter A,B,C,D values");
scanf("%d%d%d%d",&A,&B,&C,&D);
result=A/B*C-B+A*D/3;
printf("The result of Expression is=%d",result);
}

c. A+++B---A
#include<stdio.h>
void main()
{
int A,B,result;
printf("Enter A,B Values");
scanf("%d%d",&A,&B);
result=A+++B---A;
printf("The result of the expression is =%d",result);

d. J= (i++) + (++i)
#include<stdio.h>
void main()
{
int i,J;
printf("Enter value for i");
scanf("%d",&i);
J=(i++)+(++i);
printf("The result of the Expression is=%d",J);
}

ii) Find the maximum of three numbers using conditional operator


#include<stdio.h>
void main()
{
int a,b,c,max;
printf("Enter values for a,b,c:");
scanf("%d%d%d",&a,&b,&c);
max=a>b?a>c?a:c:b>c?b:c;
printf("result=%d",max);

}
iii) Take marks of 5 subjects in integers, and find the total, average in float
#include <stdio.h>
void main()
{
float m1,m2,m3,m4,m5,total, average;
printf("Enter marks of five subjects: :- ");
scanf("%f%f%f%f%f", &m1, &m2, &m3, &m4, &m5);
total = m1+ m2 + m3+ m4 + m5;
average = total / 5;
printf("Total marks = %.2f\n", total);
printf("Average marks = %.2f", average);

}
WEEK-5
Problems involving if-then-else structures.
i) Write a C program to find the max and min of four numbers using if-else.
ii) Write a C program to generate electricity bill.
iii) Find the roots of the quadratic equation.
#include <stdio.h>
#include <math.h>
void main()
{
float a, b, c, determinant, root1, root2, realPart, imaginaryPart;
printf("Enter the coefficients a, b and c: ");
scanf("%f %f %f", &a, &b, &c);
determinant = b * b - 4 * a * c;
if (determinant > 0) {
root1 = (-b + sqrt(determinant)) / (2 * a);
root2 = (-b - sqrt(determinant)) / (2 * a);

printf("The roots are real and different.\n");


printf("Root 1 = %.2f\n", root1);
printf("Root 2 = %.2f\n", root2);
} else if (determinant == 0) {
root1 = root2 = -b / (2 * a);

printf("The roots are real and equal.\n");


printf("Root 1 = Root 2 = %.2f\n", root1);
} else {
realPart = -b / (2 * a);
imaginaryPart = sqrt(-determinant) / (2 * a);
printf("The roots are complex and different.\n");
printf("Root 1 = %.2f + %.2fi\n", realPart, imaginaryPart);
printf("Root 2 = %.2f - %.2fi\n", realPart, imaginaryPart);
}

}
iv) Write a C program to simulate a calculator using switch case.
v) Write a C program to find the given year is a leap year or not.
#include <stdio.h>
int main() {
int year ;
printf("Enter any year");
scanf("%d",&year);

if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {


printf("%d is a leap year\n", year);
} else {
printf("%d is not a leap year\n", year);
}
return 0;
}

WEEK-6
#include<stdio.h>
void main()
{
int i, n;
float x, sum, t;
printf(" Enter the valueof x");
scanf("%f",&x);
printf("Enter the value of n");
scanf("%d",&n);
x=x*3.14159/180;
t=x;
sum=x;
/* Loop to calculate the value of Sine */
for(i=1;i<=n;i++)
{
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
}
printf(" The value of Sin(%f) = %.4f",x,sum);
}
COSINE SERIES
//cosine series
#include<stdio.h>
void main()
{
int i, n;
float x, sum=1, t=1;
printf(" Enter the value for x ");
scanf("%f",&x);
printf(" Enter the value for n :");
scanf("%d",&n);
x=x*3.14159/180;
/* Loop to calculate the value of Cosine */
for(i=1;i<=n;i++)
{
t=t*(-1)*x*x/(2*i*(2*i-1));
sum=sum+t;
}
printf(" The value of Cos(%f) is : %.4f", x, sum);
}
5. PYRAMID OF NUMBERS
#include<stdio.h>
int main()
{
int i,j,k=9,m;
for(i=1; i<=9; i++){
for(j=1; j<=k; j++){
printf(" ");
}
for(m=1; m<=i; m++){
printf("%d",i);
printf(" ");
}
printf("\n");
k=k-1;
}
return 0;
}
WEEK-7
1. #include<stdio.h>
void main()
{
int n,i,max=0,min=0,a[20];
printf("Enter array size");
scanf("%d",&n);
printf("Enter array elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
//max
max=a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
min=a[0];
for(i=0;i<n;i++)
{
if(a[i]<min)
{
min=a[i];
}
}
printf("Maximum of 1-D array is=%d\n",max);
printf("Minimum of 1-D array is=%d",min);
}
2. #include<stdio.h>
void main()
{
int a[10],n,i,pos=-1,ele;
printf("Enter array size");
scanf("%d",&n);
printf("Enter array elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter element to search");
scanf("%d",&ele);
for(i=0;i<n;i++)
{
if(a[i]==ele)
{
pos=i;
break;
}
}
if(pos==-1)
printf("%d is not found",ele);
else
printf("%d is found at %d position",ele,pos+1);
}
3. #include<stdio.h>
void main()
{
int a[10],n,i;
printf("Enter array size");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=n-1;i>=0;i--)
{
printf("%4d",a[i]);
}
}
4. #include <stdio.h>
#define SIZE 8
int main()
{
char binary[SIZE + 1], onesComp[SIZE + 1], twosComp[SIZE + 1];
int i, carry=1;
printf("Enter %d bit binary value: ", SIZE);
/* Input 8-bit binary string */
gets(binary);
/* Find ones complement of the binary number */
for(i=0; i<SIZE; i++)
{
if(binary[i] == '1')
{
onesComp[i] = '0';
}
else if(binary[i] == '0')
{
onesComp[i] = '1';
}
}
onesComp[SIZE] = '\0';

/*
* Add 1 to the ones complement
*/
for(i=SIZE-1; i>=0; i--)
{
if(onesComp[i] == '1' && carry == 1)
{
twosComp[i] = '0';
}
else if(onesComp[i] == '0' && carry == 1)
{
twosComp[i] = '1';
carry = 0;
}
else
{
twosComp[i] = onesComp[i];
}
}
twosComp[SIZE] = '\0';
printf("Original binary = %s\n", binary);
printf("Ones complement = %s\n", onesComp);
printf("Twos complement = %s\n", twosComp);
return 0;
}
/*Enter 8 bit binary value: 01101100
Original binary = 01101100
Ones complement = 10010011
Twos complement = 10010100*/
5. #include<stdio.h>
void main()
{
int a[10],n,i,c[10],count,j;
printf("Enter array size");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Array elements before deleting duplicates\n");
for(i=0;i<n;i++)
{
printf("%4d",a[i]);
}
for(i=0;i<n;i++)
{
c[i]=-1;
}
for(i=0;i<n;i++)
{ count=0;
for(j=0;c[j]!=-1;j++)
{
if(c[j]==a[i])
{
count++;
}
}
if(count==0)
{
c[j]=a[i];
}
}
printf("\nArray elements after deleting duplicates\n");
for(i=0;i<=j;i++)
{
printf("%4d",c[i]);
}
}

WEEK-9
9.1 Write a C program to find the sum of a 1D array using malloc()
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *ptr;
int n, i,sum=0;
printf("Enter number of elements:");
scanf("%d",&n);
ptr = (int*)malloc(n * sizeof(int));
printf("Enter values into array");
for (i=0;i<n;i++) {
scanf("%d",&ptr[i]);
}
printf("The sum of elements of the array is: ");
for (i=0;i<n;i++) {
sum+=ptr[i];
}
printf("%d",sum);
}
9.2 Write a C program to find the total, average of n students using
structures
#include<stdio.h>
struct student
{ int marks[5],total,rno;
char sname[10];
float avg;
};
void main()
{
struct student s[10];
int i,n,j;
printf("Enter number of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter student number");
scanf("%d",&s[i].rno);
printf("Enter student name");
scanf("%s",&s[i].sname);
printf("Enter student-%d marks in 5 subjects",i+1);
for(j=0;j<5;j++){
scanf("%d",&s[i].marks[j]);
}}
//calculation of total and average
for(i=0;i<n;i++)
{s[i].total=0;
for(j=0;j<5;j++){
s[i].total+=s[i].marks[j];
}
s[i].avg=s[i].total/5;
}
//Display result
for(i=0;i<n;i++)
{
printf("\t*Students Records*\n");
printf("\nStudent's Roll no. – %d", s[i].rno);
printf("\nStudent's Name – %s", s[i].sname);
printf("\nStudent's Total Marks – %d", s[i].total);
printf("\nStudent's average Marks – %f", s[i].avg);
}
}
9.3 Enter n students data using calloc() and display failed students list
#include <stdio.h>
#include<stdlib.h>
struct Student {
char name[50];
int marks;
};
int main()
{
int n,failedCount=0,i;
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student *students;
// Dynamically allocate memory for n students using calloc
students = (struct Student*)calloc(n,sizeof(struct Student));
if (students== NULL) {
printf("Memory allocation failed.\n");
return 1;
}
printf("Enter data for %d students:\n", n);
for(i=0; i<n; i++)
{
printf("Student %d\n", i+1);
printf("Name: ");
scanf("%s",students[i].name);
printf("Marks: ");
scanf("%d", &students[i].marks);
if (students[i].marks < 40)
{
failedCount++;
}
}
printf("Failed students list:\n");
for (i=0; i < n; i++)
{
if(students[i].marks<40){
printf("%s\n", students[i].name);
}
}
// Free dynamically allocated memory
free(students);
return 0;
}
9.4
#include <stdio.h>
struct student {
char name[50];
int roll;
float marks[5];
} s;

int main() {
printf("Enter information:\n");
printf("Enter name: ");
scanf("%s", s.name);
//fgets(s.name, sizeof(s.name), stdin);

printf("Enter roll number: ");


scanf("%d", &s.roll);
for (i = 1; i <=5; ++i) {
printf("Enter marks in subject %d : ",i);
scanf("%f", &s.marks);
}
printf("Displaying Information:\n");
printf("Name: ");
printf("%s", s.name);
printf("Roll number: %d\n", s.roll);
printf("Marks: %.1f\n", s.marks);

return 0;
}
9.5 Write a C program to implement realloc()
#include <stdio.h>
#include <stdlib.h>
void main()
{
int* ptr;
int n, i;
n = 5;
printf("Enter number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
ptr = (int*)realloc(ptr, n * sizeof(int));
printf("Memory successfully re-allocated using realloc.\n");
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
}

WEEK-10
10.1 Single linked list using self referential structure
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
}*start,*temp,*t,*n,*l;
int insert_element()
{
n=(struct node*)malloc(sizeof(struct node));
printf("Enter elements for inserting into linked list : ");
scanf("%d",&n->data);
if(start->next==NULL) {
l=n;
start->next=l;
l->next=NULL;}
else{
l->next=n;
l=n;
l->next=NULL;
}
}
int delete_element()
{
int pos,i=1;
printf("Enter position of the element for deleteing the element : ");
scanf("%d",&pos);
t=start;
temp=start->next;
while(i<pos) {
t=t->next;
temp=temp->next;
i+=1;
}
t->next=temp->next;
free(temp);
printf("Deleted successfully\n");
}
int display()
{
temp=start->next;
printf("The elements in the linked list are : ");
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
int count_ele()
{
int count=0;
temp=start;
while(temp->next!=NULL){
count+=1;
temp=temp->next;
}
printf("No of elements in the linked list are : %d\n",count);
}
int main() {
int c=0;
start=(struct node*)malloc(sizeof(struct node));
start->next=NULL;
l=NULL;
printf("Singly Linked List Example - All Operations\n");
while(c<5){
printf("Options\n");
printf("1 : Insert elements into the linked list\n");
printf("2 : Delete elements from the linked list\n");
printf("3 : Display the elements in the linked list\n");
printf("4 : Count the elements in the linked list\n");
printf("5 : Exit()\n");
printf("Enter your option : ");
scanf("%d",&c);
switch(c)
{
case 1: insert_element();break;
case 2: delete_element();break;
case 3: display();break;
case 4: count_ele();break;
case 5: break;
default: printf("Enter options from 1 to 5\n");break;
}
}
}

10.2 Difference between structure and union


#include<stdio.h>
struct ssize{
double a;
int b;
char c;
float d;
};
union usize{
double a;
int b;
char c;
float d;
};

int main()
{
printf("Size of Structure: %ld\n",sizeof( struct ssize));
printf("Size of Union: %ld",sizeof(union usize));
return 0;
}

10.3 Program to shift/rotate using bitfields


#include <stdio.h>
#define INT_BITS 32

/*Function to left rotate n by d bits*/


int leftRotate(int n, unsigned int d)
{
/* In n<<d, last d bits are 0. To put first 3 bits of n at last, do bitwise or
of n<<d with n >>(INT_BITS -d) */
return (n << d) | (n >> (INT_BITS - d));
}

/*Function to right rotate n by d bits*/


int rightRotate(int n, unsigned int d)
{
/* In n>>d, first d bits are 0. To put last 3 bits of at first, do bitwise or of
n>>d with n <<(INT_BITS- d) */
return (n >> d) | (n >> (INT_BITS - d));
}

/* Driver program to test above functions */


void main()
{
int n,d;
printf("Enter the value for n and d: ");
scanf("%d %d",&n,&d);
printf("Left Rotation of %d by %d is ", n, d);
printf("%d", leftRotate(n, d));
printf(" Right Rotation of %d by %d is ", n, d);
printf("%d", rightRotate(n, d));
}
10.4 Write a C program to copy one structure variable to another structure
of the same type.
#include<stdio.h>
struct student
{
int rno;
char name[20];
float avg;
};
void main()
{
struct student s1,s2;
printf("Enter student roll number,name,average");
scanf("%d%s%f",&s1.rno,&s1.name,&s1.avg);
s2=s1;
printf("\nSTUDENT DETAILS\n");
printf("Student roll number=%d\n",s1.rno);
printf("Student name=%s\n",s1.name);
printf("Student average=%f\n",s1.avg);
printf("Student roll number=%d\n",s2.rno);
printf("Student name=%s\n",s2.name);
printf("Student average=%f",s2.avg);
}

WEEK-11
11.1 Function to calculate NCR value
nCr = n! /((n-r)!r!)
#include <stdio.h>

int fact(int z);

void main()
{
int n, r, ncr;
printf("\n Enter the value for N and R \n");
scanf("%d%d", &n, &r);
ncr = fact(n) / (fact(r) * fact(n - r));
printf("\n The value of ncr is: %d", ncr);
}

int fact(int z)
{
int f = 1, i;
if (z == 0)
{
return(f);
}
else
{
for (i = 1; i <= z; i++)
{
f = f * i;
}
}
return(f);
}

11.2 Write a C function to find the length of a string.


#include<stdio.h>
int len( char s[])
{
return strlen(s);
}
void main()
{
char s[20],length;
puts("Enter string");
//fflush(stdin);gets(s);
scanf("%s",s);
length=len(s);
printf("Given string length is %d",length);
}
11.3 Write a C function to transpose of a matrix.
#include <stdio.h>

void transpose(int arr[][3], int transposed[][3]) {


int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
transposed[i][j] = arr[j][i];
}
}
}

int main() {
int arr[3][3],i, j; ;
printf("Enter elements into array\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++)
{
scanf("%d",&arr[i][j]);
}
}
int transposed[3][3];

transpose(arr, transposed);

printf("Original Array:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}

printf("\nTransposed Array:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", transposed[i][j]);
}
printf("\n");
}

return 0;
}
11.4 Function to demonstrate numerical integration of differential
equations using Euler’s method
#include<stdio.h>
#define f(x,y) x+y

int main()
{
float x0, y0, xn, h, yn, slope;
int i, n;
printf("Enter Initial Condition\n");
printf("x0 = ");
scanf("%f", &x0);
printf("y0 = ");
scanf("%f", &y0);
printf("Enter calculation point xn = ");
scanf("%f", &xn);
printf("Enter number of steps: ");
scanf("%d", &n);

/* Calculating step size (h) */


h = (xn-x0)/n;

/* Euler's Method */
printf("\nx0\ty0\tslope\tyn\n");
printf("------------------------------\n");
for(i=0; i < n; i++)
{
slope = f(x0, y0);
yn = y0 + h * slope;
printf("%.4f\t%.4f\t%0.4f\t%.4f\n",x0,y0,slope,yn);
y0 = yn;
x0 = x0+h;
}

/* Displaying result */
printf("\nValue of y at x = %0.2f is %0.3f",xn, yn);
return 0;
}
WEEK-12
12.1Write a recursive function to generate Fibonacci series.
#include<stdio.h>
int fibanocci(int n)
{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{
return fibanocci(n-1)+fibanocci(n-2);
}
}
void main()
{
int n,i;
printf("Enter number of terms in fibanocci");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("%5d",fibanocci(i));
}
}
12.2 Write a recursive function to find the lcm of two numbers.
#include<stdio.h>
int findlcm(int a,int b)
{
int max;
max=(a>b)?a:b;
while(max%a!=0 || max%b!=0)
{
max++;
}
return max;
}
void main()
{
int a,b,lcm;
printf("Enter two numbers");
scanf("%d%d",&a,&b);
lcm=findlcm(a,b);
printf("Lcm of two numbers is %d",lcm);
}
12.3 Write a recursive function to find the factorial of a number.
#include<stdio.h>
int factorial(int n)
{
if(n==1||n==0)
return 1;
else
return n*factorial(n-1);
}
void main()
{
int n,fact;
printf("Enter any positive number");
scanf("%d",&n);
fact=factorial(n);
printf("Factorial of a given number is %d",fact);
}
12.4. Ackermann function using recursion
#include<stdio.h>
int A(int m, int n);

main()
{
int m,n;
printf("Enter two numbers :: \n");
scanf("%d%d",&m,&n);
printf("\nOUTPUT :: %d\n",A(m,n));
}

int A(int m, int n)


{
if(m==0)
return n+1;
else if(n==0)
return A(m-1,1);
else
return A(m-1,A(m,n-1));
}
12.5 Write a recursive function to find the sum of series.
#include<stdio.h>
float sumofseries(int n)
{
if(n==1)
{
return 1;
}
else
{
return (float)1/n + sumofseries(n-1);
}
}
void main()
{
int n,i;
float sum=0;
printf("Enter nuber of terms in series");
scanf("%d",&n);
sum=sumofseries(n);
printf("The sum of series is=%f",sum);
}

WEEK-13
13.1Write a C program to swap two numbers using call by reference.
#include<stdio.h>
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
void main()
{
int a,b;
printf("Enter values for a and b");
scanf("%d %d",&a,&b);
swap(&a,&b);
printf("a=%d b=%d",a,b);
}
13.2Demonstrate Dangling pointer problem using a C program.
#include <stdio.h>
#include <stdlib.h>
void main() {
// 4 bytes of int memory block (64bit compiler)
// allocated using malloc() during runtime
int *ptr = (int *)malloc(sizeof(int)); // normal pointer
*ptr = 10;
printf("%d\n", *ptr);
// memory block deallocated using free() function
free(ptr);
// here ptr acts as a dangling pointer
printf("%d", *ptr);
// prints garbage value in the output console
}
13.3Write a C program to copy one string into another using pointer.
#include <stdio.h>
#include <string.h>
void main() {
char str1[100],*p,str2[100],index=0;
p=str1;
printf("Enter a string1: ");
scanf("%s",str1);
while(*p!='\0')
{
str2[index]=*p;
index++;
p++;
}
str2[index]='\0';
printf("String2=%s",str2);
}
13.4Write a C program to find no of lowercase, uppercase, digits and other
characters using pointers.
#include <stdio.h>
#include <string.h>
void main() {
char str[100],*p;
int caps=0, smalls=0, digits=0, specials=0;
p=str;
printf("Enter a string: ");
scanf("%s", str);
while(*p!='\0')
{
if(*p>='A'&& *p<='Z')
{
caps++;
}
else if(*p>='a'&& *p<='z')
{
smalls++;
}
else if(*p>='0'&& *p<='9')
{
digits++;
}
else {
specials++;
}
p++;
}
printf("Number of capital letters: %d\n", caps);
printf("Number of small letters: %d\n", smalls);
printf("Number of digits: %d\n", digits);
printf("Number of special characters: %d\n", specials);
}

WEEK-14
14.a Write a program to write and read text into a file.
#include< stdio.h >
int main()
{

FILE *fp; /* file pointer*/


char fName[20];

printf("\nEnter file name to create :");


scanf("%s",fName);

/*creating (open) a file*/


fp=fopen(fName,"w");
/*check file created or not*/
if(fp==NULL)
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}

printf("File created successfully.");


/*writting into file*/
putc('A',fp);
putc('B',fp);
putc('C',fp);

printf("\nData written successfully.");


fclose(fp);

/*again open file to read data*/


fp=fopen(fName,"r");
if(fp==NULL)
{
printf("\nCan't open file!!!");
exit(0);
}

printf("Contents of file is :\n");


printf("%c",getc(fp));
printf("%c",getc(fp));
printf("%c",getc(fp));

fclose(fp);
return 0;
}
14.b Write a C program to write and read text into binary file using fread()
and fwrite()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN 50
#define N_STUD 2

typedef struct stud{


char name[LEN+1];
unsigned int id;
float average;
}stud_t;

int main() {
FILE *fp;
stud_t student[N_STUD];
int i;
char row[LEN+1];
unsigned int n_stud;

strcpy(student[0].name, "Steven");
student[0].id = 120000;
student[0].average = 25.5;

strcpy(student[1].name, "Julia");
student[1].id = 120001;
student[1].average = 28.5;

fp = fopen("out.bin", "w"); /* Open the file for writing */


if (fp == NULL){
printf("Error: file out.bin cannot be opened\n");
exit(1);
}

/* Write in binary all the data contained in the structure */


fwrite(student, sizeof(stud_t), N_STUD, fp);

fclose(fp); /* Close the file */

fp = fopen("out.bin", "r"); /* Open the file for reading */


if (fp == NULL){
printf("Error: file out.bin cannot be opened\n");
exit(1);
}

/* Read the file */


n_stud = 0;
while( fread(&student[n_stud], sizeof(stud_t), 1, fp) == 1 ) {
n_stud++;
}

fclose(fp); /* Close the file */

/* Print the read records */


for (i=0; i<n_stud; i++) {
printf("%s %d %f\n", student[i].name, student[i].id, student[i].average);
}
return 0;
}
14.c Copy the contents of one file to another
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];
printf("\n\n Copy a file in another name :\n");
printf("----------------------------------\n");
printf(" Input the source file name : ");
scanf("%s",fname1);
fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);
exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fptr2);
}
}
printf(" The file %s copied successfully in the file %s. \n\
n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar();}
14.d. Write a program to merge two files into the third file
#include <stdio.h>
#include <stdlib.h>

void main()
{
FILE *fold1, *fold2, *fnew;
char ch, fname1[20], fname2[20], fname3[30];

printf("\n\n Merge two files and write it in a new file :\n");


printf("-------------------------------------------------\n");

printf(" Input the 1st file name : ");


scanf("%s",fname1);
printf(" Input the 2nd file name : ");
scanf("%s",fname2);
printf(" Input the new file name where to merge the above two files : ");
scanf("%s",fname3);
fold1=fopen(fname1, "r");
fold2=fopen(fname2, "r");
if(fold1==NULL || fold2==NULL)
{
// perror("Error Message ");
printf(" File does not exist or error in opening...!!\n");
exit(EXIT_FAILURE);
}
fnew=fopen(fname3, "w");
if(fnew==NULL)
{
// perror("Error Message ");
printf(" File does not exist or error in opening...!!\n");
exit(EXIT_FAILURE);
}
while((ch=fgetc(fold1))!=EOF)
{
fputc(ch, fnew);
}
while((ch=fgetc(fold2))!=EOF)
{
fputc(ch, fnew);
}
printf(" The two files merged into %s file successfully..!!\n\n", fname3);
fclose(fold1);
fclose(fold2);
fclose(fnew);
}
14.e. Find no. of lines, words and characters in a file
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr;
char ch;
int wrd=1,charctr=1;
char fname[20];
printf("\n\n Count the number of words and characters in a file :\n");
printf("---------------------------------------------------------\n");
printf(" Input the filename to be opened : ");
scanf("%s",fname);

fptr=fopen(fname,"r");
if(fptr==NULL)
{
printf(" File does not exist or can not be opened.");
}
else
{
ch=fgetc(fptr);
printf(" The content of the file %s are : ",fname);
while(ch!=EOF)
{
printf("%c",ch);
if(ch==' '||ch=='\n')
{
wrd++;
}
else
{
charctr++;
}
ch=fgetc(fptr);
}
printf("\n The number of words in the file %s are : %d\n",fname,wrd-2);
printf(" The number of characters in the file %s are : %d\n\
n",fname,charctr-1);
}
fclose(fptr);
}
14.f Write a program to print last n characters of a given file
#include<stdio.h>
int main() {
FILE *fp;
char ch;
// Read last num characters from end
int number = 10;
long length;
fp = fopen("file1.txt", "r");
if (fp == NULL) {
puts("cannot open this file");
exit(1);
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, (length - number), SEEK_SET);
do {
ch = fgetc(fp);
putchar(ch);
} while (ch != EOF);
fclose(fp);
return(0);}

You might also like