Exercise-10
Write a program to demonstrate the use of
pointers in C
#include<stdio.h>
int main()
{
int a=10;
int *ptr;
ptr=&a;
printf("\n the value of a is %d",a);
printf("\n the address of a is %u",&a);
printf("\n the value of pointer ptr=%u",ptr);
printf("\n the address of pointer ptr=
%u",&ptr);
printf("\n the value of pointer pointing to
%d",*ptr);
}
Write a program to swap two numbers using
functions and pointers (both call by value and call
by reference)
Call by value
#include<stdio.h>
void swap(int x,int y);
int main()
{
int a,b;
printf("enter a,b values:");
scanf("%d %d",&a,&b);
printf("\n Before swapping:");
printf("a=%d\t b=%d",a,b);
swap(a,b);//acctual parameters
printf("\n after swapping:");
printf("a=%d\t b=%d",a,b);
}
void swap(int x,int y)//formal parameters
{
int t;
t=x;
x=y;
y=t;
}
Call by reference
#include<stdio.h>
void swap(int *x,int *y);
int main()
{
int a,b;
printf("enter a,b values:");
scanf("%d %d",&a,&b);
printf("\n Before swapping:");
printf("a=%d\t b=%d",a,b);
swap(&a,&b);//acctual parameters
printf("\n after swapping:");
printf("a=%d\t b=%d",a,b);
}
void swap(int *x,int *y)//formal parameters
{
int t;
t=*x;
*x=*y;
*y=t;
}
//program
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr;
printf("enter number of elements:");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
printf("enter elements:");
for(i=0;i<n;i++)
{
scanf("%d",ptr+i);
}
for(i=0;i<n;i++)
{
printf("%d",*(ptr+i));
}
free(ptr);
}
EXERCISE 11
//Program to create file,add text,close file
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("C:\\Users\\kumar\\OneDrive\\
Desktop\\prasaswi\\file1.txt","w");
fprintf(fp,"aditya university");
fclose(fp);
}
//program to read a file
#include<stdio.h>
int main()
{
FILE *fp;
char b[50];
fp=fopen("C:\\Users\\kumar\\OneDrive\\
Desktop\\prasaswi\\file1.txt","r");
while(fscanf(fp,"%s",b)!=EOF)
{
printf("%s",b);
}
fclose(fp);
}
//Program to copy the content of one file to
another file
#include<stdio.h>
int main()
{
char ch;
FILE *fp1,*fp2;
fp1=fopen("C:\\Users\\kumar\\OneDrive\\
Desktop\\prasaswi\\file1.txt","r");
fp2=fopen("C:\\Users\\kumar\\OneDrive\\
Desktop\\prasaswi\\file2.txt","w");
ch=fgetc(fp1);
while(ch!=EOF)
{
fputc(ch,fp2);
ch=fgetc(fp1);
}
fclose(fp2);
fclose(fp1);
}