CP Lab (R23)
CP Lab (R23)
i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
ii) Exposure to Turbo C, gcc
iii) Writing simple programs using printf(), scanf()
i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
LINUX ENVIRONMENT
1. Hardware: This includes peripheral devices like RAM, HDD, and CPU.
2. Kernel: Interacts with the hardware directly and provides low level services to upper layer
components.
3. Shell: This hides the complexity of the functions of a kernel and acts as an interface to it. It
takes commands from users and executes kernel functions.
4. Utilities: Utility programs provide the user with OS functionalities.
VI - EDITOR :-
The default editor that comes with the UNIX operating system is called vi (visual editor).
Using vi editor, we can edit an existing file or create a new file from scratch. we can also use
this editor to just read a text file. The advanced version of the vi editor is the vim editor.
vi [file_name]
Here, [file_name] = this is the file name we want to create or to open the pre-existing file.
MODES OF OPERATIONS
Insert mode:
This mode enables you to insert text into the file. The vi always starts in command mode. To
enter text, you must be in insert mode. To come in insert mode, you simply type i. To get out
of insert mode, press the Esc key, which will put you back into command mode.
To edit the file, we need to be in the insert mode. There are many ways to enter insert mode
from the command mode.
Commands Description
q Quit
vim is an advanced and highly configurable text editor built to enable efficient text editing.
vim text editor is developed by Bram Moolenaar. It supports most file types and vim editor is
also known as a programmer‟s editor. We can use its plugin based on our needs
There are some commands given to use the vim editor. You can see all commands, and it‟s
documentation by help command as follows:
:help
:q!
vim filename.txt
After going into insert mode you will see INSERT in the status bar. After that, we can write
any data in it.
:q
To exit from vim without saving changes type the following command in vim
:q!
:wq
EMACS
emacs is one of the oldest and most versatile text editors. The GNU emacs version was originally
written in 1984 and is well known for its powerful and rich editing features.
$emacs
To start a new file, move the cursor over to the link “Visit New File” by pressing the TAB key
and then press ENTER. A prompt appears at the end of your terminal requesting a file name:
At the top of the screen there is a menu. After the menu, there is a large editing space. This is
called the main buffer where you type your text or view the contents of a file.
Output
Wrote /home/sammy/myfile.txt
We will recommend you to use Turbo C or Turbo C++ IDE, which is the oldest IDE for C
programming. It is freely available over the Internet .
Step 1: Open turbo C IDE(Integrated Development Environment), click on File, and then click
on New
Step 2: After clicking NEW button , A blank screen will be seen in which you can write C
program. Then you can save the file by selecting save option from FILE menu or F2 functional
key
Step 3: Click on Compile menu and then on Compile option, or press the keys and press Alt +
F9 to compile the code.
C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 9
Step 4: Click on Run or press Ctrl + F9 to run the code. Yes, C programs are first compiled to
generate the object code and then that object code is Run.
#include<stdio.h>
int main()
{
//Declaring Three Variables
int x;
printf("Enter The Number : \n");
scanf("%d", &x); //Input Numbers
printf("The Given number is : %d", x);
return 0;
}
OUT PUT:-
Enter The Number: 15
Algorithm :-
Step1: start
Step 2: define x,y,x, sum and avg
Step 3: read x,y,z from keyboard
Step 4: calculate sum and average
Step 5: write sun and average
Step 6: stop
Program:-
#include<stdio.h>
int main()
{
//Declaring Three Variables
int x, y, z, sum;
float avg;
printf("Enter Three Numbers : \n");
scanf("%d %d %d",&x, &y, &z); //Input Numbers
//Calculating Sum of three numbers
sum = x + y +z;
printf("Sum of Three Numbers is : %d", sum);
//Calculating Average of three numbers
avg=sum/3;
printf("\n Average of Three Numbers is : %f", avg);
return 0;
}
Flowchart:-
Program:-
Output:-
Enter Temp in Fahrenheit: 104
Temperature in Celsius: 40
Output :-
Enter Temp in Celsius: 40
Temperature in Fahrenheit: 104
program :-
# include <stdio.h>
int main(){
//Simple interset program
int principal, rate, time, interest;
printf("Enter the principal: ");
scanf("%d", &principal);
printf("Enter the rate: ");
scanf("%d", &rate);
Output:-
Enter the principal: 1000
Enter the rate: 2
Enter the time: 23
The Simple interest is 460
program:-
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main ()
{
// declaration of the int, float and double variables
int x, res;
return 0;
}
Output:-
The square root of 289 is: 17
The square root of 12.25 is: 3.50
The square root of 144.00 is: 12.00
program:-
#include <stdio.h>
#include <math.h>
int main()
{
float principle, rate, time, CI;
/* Input principle, time and rate */
printf("Enter principle (amount): ");
scanf("%f", &principle);
printf("Enter time: ");
scanf("%f", &time);
printf("Enter rate: ");
scanf("%f", &rate);
/* Calculate compound interest */
CI = principle* (pow((1 + rate / 100), time));
/* Print the resultant CI */
printf("Compound Interest = %f", CI);
return 0;
}
Output :-
Enter principle (amount): 1200
Enter time: 2
Enter rate: 5.4
Compound Interest = 1333.099243
program:-
#include<stdio.h>
#include<math.h>
int main()
{
float a, b, c, Perimeter, s, Area;
printf("\nPlease Enter three sides of triangle\n");
scanf("%f%f%f",&a,&b,&c);
Perimeter = a+b+c;
s = (a+b+c)/2;
Area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("\n Perimeter of Traiangle = %.2f\n", Perimeter);
printf("\n Semi Perimeter of Traiangle = %.2f\n", s);
printf("\n Area of triangle = %.2f\n",Area);
return 0;
}
Output:-
#include<stdio.h>
void main()
{
float u,a,t,v,s;
printf("\n Enter initial velocity: ");
scanf("%f",&u);
printf("\n Enter acceleration: ");
scanf("%f",&a);
printf("\n Enter time required: ");
scanf("%f",&t);
s=(u*t)+(a*t*t)/2;
printf("\n \n The distance traveled is : %f \n \n",s);
}
OUTPUT
Enter acceleration: 12
Lab4: Simple computational problems using the operator‟ precedence and associativity
i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
ii) Find the maximum of three numbers using conditional operator
iii) Take marks of 5 subjects in integers, and find the total, average in float
#include <stdio.h>
int main()
{
int A,B,C,D,E,F,G,sum;
printf("enter the values of A,B,C,D,E,F,G:");
scanf("%d%d%d%d%d%d%d",&A,&B,&C,&D,&E,&F,&G);
sum=A+B*C+(D*E) + F*G;
printf("value of A+B*C+(D*E) + F*G is =%d",sum);
return 0;
}
Output:-
enter the values of A,B,C,D,E,F,G:1 2 3 4 5 6 7
value of A+B*C+(D*E) + F*G is =69
b. A/B*C-B+A*D/3
#include <stdio.h>
int main()
{
int A,B,C,D,sum;
printf("enter the values of A,B,C,D:");
scanf("%d%d%d%d",&A,&B,&C,&D);
sum=A/B*C-B+A*D/3;
printf("value of A/B*C-B+A*D/3 is =%d",sum);
return 0;
}
output:-
enter the values of A,B,C,D:20 5 4 8
value of A/B*C-B+A*D/3 is =64
c. A+++B---A
The expression A+++B---A is evaluated in the following form
A+++B---A = (A++)+(B--)-A
IF a=10 AND B=20 then
(10++)+(20--)-10
10+20-11
19
d. J= (i++) + (++i)
#include <stdio.h>
int main()
{
int i,j;
printf("enter the value of i:");
scanf("%d",&i);
j= (i++) + (++i) ;
printf("value of (i++) + (++i) is =%d",j);
return 0;
}
Output:-
enter the value of i:10
value of (i++) + (++i) is =22
# include <stdio.h>
int main()
{
int a, b, c, big ;
printf("Enter three numbers : ") ;
Output :-
Enter three numbers: 44 55 22
iii) Take marks of 5 subjects in integers, and find the total, average in float
#include <stdio.h>
int main()
{
int eng, phy, chem, math, comp;
float total, average;
/* Input marks of all five subjects */
printf("Enter English marks :");
scanf("%d", &eng);
printf("\nEnter physics marks : ");
scanf("%d", &phy);
printf("\nEnter chemistry marks : ");
scanf("%d", &chem);
printf("\nEnter maths marks : ");
scanf("%d", &math);
printf("\nEnter computer marks : ");
scanf("%d", &comp);
/* Calculate total, average and percentage */
total = eng + phy + chem + math + comp;
average = total / 5.0;
/* Print all results */
printf("\n Total marks = %.2f", total);
printf("\n Average marks = %.2f", average);
i) Write a C program to find the max and min of four numbers using if-else.
#include<stdio.h>
int main()
{
int a,b,c,d;
Output:-
Enter the Four Numbers :1
2
3
4
4 is big
Enter the Four Numbers :10
15
2
1
15 is big
Program:-
#include <stdio.h>
int main()
{
int unit;
float amt, total_amt, sur_charge;
/* Input unit consumed from user */
printf("Enter total units consumed: ");
scanf("%d", &unit);
/* Calculate electricity bill according to given conditions */
if(unit <= 50)
{
amt = unit * 0.50;
}
else if(unit <= 150)
{
amt = 25 + ((unit-50) * 0.75);
}
else if(unit <= 250)
{
amt = 100 + ((unit-150) * 1.20);
}
else
{
amt = 220 + ((unit-250) * 1.50);
}
Output:-
Enter total units consumed: 220
Electricity Bill = Rs. 220.80
The term b2 - 4ac is known as the discriminant of a quadratic equation. It tells the nature of the
roots.
If the discriminant is greater than 0, the roots are real and different.
If the discriminant is less than 0, the roots are complex and different .
#include <math.h>
#include <stdio.h>
int main()
{
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart,
imagPart);
}
return 0;
}
Output:-
Enter coefficients a, b and c: 2 5 6
root1 = -1.25+1.20i and root2 = -1.25-1.20i
#include <stdio.h>
int main()
{
int y;
printf("Enter the year to check: ");
scanf("%d",&y);
if (((y % 4 == 0) && (y % 100!= 0)) || (y%400 == 0))
printf("It is a leap year");
else
printf("It is not a leap year");
return 0;
}
Output:-
Enter the year to check: 2000
It is a leap year
Output:-
Enter The Number: 5
The Factorial of 5 is: 120
For example,
Sine Series:
Sine Series is a series which is used to find the value of Sin(x). where, x is the angle
in degree which is converted to Radian. The formula used to express the Sin(x) as Sine Series is
Program:-
#include<stdio.h>
int main()
int i, n;
scanf("%f",&x);
scanf("%d",&n);
x=x*3.14159/180;
t1=x;
sum1=x;
t=t*(-1)*x*x/(2*i*(2*i-1));
sum=sum+t;
for(i=1;i<=n;i++)
t1=(t1*(-1)*x*x)/(2*i*(2*i+1));
sum1=sum1+t1;
return 0;
}
Output:-
Enter the value for x : 45
Enter the value for (no of terms to sum) n : 5
The value of Cos(0.785398) is : 0.7071
The value of Sin(0.785398) = 0.7071
#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number=");
scanf("%d",&n);
temp=n;
while(n>0)
Output:-
#include <stdio.h>
int main() {
int i, space, rows, k = 0, count = 0, count1 = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (space = 1; space <= rows - i; ++space) {
printf(" ");
++count;
}
while (k != 2 * i - 1) {
if (count <= rows - 1) {
printf("%d ", i + k);
++count;
} else {
++count1;
printf("%d ", (i + k - 2 * count1));
}
Output:-
Enter the number of rows: 5
1
232
34543
4567654
567898765
#include <stdio.h>
int main()
{
int a[1000],i,n,min,max;
return 0;
}
Output:-
Enter size of the array : 5
Enter elements in array : 23
21
56
43
8
minimum element of array is : 8
maximum element of array is : 56
#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");
return 0;
}
Output:-
Enter number of elements in array
5
Enter 5 integer(s)
23
43
12
56
77
Enter a number to search
12
12 is present at location 3.
#include<stdio.h>
int main()
In short, we can say that the 2s complement is defined as the sum of the one's complement and
one.
Program:-
#include <stdio.h>
int main()
{
int n; // variable declaration
printf("Enter the number of bits do you want to enter :");
scanf("%d",&n);
char binary[n+1]; // binary array declaration;
char onescomplement[n+1]; // onescomplement array declaration
char twoscomplement[n+1]; // twoscomplement array declaration
int carry=1; // variable initialization
printf("\nEnter the binary number : ");
scanf("%s", binary);
printf("The given binary number is :%s", binary);
printf("\nThe ones complement of the binary number is :");
// Finding onescomplement in C
for(int i=0;i<n;i++)
{
if(binary[i]=='0')
return 0;
}
Output:-
Enter the number of rows (between 1 and 100): 2
Enter the number of columns (between 1 and 100): 2
#include<stdio.h>
int main()
{
int r1,r2,c1,c2;
printf("Enter number of rows for First Matrix:\n");
scanf("%d",&r1);
printf("Enter number of columns for First Matrix:\n");
scanf("%d",&c1);
printf("Enter number of rows for Second Matrix:\n");
scanf("%d",&r2);
printf("Enter number of columns for Second Matrix:\n");
scanf("%d",&c2);
if(c1!=r2)
{
printf("Matrices Can't be multiplied together");
Multiplied matrix
30 24 88
84 69 334
138 114 580
2. For example:
If we have the array as {40,10,50,70,30}
and we apply bubble sort to sort the array,
then the resultant array after each iteration will be as follows:
Original array: {40, 10, 50, 70, 30}
Program:-
#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 '<' instead of '>' */
{
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:-
Enter number of elements
5
Enter 5 integers
2
1
4
3
0
Sorted list in ascending order:
0
#include<stdio.h>
int main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
return 0;
}
Output:-
Enter First String:hai
Output:-
Input a string
srikar
rakirs
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
int count;
int *arr;
int sum = 0;
printf("Enter the total number of elements you want to enter : ");
scanf("%d", &count);
arr = (int *)malloc(count * sizeof(int));
for (i = 0; i < count; i++)
{
printf("Enter element %d : ", (i + 1));
scanf("%d", arr + i);
sum += *(arr + i);
}
free(arr);
Output:-
ii) Write a C program to find the total, average of n students using structures
#include<stdio.h>
struct student
{
char name[10];
float m1,m2,m3;
float avg,total;
};
void main()
{
struct student s[20];
int n,i;
float tavg,sum=0.0;
printf("Enter the number of student=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the detail of student-%d \n",i+1);
printf("Enter Name=");
scanf("%s",s[i].name);
printf("Enter the subject-1 score :");
scanf("%f",&s[i].m1);
printf("\n Enter the subject-2 score :");
scanf("%f",&s[i].m2);
printf("\n Enter the subject-3 score :");
scanf("%f",&s[i].m3);
s[i].total=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].total/3;
}
for(i=0;i<n;i++)
{
printf("\n student-%d details ",i+1);
student-1 details
total marks :253.000000
average marks : 84.333336
student-2 details
total marks :243.000000
average marks : 81.000000
iii) Enter n students data using calloc() and display failed students list
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// student structure
struct student {
char roll_no[10];
char name[64];
int m1,m2,m3,m4,m5;
};
// new type
// variables
int no_of_students;
int i,total,count=0;
printf("Enter the no_of students: ");
scanf("%d",&no_of_students);
iv) Read student name and marks from the command line and display the student details
along with the total.
#include<stdio.h>
int main(int argc,char *argv[])
{
int i,avg,count=0;sum=0;
int c=argc;
printf(“Name of the student=%s”,argv[1]);
for(i=2;i<c;i++)
{
Sum+=atoi(argv[i]);
Count++;
}
Avg=sum/count;
Printf(“\n Sum=%d”,sum);
Printf(“\n Average=%d”,avg);
}
Output:-
C:\TURBOC3\SOURCE>ss.exe srikar 10 20 30 40
Name of the student= srikar
Sum =100
Average=25
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*) malloc(3 * sizeof(int));
ptr[0] = 1;
ptr[1] = 2;
C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 59
ptr[2] = 3;
Output :-
12345
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num; //Data of the node
struct node *nextptr; //Address of the node
}*stnode;
int main()
{
void displayList()
{
int i=1;
struct node *tmp;
if(stnode == NULL)
{
printf(" No data found in the list.");
}
else
{
tmp = stnode;
while(tmp != NULL)
{
printf(" node - %i Data = %d\n", i,tmp->num); // prints the data of current node
tmp = tmp->nextptr;
i++;// advances the position of current node
}
}
}
Output:-
Input the number of nodes : 3
Input data for node 1 : 10
Input data for node 2 : 20
Input data for node 3 : 30
iv) Write a C program to copy one structure variable to another structure of the same type.
Lab 11: Simple functions using call by value, solving differential equations using Eulers
theorem.
i) Write a C function to calculate NCR value.
ii) Write a C function to find the length of a string.
iii) Write a C function to transpose of a matrix.
iv) Write a C function to demonstrate numerical integration of differential equations using
Euler’s method
The total number of ways for selecting r elements out of n options are
nCr = (n!) / (r! * (n-r)!)
#include <stdio.h>
int fact(int z);
void main()
{
int n, r, nCr;
printf("Enter the value of n and r?");
scanf("%d %d",&n,&r);
nCr = fact(n) / (fact(r) * fact(n - r));
printf("\nnCr = %d", nCr);
}
int fact(int z)
#include<stdio.h>
int FindLength(char str[]);
int main() {
char str[100];
int length;
length = FindLength(str);
#include <stdio.h>
void main()
{
static int a[10][10];
Mathematically, here, the curve of the solution is approximated by a sequence of short lines i.e.
by the tangent line in each interval. (Derivation) Using this information, the value of the value
of „yn‟ corresponding to the value of „xn„ is to determined by dividing the length (xn – x) into n
strips.Therefore, strip width= (xn – x)/n and xn=x0+ nh.
Again, if m be the slope of the curve at point, y1= y0 + m(x0 , yo)h.
Program :-
#include<stdio.h>
float fun(float x,float y)
{
float f;
f=x+y;
return f;
}
main()
{
float a,b,x,y,h,t,k;
printf("\nEnter x0,y0,h,xn: ");
scanf("%f%f%f%f",&a,&b,&h,&t);
x=a;
y=b;
x y
4.000 11.000
7.000 56.000
LCM stands for Least Common Multiple. It is a method to find the lowest common multiple
between the two numbers. LCM of two numbers is the lowest possible number that is divisible
by both numbers.
Examples: LCM(10,15) = 30, LCM(18,26) = 234.
Program:-
#include <stdio.h>
int lcm(int, int);
int main()
{
int a, b, result;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
result = lcm(a, b); //call the function lcm recursively.
printf("The LCM of %d and %d is %d\n", a, b, result);
return 0;
}
#include<stdio.h>
long int factorial(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
return 0;
}
The Ackermann function, named after the German mathematician Wilhelm Ackermann, is a
recursive mathematical function that takes two non-negative integers as inputs and produces a
non-negative integer as its output. In C, the Ackermann function can be implemented using
recursion.
Output:-
Enter two numbers ::
2
3
Result :: 9
int main()
{
int num;
if (num == 0)
{
printf("Sum of first N numbers is %d\n", sum);
return;
}
else
{
sum += num;
display_sum(--num);
}
}
Output:-
Enter the Nth number: 5
Sum of first N numbers is 15
#include <stdio.h>
void swap(int*, int*);
int main()
C-PROGRAMMING LAB[R-23] SRKR ENGINEERING COLLEGE Page 73
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
Dangling Pointers in C
The most common bugs related to pointers and memory management is dangling/wild pointers.
Sometimes the programmer fails to initialize the pointer with a valid address, and then this type
of initialized pointer is known as a dangling pointer in C.
Dangling pointer occurs at the time of the object destruction when the object is deleted or de-
allocated from memory without modifying the value of the pointer. In this case, the pointer is
pointing to the memory, which is de-allocated. The dangling pointer can point to the memory,
which contains either the program code or the code of the operating system. If we assign the
value to this pointer, then it overwrites the value of the program code or operating system
instructions; in such cases, the program will show the undesirable result or may even crash. If the
Program:-
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr=(int*)malloc(sizeof(int));
*ptr=10;
printf("value of ptr=%d",*ptr);
free(ptr); /free the ptr memory but still it points the memory
printf("\n At dangling point ptr value is: %d",*ptr);
ptr=NULL; // free the pointer
}
Output:-
value of ptr=10
At dangling point ptr value is: 1588739705 //garbage value
iii) Write a C program to copy one string into another using pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
char *str1, *str2;
int i;
clrscr();
printf("Enter the string : ");
scanf("%s", str2);
for(i = 0; *str2 != '\0'; i++, str1++, str2++)
*str1 = *str2;
*str1 = '\0';
str1 = str1 - i;
printf("\nThe copied string is : %s", str1);
getch();
}
Output:-
iv) Write a C program to find no of lowercase, uppercase, digits and other characters using
pointers.
#include <string.h>
int main()
{
char s[1000],*p;
int alphabets=0,digits=0,specialcharacters=0;
p=s;
while(*p)
{
if( (*p>=65 && *p<=90) || (*p>=97 && *p<=122 ) )
alphabets++;
else if(*p>=48 && *p<=57)
digits++;
else
specialcharacters++;
p++;
}
printf("Alphabets = %d\n",alphabets);
printf("Digits = %d\n",digits);
printf("Special characters = %d", specialcharacters);
}
Output:-
Enter the string: srikar@1974
Alphabets = 6
Digits = 4
Special characters = 1
#include<stdio.h>
#include<stdlib.h>
main()
{
char name[30];
int i,score,n;
FILE *f1;
f1=fopen("marks.txt","w");
printf("Enter the no of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the name:");
scanf("%s",name);
printf("Enter the score:");
scanf("%d",&score);
fprintf(f1,"\n%s",name);
fprintf(f1,"\t%d",score);
printf("\n");
}
fclose(f1);
f1=fopen("marks.txt","r");
while(fscanf(f1,"%s%d",&name,&score)!=EOF)
{
printf("\n Name=%s",name);
struct threeNum
{
int n1,n2,n3;
};
main()
{
int n;
struct threeNum num;
FILE *fp;
clrscr();
if((fp=fopen("srikar1.bin","wb"))==NULL)
{
printf("Error opening file:");
exit(1);
}
fread(&num,sizeof(struct threeNum),1,fp);
printf("n1=%d\tn2=%d\tn3=%d",num.n1,num.n2,num.n3);
fclose(fp);
}
Output:-
Enter the n value:5
n1=5 n2=25 n=26
iii) Copy the contents of one file to another file.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
Output :-
iv) Write a C program to merge two files into the third file using command-line arguments.
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main(int argc, char *argv[])
{
FILE *fp1,*fp2,*fp3;
int main()
{
FILE * file;
char path[100];
exit(EXIT_FAILURE);
}
/*
* Logic to count characters, words and lines.
*/
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;
/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
return 0;
}
Output:-
Enter the source file name:a1.txt
Characters :26
Words: 1
Lines: 1
a1.txt
ABCDEFGHIJKLMNOPQRSTUVWXYZ
#include<stdio.h>
#include<process.h>
int main()
{
FILE *fp;
char ch;
int num;
long length;
printf("Enter the no of characters :");
scanf("%d",&num);
fp=fopen("a1.txt","r");
if(fp==NULL)
{
puts("Cannot open this file");