SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 1
C programs
Week 1:
a) Write a C program to exchange the values between two variables with and without using
temporary variable.
Program code:
/* using temporary variable */
#include <stdio.h>
int main()
{
doublefirstNumber, secondNumber, temporaryVariable;
printf("Enter first number: ");
scanf("%lf", &firstNumber);
printf("Enter second number: ");
scanf("%lf",&secondNumber);
// Value of firstNumber is assigned to temporaryVariable
temporaryVariable = firstNumber;
// Value of secondNumber is assigned to firstNumber
firstNumber = secondNumber;
// Value of temporaryVariable (which contains the initial value of firstNumber) is assigned to
secondNumber
secondNumber = temporaryVariable;
printf("nAfter swapping, firstNumber = %.2lfn", firstNumber);
printf("After swapping, secondNumber = %.2lf", secondNumber);
return 0;
}
Output:
Enter first number: 1.20
Enter second number: 2.45
After swapping, firstNumber = 2.45
After swapping, secondNumber = 1.20
/*without using temporary variable */
#include <stdio.h>
int main()
{
doublefirstNumber, secondNumber;
printf("Enter first number: ");
scanf("%lf", &firstNumber);
printf("Enter second number: ");
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 2
scanf("%lf",&secondNumber);
// Swapping process
firstNumber = firstNumber - secondNumber;
secondNumber = firstNumber + secondNumber;
firstNumber = secondNumber - firstNumber;
printf("nAfter swapping, firstNumber = %.2lfn", firstNumber);
printf("After swapping, secondNumber = %.2lf", secondNumber);
return 0;
}
Output:
Enter first number: 10.25
Enter second number: -12.5
After swapping, firstNumber = -12.50
After swapping, secondNumber = 10.25
b) Write a C program to find the sum of individual digits of a positive integer.
Program Code:
#include<stdio.h>
int main()
{
intn,sum=0,m;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
m=n%10;
sum=sum+m;
n=n/10;
}
printf("Sum is=%d",sum);
return 0;
}
Output:
Enter a number:654
Sum is=15
c) Write a C program to generate all the factors of 4 and 7 between 1 and n and count their value,
where n is a value supplied by the user.
#include <stdio.h>
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 3
int main()
{
int number, i;
printf("Enter a positive integer: ");
scanf("%d",&number);
printf("Factors of 4 are: ", number);
for(i=1; i<= number; ++i)
{
if (4%i == 0)
{
printf("%d ",i);
}
}
printf("Factors of 7 are: ", number);
for(i=1; i<= number; ++i)
{
if (7%i == 0)
{
printf("%d ",i);
}
}
return 0;
}
Output:
Enter a positive integer: 10
The Factors of 4 are: 1 2 4
The factors of 7 are: 1 7
Week 2:
a) Write a C program to compute the factorial of a given number.
Program Code:
#include <stdio.h>
int main()
{
int n, i;
unsigned long long factorial = 1;
printf("Enter an integer: ");
scanf("%d",&n);
// show error if the user enters a negative integer
if (n < 0)
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 4
printf("Error! Factorial of a negative number doesn't exist.");
else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of %d = %llu", n, factorial);
}
return 0;
}
Output:
Enter an integer: 10
Factorial of 10 = 3628800
b) Write a C program to compute the Sine function.
Program Code:
/*
* C program to find the value of sin(x) using the series
* up to the given accuracy (without using user defined function)
* also print sin(x) using library function.
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
int n, x1;
float accuracy, term, denominator, x, sinx, sinval;
printf("Enter the value of x (in degrees) n");
scanf("%f", &x);
x1 = x;
/* Converting degrees to radians */
x = x * (3.142 / 180.0);
sinval = sin(x);
printf("Enter the accuracy for the result n");
scanf("%f", &accuracy);
term = x;
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 5
sinx = term;
n = 1;
do
{
denominator = 2 * n * (2 * n + 1);
term = -term * x * x / denominator;
sinx = sinx + term;
n = n + 1;
} while (accuracy <= fabs(sinval - sinx));
printf("Sum of the sine series = %f n", sinx);
printf("Using Library function sin(%d) = %fn", x1, sin(x));
}
Output:
Enter the value of x (in degrees)
60
Enter the accuracy for the result
0.86602540378443864676372317075294
Sum of the sine series = 0.855862
Using Library function sin(60) = 0.866093
Week 3:
a) Write a C program to generate the first n terms of the Fibonacci sequence.
Program code:
#include <stdio.h>
int main()
{
int t1 = 0, t2 = 1, nextTerm = 0, n;
printf("Enter a positive number: ");
scanf("%d", &n);
// displays the first two terms which is always 0 and 1
printf("Fibonacci Series: %d, %d, ", t1, t2);
nextTerm = t1 + t2;
while(nextTerm<= n)
{
printf("%d, ",nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 6
}
Output:
Enter a positive integer: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
b) Write a C program to reverse the digits of a given integer
Program code:
#include <stdio.h>
int main()
{
int n, reversedNumber = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &n);
while(n != 0)
{
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
printf("Reversed Number = %d", reversedNumber);
return 0;
}
Output:
Enter an integer: 2345
Reversed Number = 5432
Week 4
a) Write a C program to covert the given decimal number into its equivalent binary, octal and
hexadecimal number.
Program Code:
#include<stdio.h>
#include<stdlib.h>
void conversion(intnum, int base)
{
int remainder = num % base;
if(num == 0)
{
return;
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 7
}
conversion(num / base, base);
if(remainder < 10)
{
printf("%d", remainder);
}
else
{
printf("%c", remainder - 10 + 'A' );
}
}
int main()
{
intnum, choice;
printf("nEnter a Positive Decimal Number:t");
scanf("%d", &num);
while(1)
{
printf("n1. Decimal To Binary Conversion");
printf("n2. Decimal To Octal Conversion");
printf("n3. Decimal To Hexadecimal Conversion");
printf("n4. Quit");
printf("nEnter Your Option:t");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("nBinary Value:t");
conversion(num, 2);
break;
case 2: printf("nOctal Value:t");
conversion(num, 8);
break;
case 3: printf("nHexadecimal Value:t");
conversion(num, 16);
break;
case 4: exit(0);
default: printf("Enter a correct inputn");
}
}
printf("n");
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 8
return 0;
}
Output:
Enter a positive Decimal Number:
1.Decimal To Binary Conversion
2.Decimal To Octal Conversion
3.Decimal To Hexadecimal Conversion
4.Quit
Enter your Option: 1
Binary Value: 1010
1.Decimal To Binary Conversion
2.Decimal To Octal Conversion
3.Decimal To Hexadecimal Conversion
4.Quit
Enter Your option: 2
Octal Value: 12
1.Decimal To Binary Conversion
2.Decimal To Octal Conversion
3.Decimal To Hexadecimal Conversion
4.Quit
Enter your option: 3
Hexadecimal Value : A
1.Decimal To Binary Conversion
2.Decimal To Octal Conversion
3.Decimal To Hexadecimal Conversion
4.Quit
Enter your option: 4
b) Write a C program to calculate the following: Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!.
Program Code:
// C program to get the sum of the series
#include <math.h>
#include <stdio.h>
// Function to get the series
double Series(double x, int n)
{
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 9
double sum = 1, term = 1, fct, j, y = 2, m;
// Sum of n-1 terms starting from 2nd term
inti;
for (i = 1; i< n; i++) {
fct = 1;
for (j = 1; j <= y; j++) {
fct = fct * j;
}
term = term * (-1);
m = term * pow(x, y) / fct;
sum = sum + m;
y += 2;
}
return sum;
}
// Driver Code
int main()
{
double x = 9;
int n = 10;
printf("%.4f", Series(x, n));
return 0;
}
Output:
-5.1463
c)Write a C program, which takes two integer operands and one operator from the user,
performs the operation and then prints the result.
Program Code:
#include<stdio.h>
int main()
{
inta,b,res;
char c;
printf ("Enter any one operator +, -, *, / n");
scanf("%c", &c);
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 10
printf ("n Enter two numbers n");
scanf ("n %d n %d",&a, &b);
switch(c)
{
case '+': res=a+b;
printf("n The sum is %d",res);
break;
case '-': res=a-b;
printf("n The difference is %d",res);
break;
case '*': res=a*b;
printf("n The product is %d",res);
break;
case '/': res=a/b;
printf("n The quotient is %d",res);
break;
default: printf ("n Invalid entry");
}
return 0;
}
Output:
Case 1:
Enter any one operator +, -, *, /
+
Enter two numbers
5
3
The sum is 8
Case 2:
Enter any one operator +, -, *, /
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 11
/
Enter two numbers
100
20
The quotient is 5
Week 5
a) Write C program to display the result of a student by considering the standard grades.
Program code:
#include<stdio.h>
void main()
{
int marks;
printf("Enter your marks ");
scanf("%d",&marks);
if(marks<0 || marks>100)
{
printf("Wrong Entry");
}
else if(marks<50)
{
printf("Grade F");
}
else if(marks>=50 && marks<60)
{
printf("Grade D");
}
else if(marks>=60 && marks<70)
{
printf("Grade C");
}
else if(marks>=70 && marks<80)
{
printf("Grade B");
}
else if(marks>=80 && marks<90)
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 12
{
printf("Grade A");
}
else
{
printf("Grade A+");
}
}
Output:
Enter your marks 67
Grade C
press any key to continue.
b)Write a C Program to find both largest and smallest in the given list of integers.
Program code:
#include<stdio.h>
int main()
{
inti, n, lar,sm, elem;
printf ("Enter total number of elements n");
scanf ("%d", &elem);
printf ("Enter first number n");
scanf ("%d", &n);
lar = n;
sm=n;
for (i=1; i<= elem -1 ; i++)
{
printf ("n Enter another number n");
scanf ("%d",&n);
if (n>lar)
lar=n;
if (n<sm)
sm=n;
}
printf ("n The largest number is %d", lar);
printf ("n The smallest number is %d", sm);
return 0;
}
Output:
Enter total number of elements
10
Enter first number
3
Enter another number
8
Enter another number
12
Enter another number
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 13
42
Enter another number
89
Enter another number
45
Enter another number
236
Enter another number
890
Enter another number
411
Enter another number
328
The largest number is 890
The smallest number is 3
Week 6
a) Write a C program to generate Pascal’s triangle.
Program Code:
#include <stdio.h>
int main()
{
int rows, cal = 1, space, i, j;
printf("Enter number of rows: ");//enter number of rows for generating the pascal triangle
scanf("%d",&rows);
for(i=0; i<rows; i++) // outer loop for displaying rows
{
for(space=1; space <= rows-i; space++) // space for every row starting
printf(" ");
for(j=0; j <= i; j++) // inner loop for displaying the pascal triangle of numbers
{
if (j==0 || i==0) // either outer loop value or inner-loop value is "0 " it prints 1
cal = 1;
else
cal = cal*(i-j+1)/j; //calculate the coefficient
printf("%4d", cal);
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 14
}
printf("n");
}
return 0;
}
Output:
Enter number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
b) Write a C program to construct a pyramid of numbers
Program Code:
#include<stdio.h>
#include<stdlib.h>
int main(){
inti,j,k,l,n;
system("cls");
printf("enter the range=");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(k=1;k<=i;k++)
{
printf("%d",k);
}
for(l=i-1;l>=1;l--)
{
printf("%d",l);
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 15
}
printf("n");
}
return 0;
}
Output:
enter the range= 4
1
121
12321
1234321
Week 7
a)Write a c program
1) To find square root of a given integer.
Program Code:
/**
* C program to find square root of a number
*/
#include <stdio.h>
#include <math.h>
int main()
{
doublenum, root;
/* Input a number from user */
printf("Enter any number to find square root: ");
scanf("%lf", &num);
/* Calculate square root of num */
root = sqrt(num);
/* Print the resultant value */
printf("Square root of %.2lf = %.2lf", num, root);
return 0;
}
Output:
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 16
Enter any number to find square root: 144
Square root of 144.00=12.00
2) To find the smallest Divisor of a number
Program Code:
// C++ program to count the number of
// subarrays that having 1
#include <bits/stdc++.h>
using namespace std;
// Function to find the smallest divisor
intsmallestDivisor(int n)
{
// if divisible by 2
if (n % 2 == 0)
return 2;
// iterate from 3 to sqrt(n)
for (inti = 3; i * i<= n; i += 2) {
if (n % i == 0)
returni;
}
return n;
}
// Driver Code
int main()
{
int n = 31;
cout<<smallestDivisor(n);
return 0;
}
Output:
31
3) To raise the number to large power.
Program Code:
#include <stdio.h>
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 17
int main()
{
int base, exponent;
longlong 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:
Enter a base number: 3
Enter an exponent: 4
Answer = 81
4)To generate the prime numbers from 1 to n
Program Code:
/**
* C program to print all prime numbers between 1 to n
*/
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 18
#include <stdio.h>
int main()
{
inti, j, end, isPrime; // isPrime is used as flag variable
/* Input upper limit to print prime */
printf("Find prime numbers between 1 to : ");
scanf("%d", &end);
printf("All prime numbers between 1 to %d are:n", end);
/* Find all Prime numbers between 1 to end */
for(i=2; i<=end; i++)
{
/* Assume that the current number is Prime */
isPrime = 1;
/* Check if the current number i is prime or not */
for(j=2; j<=i/2; j++)
{
/*
* If i is divisible by any number other than 1 and self
* then it is not prime number
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 19
*/
if(i%j==0)
{
isPrime = 0;
break;
}
}
/* If the number is prime then print */
if(isPrime==1)
{
printf("%d, ", i);
}
}
return 0;
}
Output:
Find Prime numbers between 1 to 10
All prime numbers between 1 to 10 are:
2 3 5 7
Week 8
1)C program to computer prime factor of an integer
Program code:
// Program to print all prime factors
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 20
# include <stdio.h>
# include <math.h>
// A function to print all prime factors of a given number n
voidprimeFactors(int n)
{
// Print the number of 2s that divide n
while (n%2 == 0)
{
printf("%d ", 2);
n = n/2;
}
// n must be odd at this point. So we can skip
// one element (Note i = i +2)
for (inti = 3; i<= sqrt(n); i = i+2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
printf("%d ", i);
n = n/i;
}
}
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 21
// This condition is to handle the case when n
// is a prime number greater than 2
if (n > 2)
printf ("%d ", n);
}
/* Driver program to test above function */
int main()
{
int n = 315;
primeFactors(n);
return 0;
}
Output:
3 3 5 7
2)
C program to generate pseudorandom number in c
Program code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int c, n;
printf("Ten random numbers in [1,100]n");
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 22
for (c = 1; c <= 5; c++) {
n = rand() % 100 + 1;
printf("%dn", n);
}
return 0;
}
Output:
3569
254
57
5
9675
3)
C Program to find GCD of two numbers
Program code:
#include <stdio.h>
int main()
{
int n1, n2, i, gcd;
printf("Enter two integers: ");
scanf("%d %d", &n1, &n2);
for(i=1; i<= n1 &&i<= n2; ++i)
{
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 23
// Checks if i is factor of both integers
if(n1%i==0 && n2%i==0)
gcd = i;
}
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
return 0;
}
Output:
Enter two positive integers: 81
153
GCD = 9
4)
C program to compute nth Fibonacci number
Program code:
/*
* C Program to find the nth number in Fibonacci series using recursion
*/
#include <stdio.h>
intfibo(int);
int main()
{
intnum;
int result;
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 24
printf("Enter the nth number in fibonacci series: ");
scanf("%d", &num);
if (num< 0)
{
printf("Fibonacci of negative number is not possible.n");
}
else
{
result = fibo(num);
printf("The %d number in fibonacci series is %dn", num, result);
}
return 0;
}
intfibo(intnum)
{
if (num == 0)
{
return 0;
}
else if (num == 1)
{
return 1;
}
else
{
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 25
return(fibo(num - 1) + fibo(num - 2));
}
}
Output:
Enter the nth number in fibonacci series: 8
The 8 number in fibonacci series is 21
Week 9
1) To find the both the largest and smallest number in the a list of integers
Program code:
#include<stdio.h>
int main()
{
inti, n, lar,sm, elem;
printf ("Enter total number of elements n");
scanf ("%d", &elem);
printf ("Enter first number n");
scanf ("%d", &n);
lar = n;
sm=n;
for (i=1; i<= elem -1 ; i++)
{
printf ("n Enter another number n");
scanf ("%d",&n);
if (n>lar)
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 26
lar=n;
if (n<sm)
sm=n;
}
printf ("n The largest number is %d", lar);
printf ("n The smallest number is %d", sm);
return 0;
}
Output:
Enter total number of elements
10
Enter first number
3
Enter another number
8
Enter another number
12
Enter another number
42
Enter another number
89
Enter another number
45
Enter another number
236
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 27
Enter another number
890
Enter another number
411
Enter another number
328
The largest number is 890
The smallest number is 3
2)
a.)c program to find the addition of two matrices
Program code:
#include <stdio.h>
int main(){
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("nEnter elements of 1st matrix:n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d",&a[i][j]);
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 28
}
printf("Enter elements of 2nd matrix:n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("Enter element a%d%d: ",i+1, j+1);
scanf("%d", &b[i][j]);
}
// Adding Two matrices
for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
sum[i][j]=a[i][j]+b[i][j];
}
// Displaying the result
printf("nSum of two matrices: n");
for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
printf("%d ",sum[i][j]);
if(j==c-1)
{
printf("nn");
}
}
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 29
return 0;
}
Output:
Enter number of rows (between 1 and 100): 2
Enter number of columns (between 1 and 100): 3
Enter elements of 1st matrix:
Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
Enter element a11: -4
Enter element a12: 5
Enter element a13: 3
Enter element a21: 5
Enter element a22: 6
Enter element a23: 3
Sum of two matrices:
-2 8 7
10 8 6
b)c program for multiplication of two matrices
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 30
Program code:
#include <stdio.h>
int main()
{
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
// Column of first matrix should be equal to column of second matrix and
while (c1 != r2)
{
printf("Error! column of first matrix not equal to row of second.nn");
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
}
// Storing elements of first matrix.
printf("nEnter elements of matrix 1:n");
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
printf("Enter elements a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 31
}
// Storing elements of second matrix.
printf("nEnter elements of matrix 2:n");
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
printf("Enter elements b%d%d: ",i+1, j+1);
scanf("%d",&b[i][j]);
}
// Initializing all elements of result matrix to 0
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
result[i][j] = 0;
}
// Multiplying matrices a and b and
// storing result in result matrix
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
result[i][j]+=a[i][k]*b[k][j];
}
// Displaying the result
printf("nOutput Matrix:n");
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 32
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
printf("%d ", result[i][j]);
if(j == c2-1)
printf("nn");
}
return 0;
}
Output:
Enter rows and column for first matrix: 3
2
Enter rows and column for second matrix: 3
2
Error! column of first matrix not equal to row of second.
Enter rows and column for first matrix: 2
3
Enter rows and column for second matrix: 3
2
Enter elements of matrix 1:
Enter elements a11: 3
Enter elements a12: -2
Enter elements a13: 5
Enter elements a21: 3
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 33
Enter elements a22: 0
Enter elements a23: 4
Enter elements of matrix 2:
Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4
Output Matrix:
24 29
6 25
Week 10
a)Write a C program that uses functions to perform the following operations:
i) Reading a complex number ii) Writing a complex number
iii) Addition of two complex numbers iv) Multiplication of two complex numbers
Program code:
#include <stdio.h>
#include <conio.h>
struct complex
{
float real, imag;
}a, b, c;
struct complex read(void);
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 34
void write(struct complex);
struct complex add(struct complex, struct complex);
struct complex sub(struct complex, struct complex);
struct complex mul(struct complex, struct complex);
struct complex div(struct complex, struct complex);
void main ()
{
clrscr();
printf("Enter the 1st complex numbern ");
a = read();
write(a);
printf("Enter the 2nd complex numbern");
b = read();
write(b);
printf("Additionn ");
c = add(a, b);
write(c);
printf("Substractionn ");
c = sub(a, b);
write(c);
printf("Multiplicationn");
c = mul(a, b);
write(c);
printf("Divisionn");
c = div(a, b);
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 35
write(c);
getch();
}
struct complex read(void)
{
struct complex t;
printf("Enter the real partn");
scanf("%f", &t.real);
printf("Enter the imaginary partn");
scanf("%f", &t.imag);
return t;
}
void write(struct complex a)
{
printf("Complex number isn");
printf(" %.1f + i %.1f", a.real, a.imag);
printf("n");
}
struct complex add(struct complex p, struct complex q)
{
struct complex t;
t.real = (p.real + q.real);
t.imag = (p.imag + q.imag);
return t;
}
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 36
struct complex sub(struct complex p, struct complex q)
{
struct complex t;
t.real = (p.real - q.real);
t.imag = (p.imag - q.imag);
return t;
}
struct complex mul(struct complex p, struct complex q)
{
struct complex t;
t.real=(p.real * q.real) - (p.imag * q.imag);
t.imag=(p.real * q.imag) + (p.imag * q.real);
return t;
}
struct complex div(struct complex p, struct complex q)
{
struct complex t;
t.real = ((p.imag * q.real) - (p.real * q.imag)) / ((q.real * q.real) + (q.imag * q.imag));
t.imag = ((p.real * q.real) + (p.imag * q.imag)) / ((q.real * q.real) + (q.imag * q.imag));
return(t);
}
Output:
Enter the real part
2
Enter the imaginary part
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 37
4
Complex number is
2.0 + i4.0
Enter the real part
4
Enter the imaginary part
2
Complex number is
4.0 + i2.0
Addition
Complex number is
6.0 + i6.0
Subtraction
Complex number is
-2.0 + i2.0
Multiplication
Complex number is
0.0 + i20.0
Division
Complex number is
0.6 + i0.8
b) Write a C Program to find whether the given string is a palindrome or not.
Program code:
#include <stdio.h>
#include <string.h>
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 38
// A function to check if a string str is palindrome
voidisPalindrome(char str[])
{
// Start from leftmost and rightmost corners of str
int l = 0;
int h = strlen(str) - 1;
// Keep comparing characters while they are same
while (h > l)
{
if (str[l++] != str[h--])
{
printf("%s is Not Palindrome", str);
return;
}
}
printf("%s is palindrome", str);
}
// Driver program to test above function
int main()
{
isPalindrome("abba");
isPalindrome("abbccbba");
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 39
isPalindrome("geeks");
return 0;
}
Output:
abba is palindrome
abbccbba is palindrome
geeks is Not Palindrome
week 11
1)
a) To insert a sub-string in to a given main string from a given position.
Program code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20], str2[20];
int l1, l2, n, i;
clrscr();
puts("Enter the string 1n");
gets(str1);
l1 = strlen(str1);
puts("Enter the string 2n");
gets(str2);
l2 = strlen(str2);
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 40
printf("Enter the position where the string is to be insertedn");
scanf("%d", &n);
for(i = n; i< l1; i++)
{
str1[i + l2] = str1[i];
}
for(i = 0; i< l2; i++)
{
str1[n + i] = str2[i];
}
str2[l2 + 1] = '0';
printf("After inserting the string is %s", str1);
getch();
}
Output:
Enter the string 1
sachin
Enter the string 2
tendulkar
Enter the position where the string is to be inserted
4
After inserting the string is sachtendulkarin
b)To delete n Characters from a given position in a given string.
Program code:
#include<stdio.h>
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 41
#include<conio.h>
#include<string.h>
void main()
{
charstr[20];
inti, n, l, pos;
clrscr();
puts("Enter the stringn");
gets(str);
printf("Enter the position where the characters are to be deletedn");
scanf("%d", &pos);
printf("Enter the number of characters to be deletedn");
scanf("%d", &n);
l = strlen(str);
for(i = pos + n; i< l; i++)
{
str[i - n] = str[i];
}
str[i - n] = '0';
printf("The string is %s", str);
getch();
}
Output:
Enter the string
sachin
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 42
Enter the position where characters are to be deleted
2
Enter the number of characters to be deleted
2
The string is sain
2)
write-a-c-program-to-count-the-lines-words-and-characters-in-a-given-text
Program code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
charstr[100];
inti = 0, l = 0, f = 1;
clrscr();
puts("Enter any stringn");
gets(str);
for(i = 0; str[i] !='0'; i++)
{
l = l + 1;
}
printf("The number of characters in the string are %dn", l);
for(i = 0; i<= l-1; i++)
{
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 43
if(str[i] == ' ')
{
f = f + 1;
}
}
printf("The number of words in the string are %d", f);
getch();
}
Output:
Enter any string
abcdefghijklmnopqrstuvwxyz
The number of characters in the string are 34
The number of words in the string are 9
Week 12
a) Write a C program to display the contents of a file.
Program code:
#include<stdio.h>
#include<conio.h>
FILE *fp1,*fp2;
char c;
void main()
{
clrscr();
printf("enter the textn");
fp1 = fopen("abc.txt", "w");
while((c = getchar()) != EOF)
putc(c, fp1);
fclose(fp1);
fp1 = fopen("abc.txt","r");
fp2=fopen("xyz.txt","w");
while(!feof(fp1))
{
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 44
c = getc(fp1);
putc(c,fp2);
}
fclose(fp1);
fclose(fp2);
printf("the copied data is n");
fp2 = fopen("xyz.txt", "r");
while(!feof(fp2))
{
c = getc(fp2);
printf("%c", c);
}
getch();
}
Output:
enter the text
engineering students are very good.
^Z
the copied data is
engineering students are very good.
b) Write a C program to merge two files into a third file
Program code:
#include<stdio.h>
void concatenate(FILE *fp1, FILE *fp2, char *argv[], intargc);
int main(intargc, char *argv[]){
FILE *fp1, *fp2;
concatenate(fp1, fp2, argv, argc);
return 0;
}
void concatenate(FILE *fp1, FILE *fp2, char **argv, intargc){
inti, ch;
fp2 = fopen("files", "a");
for(i = 1; i<argc - 1; i++){
fp1 = fopen(argv[i], "r");
while((ch = getc(fp1)) != EOF)
putc(ch, fp2);
}
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 45
}
Output:
File1:
studentboxoffice.in.
File2:
This is Computer Programming Lab.
File 3:
studentboxoffice.in. This is Computer Programming Lab
week 13
a)
Write a C program using command line arguments to search for word in file and replace it with the
specific word.
Program code:
// C program to search and replace
// all occurrences of a word with
// other word.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Function to replace a string with another
// string
char *replaceWord(const char *s, const char *oldW,
const char *newW)
{
char *result;
inti, cnt = 0;
intnewWlen = strlen(newW);
intoldWlen = strlen(oldW);
// Counting the number of times old word
// occur in the string
for (i = 0; s[i] != '0'; i++)
{
if (strstr(&s[i], oldW) == &s[i])
{
cnt++;
// Jumping to index after the old word.
i += oldWlen - 1;
}
}
// Making new string of enough length
result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1);
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 46
i = 0;
while (*s)
{
// compare the substring with the result
if (strstr(s, oldW) == s)
{
strcpy(&result[i], newW);
i += newWlen;
s += oldWlen;
}
else
result[i++] = *s++;
}
result[i] = '0';
return result;
}
// Driver Program
int main()
{
charstr[] = "xxforxx";
char c[] = "xx";
char d[] = "Geeks";
char *result = NULL;
// oldW string
printf("Old string: %sn", str);
result = replaceWord(str, c, d);
printf("New String: %sn", result);
free(result);
return 0;
}
Output:
Old string: xxforxx
New String: GeeksforGeeks
b)
1)To write macro definition to test whether a character is lowercase or not.
Program code:
#include <stdio.h>
//#define IS_UPPER_CASE(n) ((n) >= ‘A’ && (n) <= ‘Z’)
#define IS_LOWER_CASE(n) ((n) >= ‘a’ && (n) <= ‘z’)
//#define IS_ALPHABETIC(n) (IS_UPPER_CASE(n) || IS_LOWER_CASE(n))
void main()
{
char CH=’a’;
clrscr();
if(IS_LOWER_CASE(CH))
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 47
printf(“nYES, CHARACTER IS A LOWER CASE CHARACTER”);
else
printf(“nNO, CHARACTER IS NOT A LOWER CASE CHARACTER”);
getch();
}
Output:
YES, CHARACTER IS A LOWER CASE CHARACTER
2)To check whether a character is alphabet or not.
Program code:
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
if( (c>='a' && c<='z') || (c>='A' && c<='Z'))
printf("%c is an alphabet.",c);
else
printf("%c is not an alphabet.",c);
return 0;
}
Output:
Enter a character: *
* is not an alphabet
3) c program to find the largest of two numbers
Program code:
/* C Program to Find Largest of Two numbers */
#include <stdio.h>
int main() {
int a, b;
printf("Please Enter Two different valuesn");
scanf("%d %d", &a, &b);
if(a > b)
{
printf("%d is Largestn", a);
}
else if (b > a)
{
printf("%d is Largestn", b);
}
else
{
printf("Both are Equaln");
}
return 0;
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 48
}
Output:
Please Enter Two different values
65 5
65 is Largest
c) Write a C program to concatenate two strings using command line arguments.
Program code:
// C program to concatenate the two Strings
// using command line arguments
#include <stdio.h>
#include <stdlib.h> /* atoi */
#include <string.h>
// Function to concatenate the Strings
char* concat(char dest[], char src[])
{
// Appends the entire string
// of src to dest
strcat(dest, src);
// Return the concatenated String
returndest;
}
// Driver code
int main(intargc, char* argv[])
{
// Check if the length of args array is 1
if (argc == 1)
printf("No command line arguments found.n");
else {
// Get the command line arguments
// and concatenate them
printf("%sn", concat(argv[1], argv[2]));
}
return 0;
}
Output:
./main
No command line arguments found
./main hello world
helloworld
./main Geeks ForGeeks
GeeksForGeeks
C Practical Programs
Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 49

Contenu connexe

Tendances (20)

c-programming-using-pointers
c-programming-using-pointersc-programming-using-pointers
c-programming-using-pointers
 
Data structures lab manual
Data structures lab manualData structures lab manual
Data structures lab manual
 
VTU Data Structures Lab Manual
VTU Data Structures Lab ManualVTU Data Structures Lab Manual
VTU Data Structures Lab Manual
 
C lab excellent
C lab excellentC lab excellent
C lab excellent
 
Practical File of C Language
Practical File of C LanguagePractical File of C Language
Practical File of C Language
 
Function basics
Function basicsFunction basics
Function basics
 
C++ file
C++ fileC++ file
C++ file
 
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORYCS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
 
C PROGRAMS
C PROGRAMSC PROGRAMS
C PROGRAMS
 
C programms
C programmsC programms
C programms
 
Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
 
Implementing string
Implementing stringImplementing string
Implementing string
 
Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphism
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
C++ Programming - 1st Study
C++ Programming - 1st StudyC++ Programming - 1st Study
C++ Programming - 1st Study
 
Static and const members
Static and const membersStatic and const members
Static and const members
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
C tech questions
C tech questionsC tech questions
C tech questions
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
 

Similaire à C programs

Similaire à C programs (20)

C lab
C labC lab
C lab
 
C Programming
C ProgrammingC Programming
C Programming
 
Core programming in c
Core programming in cCore programming in c
Core programming in c
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
Progr3
Progr3Progr3
Progr3
 
C lab programs
C lab programsC lab programs
C lab programs
 
C lab programs
C lab programsC lab programs
C lab programs
 
B.Com 1year Lab programs
B.Com 1year Lab programsB.Com 1year Lab programs
B.Com 1year Lab programs
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solution
 
C important questions
C important questionsC important questions
C important questions
 
C Programming Example
C Programming Example C Programming Example
C Programming Example
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
 
Program flowchart
Program flowchartProgram flowchart
Program flowchart
 
C file
C fileC file
C file
 
C Programming Exam problems & Solution by sazzad hossain
C Programming Exam problems & Solution by sazzad hossainC Programming Exam problems & Solution by sazzad hossain
C Programming Exam problems & Solution by sazzad hossain
 
C programming Lab 2
C programming Lab 2C programming Lab 2
C programming Lab 2
 
C Programming Example
C Programming ExampleC Programming Example
C Programming Example
 
C- Programming Assignment 4 solution
C- Programming Assignment 4 solutionC- Programming Assignment 4 solution
C- Programming Assignment 4 solution
 
week-3x
week-3xweek-3x
week-3x
 

Plus de Vikram Nandini

IoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold BarIoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold BarVikram Nandini
 
Linux File Trees and Commands
Linux File Trees and CommandsLinux File Trees and Commands
Linux File Trees and CommandsVikram Nandini
 
Introduction to Linux & Basic Commands
Introduction to Linux & Basic CommandsIntroduction to Linux & Basic Commands
Introduction to Linux & Basic CommandsVikram Nandini
 
Manufacturing - II Part
Manufacturing - II PartManufacturing - II Part
Manufacturing - II PartVikram Nandini
 
Prototyping Online Components
Prototyping Online ComponentsPrototyping Online Components
Prototyping Online ComponentsVikram Nandini
 
Artificial Neural Networks
Artificial Neural NetworksArtificial Neural Networks
Artificial Neural NetworksVikram Nandini
 
Design Principles for Connected Devices
Design Principles for Connected DevicesDesign Principles for Connected Devices
Design Principles for Connected DevicesVikram Nandini
 
Communication in the IoT
Communication in the IoTCommunication in the IoT
Communication in the IoTVikram Nandini
 
Introduction to Cyber Security
Introduction to Cyber SecurityIntroduction to Cyber Security
Introduction to Cyber SecurityVikram Nandini
 
cloud computing UNIT-2.pdf
cloud computing UNIT-2.pdfcloud computing UNIT-2.pdf
cloud computing UNIT-2.pdfVikram Nandini
 
Introduction to Web Technologies
Introduction to Web TechnologiesIntroduction to Web Technologies
Introduction to Web TechnologiesVikram Nandini
 
Cascading Style Sheets
Cascading Style SheetsCascading Style Sheets
Cascading Style SheetsVikram Nandini
 

Plus de Vikram Nandini (20)

IoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold BarIoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold Bar
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Linux File Trees and Commands
Linux File Trees and CommandsLinux File Trees and Commands
Linux File Trees and Commands
 
Introduction to Linux & Basic Commands
Introduction to Linux & Basic CommandsIntroduction to Linux & Basic Commands
Introduction to Linux & Basic Commands
 
INTRODUCTION to OOAD
INTRODUCTION to OOADINTRODUCTION to OOAD
INTRODUCTION to OOAD
 
Ethics
EthicsEthics
Ethics
 
Manufacturing - II Part
Manufacturing - II PartManufacturing - II Part
Manufacturing - II Part
 
Manufacturing
ManufacturingManufacturing
Manufacturing
 
Business Models
Business ModelsBusiness Models
Business Models
 
Prototyping Online Components
Prototyping Online ComponentsPrototyping Online Components
Prototyping Online Components
 
Artificial Neural Networks
Artificial Neural NetworksArtificial Neural Networks
Artificial Neural Networks
 
IoT-Prototyping
IoT-PrototypingIoT-Prototyping
IoT-Prototyping
 
Design Principles for Connected Devices
Design Principles for Connected DevicesDesign Principles for Connected Devices
Design Principles for Connected Devices
 
Introduction to IoT
Introduction to IoTIntroduction to IoT
Introduction to IoT
 
Embedded decices
Embedded decicesEmbedded decices
Embedded decices
 
Communication in the IoT
Communication in the IoTCommunication in the IoT
Communication in the IoT
 
Introduction to Cyber Security
Introduction to Cyber SecurityIntroduction to Cyber Security
Introduction to Cyber Security
 
cloud computing UNIT-2.pdf
cloud computing UNIT-2.pdfcloud computing UNIT-2.pdf
cloud computing UNIT-2.pdf
 
Introduction to Web Technologies
Introduction to Web TechnologiesIntroduction to Web Technologies
Introduction to Web Technologies
 
Cascading Style Sheets
Cascading Style SheetsCascading Style Sheets
Cascading Style Sheets
 

Dernier

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 

Dernier (20)

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 

C programs

  • 1. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 1 C programs Week 1: a) Write a C program to exchange the values between two variables with and without using temporary variable. Program code: /* using temporary variable */ #include <stdio.h> int main() { doublefirstNumber, secondNumber, temporaryVariable; printf("Enter first number: "); scanf("%lf", &firstNumber); printf("Enter second number: "); scanf("%lf",&secondNumber); // Value of firstNumber is assigned to temporaryVariable temporaryVariable = firstNumber; // Value of secondNumber is assigned to firstNumber firstNumber = secondNumber; // Value of temporaryVariable (which contains the initial value of firstNumber) is assigned to secondNumber secondNumber = temporaryVariable; printf("nAfter swapping, firstNumber = %.2lfn", firstNumber); printf("After swapping, secondNumber = %.2lf", secondNumber); return 0; } Output: Enter first number: 1.20 Enter second number: 2.45 After swapping, firstNumber = 2.45 After swapping, secondNumber = 1.20 /*without using temporary variable */ #include <stdio.h> int main() { doublefirstNumber, secondNumber; printf("Enter first number: "); scanf("%lf", &firstNumber); printf("Enter second number: ");
  • 2. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 2 scanf("%lf",&secondNumber); // Swapping process firstNumber = firstNumber - secondNumber; secondNumber = firstNumber + secondNumber; firstNumber = secondNumber - firstNumber; printf("nAfter swapping, firstNumber = %.2lfn", firstNumber); printf("After swapping, secondNumber = %.2lf", secondNumber); return 0; } Output: Enter first number: 10.25 Enter second number: -12.5 After swapping, firstNumber = -12.50 After swapping, secondNumber = 10.25 b) Write a C program to find the sum of individual digits of a positive integer. Program Code: #include<stdio.h> int main() { intn,sum=0,m; printf("Enter a number:"); scanf("%d",&n); while(n>0) { m=n%10; sum=sum+m; n=n/10; } printf("Sum is=%d",sum); return 0; } Output: Enter a number:654 Sum is=15 c) Write a C program to generate all the factors of 4 and 7 between 1 and n and count their value, where n is a value supplied by the user. #include <stdio.h>
  • 3. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 3 int main() { int number, i; printf("Enter a positive integer: "); scanf("%d",&number); printf("Factors of 4 are: ", number); for(i=1; i<= number; ++i) { if (4%i == 0) { printf("%d ",i); } } printf("Factors of 7 are: ", number); for(i=1; i<= number; ++i) { if (7%i == 0) { printf("%d ",i); } } return 0; } Output: Enter a positive integer: 10 The Factors of 4 are: 1 2 4 The factors of 7 are: 1 7 Week 2: a) Write a C program to compute the factorial of a given number. Program Code: #include <stdio.h> int main() { int n, i; unsigned long long factorial = 1; printf("Enter an integer: "); scanf("%d",&n); // show error if the user enters a negative integer if (n < 0)
  • 4. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 4 printf("Error! Factorial of a negative number doesn't exist."); else { for(i=1; i<=n; ++i) { factorial *= i; // factorial = factorial*i; } printf("Factorial of %d = %llu", n, factorial); } return 0; } Output: Enter an integer: 10 Factorial of 10 = 3628800 b) Write a C program to compute the Sine function. Program Code: /* * C program to find the value of sin(x) using the series * up to the given accuracy (without using user defined function) * also print sin(x) using library function. */ #include <stdio.h> #include <math.h> #include <stdlib.h> void main() { int n, x1; float accuracy, term, denominator, x, sinx, sinval; printf("Enter the value of x (in degrees) n"); scanf("%f", &x); x1 = x; /* Converting degrees to radians */ x = x * (3.142 / 180.0); sinval = sin(x); printf("Enter the accuracy for the result n"); scanf("%f", &accuracy); term = x;
  • 5. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 5 sinx = term; n = 1; do { denominator = 2 * n * (2 * n + 1); term = -term * x * x / denominator; sinx = sinx + term; n = n + 1; } while (accuracy <= fabs(sinval - sinx)); printf("Sum of the sine series = %f n", sinx); printf("Using Library function sin(%d) = %fn", x1, sin(x)); } Output: Enter the value of x (in degrees) 60 Enter the accuracy for the result 0.86602540378443864676372317075294 Sum of the sine series = 0.855862 Using Library function sin(60) = 0.866093 Week 3: a) Write a C program to generate the first n terms of the Fibonacci sequence. Program code: #include <stdio.h> int main() { int t1 = 0, t2 = 1, nextTerm = 0, n; printf("Enter a positive number: "); scanf("%d", &n); // displays the first two terms which is always 0 and 1 printf("Fibonacci Series: %d, %d, ", t1, t2); nextTerm = t1 + t2; while(nextTerm<= n) { printf("%d, ",nextTerm); t1 = t2; t2 = nextTerm; nextTerm = t1 + t2; } return 0;
  • 6. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 6 } Output: Enter a positive integer: 100 Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, b) Write a C program to reverse the digits of a given integer Program code: #include <stdio.h> int main() { int n, reversedNumber = 0, remainder; printf("Enter an integer: "); scanf("%d", &n); while(n != 0) { remainder = n%10; reversedNumber = reversedNumber*10 + remainder; n /= 10; } printf("Reversed Number = %d", reversedNumber); return 0; } Output: Enter an integer: 2345 Reversed Number = 5432 Week 4 a) Write a C program to covert the given decimal number into its equivalent binary, octal and hexadecimal number. Program Code: #include<stdio.h> #include<stdlib.h> void conversion(intnum, int base) { int remainder = num % base; if(num == 0) { return;
  • 7. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 7 } conversion(num / base, base); if(remainder < 10) { printf("%d", remainder); } else { printf("%c", remainder - 10 + 'A' ); } } int main() { intnum, choice; printf("nEnter a Positive Decimal Number:t"); scanf("%d", &num); while(1) { printf("n1. Decimal To Binary Conversion"); printf("n2. Decimal To Octal Conversion"); printf("n3. Decimal To Hexadecimal Conversion"); printf("n4. Quit"); printf("nEnter Your Option:t"); scanf("%d", &choice); switch(choice) { case 1: printf("nBinary Value:t"); conversion(num, 2); break; case 2: printf("nOctal Value:t"); conversion(num, 8); break; case 3: printf("nHexadecimal Value:t"); conversion(num, 16); break; case 4: exit(0); default: printf("Enter a correct inputn"); } } printf("n");
  • 8. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 8 return 0; } Output: Enter a positive Decimal Number: 1.Decimal To Binary Conversion 2.Decimal To Octal Conversion 3.Decimal To Hexadecimal Conversion 4.Quit Enter your Option: 1 Binary Value: 1010 1.Decimal To Binary Conversion 2.Decimal To Octal Conversion 3.Decimal To Hexadecimal Conversion 4.Quit Enter Your option: 2 Octal Value: 12 1.Decimal To Binary Conversion 2.Decimal To Octal Conversion 3.Decimal To Hexadecimal Conversion 4.Quit Enter your option: 3 Hexadecimal Value : A 1.Decimal To Binary Conversion 2.Decimal To Octal Conversion 3.Decimal To Hexadecimal Conversion 4.Quit Enter your option: 4 b) Write a C program to calculate the following: Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!. Program Code: // C program to get the sum of the series #include <math.h> #include <stdio.h> // Function to get the series double Series(double x, int n) {
  • 9. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 9 double sum = 1, term = 1, fct, j, y = 2, m; // Sum of n-1 terms starting from 2nd term inti; for (i = 1; i< n; i++) { fct = 1; for (j = 1; j <= y; j++) { fct = fct * j; } term = term * (-1); m = term * pow(x, y) / fct; sum = sum + m; y += 2; } return sum; } // Driver Code int main() { double x = 9; int n = 10; printf("%.4f", Series(x, n)); return 0; } Output: -5.1463 c)Write a C program, which takes two integer operands and one operator from the user, performs the operation and then prints the result. Program Code: #include<stdio.h> int main() { inta,b,res; char c; printf ("Enter any one operator +, -, *, / n"); scanf("%c", &c);
  • 10. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 10 printf ("n Enter two numbers n"); scanf ("n %d n %d",&a, &b); switch(c) { case '+': res=a+b; printf("n The sum is %d",res); break; case '-': res=a-b; printf("n The difference is %d",res); break; case '*': res=a*b; printf("n The product is %d",res); break; case '/': res=a/b; printf("n The quotient is %d",res); break; default: printf ("n Invalid entry"); } return 0; } Output: Case 1: Enter any one operator +, -, *, / + Enter two numbers 5 3 The sum is 8 Case 2: Enter any one operator +, -, *, /
  • 11. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 11 / Enter two numbers 100 20 The quotient is 5 Week 5 a) Write C program to display the result of a student by considering the standard grades. Program code: #include<stdio.h> void main() { int marks; printf("Enter your marks "); scanf("%d",&marks); if(marks<0 || marks>100) { printf("Wrong Entry"); } else if(marks<50) { printf("Grade F"); } else if(marks>=50 && marks<60) { printf("Grade D"); } else if(marks>=60 && marks<70) { printf("Grade C"); } else if(marks>=70 && marks<80) { printf("Grade B"); } else if(marks>=80 && marks<90)
  • 12. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 12 { printf("Grade A"); } else { printf("Grade A+"); } } Output: Enter your marks 67 Grade C press any key to continue. b)Write a C Program to find both largest and smallest in the given list of integers. Program code: #include<stdio.h> int main() { inti, n, lar,sm, elem; printf ("Enter total number of elements n"); scanf ("%d", &elem); printf ("Enter first number n"); scanf ("%d", &n); lar = n; sm=n; for (i=1; i<= elem -1 ; i++) { printf ("n Enter another number n"); scanf ("%d",&n); if (n>lar) lar=n; if (n<sm) sm=n; } printf ("n The largest number is %d", lar); printf ("n The smallest number is %d", sm); return 0; } Output: Enter total number of elements 10 Enter first number 3 Enter another number 8 Enter another number 12 Enter another number
  • 13. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 13 42 Enter another number 89 Enter another number 45 Enter another number 236 Enter another number 890 Enter another number 411 Enter another number 328 The largest number is 890 The smallest number is 3 Week 6 a) Write a C program to generate Pascal’s triangle. Program Code: #include <stdio.h> int main() { int rows, cal = 1, space, i, j; printf("Enter number of rows: ");//enter number of rows for generating the pascal triangle scanf("%d",&rows); for(i=0; i<rows; i++) // outer loop for displaying rows { for(space=1; space <= rows-i; space++) // space for every row starting printf(" "); for(j=0; j <= i; j++) // inner loop for displaying the pascal triangle of numbers { if (j==0 || i==0) // either outer loop value or inner-loop value is "0 " it prints 1 cal = 1; else cal = cal*(i-j+1)/j; //calculate the coefficient printf("%4d", cal);
  • 14. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 14 } printf("n"); } return 0; } Output: Enter number of rows: 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 b) Write a C program to construct a pyramid of numbers Program Code: #include<stdio.h> #include<stdlib.h> int main(){ inti,j,k,l,n; system("cls"); printf("enter the range="); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=n-i;j++) { printf(" "); } for(k=1;k<=i;k++) { printf("%d",k); } for(l=i-1;l>=1;l--) { printf("%d",l);
  • 15. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 15 } printf("n"); } return 0; } Output: enter the range= 4 1 121 12321 1234321 Week 7 a)Write a c program 1) To find square root of a given integer. Program Code: /** * C program to find square root of a number */ #include <stdio.h> #include <math.h> int main() { doublenum, root; /* Input a number from user */ printf("Enter any number to find square root: "); scanf("%lf", &num); /* Calculate square root of num */ root = sqrt(num); /* Print the resultant value */ printf("Square root of %.2lf = %.2lf", num, root); return 0; } Output:
  • 16. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 16 Enter any number to find square root: 144 Square root of 144.00=12.00 2) To find the smallest Divisor of a number Program Code: // C++ program to count the number of // subarrays that having 1 #include <bits/stdc++.h> using namespace std; // Function to find the smallest divisor intsmallestDivisor(int n) { // if divisible by 2 if (n % 2 == 0) return 2; // iterate from 3 to sqrt(n) for (inti = 3; i * i<= n; i += 2) { if (n % i == 0) returni; } return n; } // Driver Code int main() { int n = 31; cout<<smallestDivisor(n); return 0; } Output: 31 3) To raise the number to large power. Program Code: #include <stdio.h>
  • 17. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 17 int main() { int base, exponent; longlong 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: Enter a base number: 3 Enter an exponent: 4 Answer = 81 4)To generate the prime numbers from 1 to n Program Code: /** * C program to print all prime numbers between 1 to n */
  • 18. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 18 #include <stdio.h> int main() { inti, j, end, isPrime; // isPrime is used as flag variable /* Input upper limit to print prime */ printf("Find prime numbers between 1 to : "); scanf("%d", &end); printf("All prime numbers between 1 to %d are:n", end); /* Find all Prime numbers between 1 to end */ for(i=2; i<=end; i++) { /* Assume that the current number is Prime */ isPrime = 1; /* Check if the current number i is prime or not */ for(j=2; j<=i/2; j++) { /* * If i is divisible by any number other than 1 and self * then it is not prime number
  • 19. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 19 */ if(i%j==0) { isPrime = 0; break; } } /* If the number is prime then print */ if(isPrime==1) { printf("%d, ", i); } } return 0; } Output: Find Prime numbers between 1 to 10 All prime numbers between 1 to 10 are: 2 3 5 7 Week 8 1)C program to computer prime factor of an integer Program code: // Program to print all prime factors
  • 20. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 20 # include <stdio.h> # include <math.h> // A function to print all prime factors of a given number n voidprimeFactors(int n) { // Print the number of 2s that divide n while (n%2 == 0) { printf("%d ", 2); n = n/2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (inti = 3; i<= sqrt(n); i = i+2) { // While i divides n, print i and divide n while (n%i == 0) { printf("%d ", i); n = n/i; } }
  • 21. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 21 // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) printf ("%d ", n); } /* Driver program to test above function */ int main() { int n = 315; primeFactors(n); return 0; } Output: 3 3 5 7 2) C program to generate pseudorandom number in c Program code: #include <stdio.h> #include <stdlib.h> int main() { int c, n; printf("Ten random numbers in [1,100]n");
  • 22. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 22 for (c = 1; c <= 5; c++) { n = rand() % 100 + 1; printf("%dn", n); } return 0; } Output: 3569 254 57 5 9675 3) C Program to find GCD of two numbers Program code: #include <stdio.h> int main() { int n1, n2, i, gcd; printf("Enter two integers: "); scanf("%d %d", &n1, &n2); for(i=1; i<= n1 &&i<= n2; ++i) {
  • 23. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 23 // Checks if i is factor of both integers if(n1%i==0 && n2%i==0) gcd = i; } printf("G.C.D of %d and %d is %d", n1, n2, gcd); return 0; } Output: Enter two positive integers: 81 153 GCD = 9 4) C program to compute nth Fibonacci number Program code: /* * C Program to find the nth number in Fibonacci series using recursion */ #include <stdio.h> intfibo(int); int main() { intnum; int result;
  • 24. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 24 printf("Enter the nth number in fibonacci series: "); scanf("%d", &num); if (num< 0) { printf("Fibonacci of negative number is not possible.n"); } else { result = fibo(num); printf("The %d number in fibonacci series is %dn", num, result); } return 0; } intfibo(intnum) { if (num == 0) { return 0; } else if (num == 1) { return 1; } else {
  • 25. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 25 return(fibo(num - 1) + fibo(num - 2)); } } Output: Enter the nth number in fibonacci series: 8 The 8 number in fibonacci series is 21 Week 9 1) To find the both the largest and smallest number in the a list of integers Program code: #include<stdio.h> int main() { inti, n, lar,sm, elem; printf ("Enter total number of elements n"); scanf ("%d", &elem); printf ("Enter first number n"); scanf ("%d", &n); lar = n; sm=n; for (i=1; i<= elem -1 ; i++) { printf ("n Enter another number n"); scanf ("%d",&n); if (n>lar)
  • 26. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 26 lar=n; if (n<sm) sm=n; } printf ("n The largest number is %d", lar); printf ("n The smallest number is %d", sm); return 0; } Output: Enter total number of elements 10 Enter first number 3 Enter another number 8 Enter another number 12 Enter another number 42 Enter another number 89 Enter another number 45 Enter another number 236
  • 27. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 27 Enter another number 890 Enter another number 411 Enter another number 328 The largest number is 890 The smallest number is 3 2) a.)c program to find the addition of two matrices Program code: #include <stdio.h> int main(){ int r, c, a[100][100], b[100][100], sum[100][100], i, j; printf("Enter number of rows (between 1 and 100): "); scanf("%d", &r); printf("Enter number of columns (between 1 and 100): "); scanf("%d", &c); printf("nEnter elements of 1st matrix:n"); for(i=0; i<r; ++i) for(j=0; j<c; ++j) { printf("Enter element a%d%d: ",i+1,j+1); scanf("%d",&a[i][j]);
  • 28. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 28 } printf("Enter elements of 2nd matrix:n"); for(i=0; i<r; ++i) for(j=0; j<c; ++j) { printf("Enter element a%d%d: ",i+1, j+1); scanf("%d", &b[i][j]); } // Adding Two matrices for(i=0;i<r;++i) for(j=0;j<c;++j) { sum[i][j]=a[i][j]+b[i][j]; } // Displaying the result printf("nSum of two matrices: n"); for(i=0;i<r;++i) for(j=0;j<c;++j) { printf("%d ",sum[i][j]); if(j==c-1) { printf("nn"); } }
  • 29. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 29 return 0; } Output: Enter number of rows (between 1 and 100): 2 Enter number of columns (between 1 and 100): 3 Enter elements of 1st matrix: Enter element a11: 2 Enter element a12: 3 Enter element a13: 4 Enter element a21: 5 Enter element a22: 2 Enter element a23: 3 Enter elements of 2nd matrix: Enter element a11: -4 Enter element a12: 5 Enter element a13: 3 Enter element a21: 5 Enter element a22: 6 Enter element a23: 3 Sum of two matrices: -2 8 7 10 8 6 b)c program for multiplication of two matrices
  • 30. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 30 Program code: #include <stdio.h> int main() { int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k; printf("Enter rows and column for first matrix: "); scanf("%d %d", &r1, &c1); printf("Enter rows and column for second matrix: "); scanf("%d %d",&r2, &c2); // Column of first matrix should be equal to column of second matrix and while (c1 != r2) { printf("Error! column of first matrix not equal to row of second.nn"); printf("Enter rows and column for first matrix: "); scanf("%d %d", &r1, &c1); printf("Enter rows and column for second matrix: "); scanf("%d %d",&r2, &c2); } // Storing elements of first matrix. printf("nEnter elements of matrix 1:n"); for(i=0; i<r1; ++i) for(j=0; j<c1; ++j) { printf("Enter elements a%d%d: ",i+1, j+1); scanf("%d", &a[i][j]);
  • 31. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 31 } // Storing elements of second matrix. printf("nEnter elements of matrix 2:n"); for(i=0; i<r2; ++i) for(j=0; j<c2; ++j) { printf("Enter elements b%d%d: ",i+1, j+1); scanf("%d",&b[i][j]); } // Initializing all elements of result matrix to 0 for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { result[i][j] = 0; } // Multiplying matrices a and b and // storing result in result matrix for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) for(k=0; k<c1; ++k) { result[i][j]+=a[i][k]*b[k][j]; } // Displaying the result printf("nOutput Matrix:n");
  • 32. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 32 for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { printf("%d ", result[i][j]); if(j == c2-1) printf("nn"); } return 0; } Output: Enter rows and column for first matrix: 3 2 Enter rows and column for second matrix: 3 2 Error! column of first matrix not equal to row of second. Enter rows and column for first matrix: 2 3 Enter rows and column for second matrix: 3 2 Enter elements of matrix 1: Enter elements a11: 3 Enter elements a12: -2 Enter elements a13: 5 Enter elements a21: 3
  • 33. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 33 Enter elements a22: 0 Enter elements a23: 4 Enter elements of matrix 2: Enter elements b11: 2 Enter elements b12: 3 Enter elements b21: -9 Enter elements b22: 0 Enter elements b31: 0 Enter elements b32: 4 Output Matrix: 24 29 6 25 Week 10 a)Write a C program that uses functions to perform the following operations: i) Reading a complex number ii) Writing a complex number iii) Addition of two complex numbers iv) Multiplication of two complex numbers Program code: #include <stdio.h> #include <conio.h> struct complex { float real, imag; }a, b, c; struct complex read(void);
  • 34. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 34 void write(struct complex); struct complex add(struct complex, struct complex); struct complex sub(struct complex, struct complex); struct complex mul(struct complex, struct complex); struct complex div(struct complex, struct complex); void main () { clrscr(); printf("Enter the 1st complex numbern "); a = read(); write(a); printf("Enter the 2nd complex numbern"); b = read(); write(b); printf("Additionn "); c = add(a, b); write(c); printf("Substractionn "); c = sub(a, b); write(c); printf("Multiplicationn"); c = mul(a, b); write(c); printf("Divisionn"); c = div(a, b);
  • 35. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 35 write(c); getch(); } struct complex read(void) { struct complex t; printf("Enter the real partn"); scanf("%f", &t.real); printf("Enter the imaginary partn"); scanf("%f", &t.imag); return t; } void write(struct complex a) { printf("Complex number isn"); printf(" %.1f + i %.1f", a.real, a.imag); printf("n"); } struct complex add(struct complex p, struct complex q) { struct complex t; t.real = (p.real + q.real); t.imag = (p.imag + q.imag); return t; }
  • 36. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 36 struct complex sub(struct complex p, struct complex q) { struct complex t; t.real = (p.real - q.real); t.imag = (p.imag - q.imag); return t; } struct complex mul(struct complex p, struct complex q) { struct complex t; t.real=(p.real * q.real) - (p.imag * q.imag); t.imag=(p.real * q.imag) + (p.imag * q.real); return t; } struct complex div(struct complex p, struct complex q) { struct complex t; t.real = ((p.imag * q.real) - (p.real * q.imag)) / ((q.real * q.real) + (q.imag * q.imag)); t.imag = ((p.real * q.real) + (p.imag * q.imag)) / ((q.real * q.real) + (q.imag * q.imag)); return(t); } Output: Enter the real part 2 Enter the imaginary part
  • 37. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 37 4 Complex number is 2.0 + i4.0 Enter the real part 4 Enter the imaginary part 2 Complex number is 4.0 + i2.0 Addition Complex number is 6.0 + i6.0 Subtraction Complex number is -2.0 + i2.0 Multiplication Complex number is 0.0 + i20.0 Division Complex number is 0.6 + i0.8 b) Write a C Program to find whether the given string is a palindrome or not. Program code: #include <stdio.h> #include <string.h>
  • 38. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 38 // A function to check if a string str is palindrome voidisPalindrome(char str[]) { // Start from leftmost and rightmost corners of str int l = 0; int h = strlen(str) - 1; // Keep comparing characters while they are same while (h > l) { if (str[l++] != str[h--]) { printf("%s is Not Palindrome", str); return; } } printf("%s is palindrome", str); } // Driver program to test above function int main() { isPalindrome("abba"); isPalindrome("abbccbba");
  • 39. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 39 isPalindrome("geeks"); return 0; } Output: abba is palindrome abbccbba is palindrome geeks is Not Palindrome week 11 1) a) To insert a sub-string in to a given main string from a given position. Program code: #include<stdio.h> #include<conio.h> #include<string.h> void main() { char str1[20], str2[20]; int l1, l2, n, i; clrscr(); puts("Enter the string 1n"); gets(str1); l1 = strlen(str1); puts("Enter the string 2n"); gets(str2); l2 = strlen(str2);
  • 40. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 40 printf("Enter the position where the string is to be insertedn"); scanf("%d", &n); for(i = n; i< l1; i++) { str1[i + l2] = str1[i]; } for(i = 0; i< l2; i++) { str1[n + i] = str2[i]; } str2[l2 + 1] = '0'; printf("After inserting the string is %s", str1); getch(); } Output: Enter the string 1 sachin Enter the string 2 tendulkar Enter the position where the string is to be inserted 4 After inserting the string is sachtendulkarin b)To delete n Characters from a given position in a given string. Program code: #include<stdio.h>
  • 41. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 41 #include<conio.h> #include<string.h> void main() { charstr[20]; inti, n, l, pos; clrscr(); puts("Enter the stringn"); gets(str); printf("Enter the position where the characters are to be deletedn"); scanf("%d", &pos); printf("Enter the number of characters to be deletedn"); scanf("%d", &n); l = strlen(str); for(i = pos + n; i< l; i++) { str[i - n] = str[i]; } str[i - n] = '0'; printf("The string is %s", str); getch(); } Output: Enter the string sachin
  • 42. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 42 Enter the position where characters are to be deleted 2 Enter the number of characters to be deleted 2 The string is sain 2) write-a-c-program-to-count-the-lines-words-and-characters-in-a-given-text Program code: #include <stdio.h> #include <conio.h> #include <string.h> void main() { charstr[100]; inti = 0, l = 0, f = 1; clrscr(); puts("Enter any stringn"); gets(str); for(i = 0; str[i] !='0'; i++) { l = l + 1; } printf("The number of characters in the string are %dn", l); for(i = 0; i<= l-1; i++) {
  • 43. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 43 if(str[i] == ' ') { f = f + 1; } } printf("The number of words in the string are %d", f); getch(); } Output: Enter any string abcdefghijklmnopqrstuvwxyz The number of characters in the string are 34 The number of words in the string are 9 Week 12 a) Write a C program to display the contents of a file. Program code: #include<stdio.h> #include<conio.h> FILE *fp1,*fp2; char c; void main() { clrscr(); printf("enter the textn"); fp1 = fopen("abc.txt", "w"); while((c = getchar()) != EOF) putc(c, fp1); fclose(fp1); fp1 = fopen("abc.txt","r"); fp2=fopen("xyz.txt","w"); while(!feof(fp1)) {
  • 44. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 44 c = getc(fp1); putc(c,fp2); } fclose(fp1); fclose(fp2); printf("the copied data is n"); fp2 = fopen("xyz.txt", "r"); while(!feof(fp2)) { c = getc(fp2); printf("%c", c); } getch(); } Output: enter the text engineering students are very good. ^Z the copied data is engineering students are very good. b) Write a C program to merge two files into a third file Program code: #include<stdio.h> void concatenate(FILE *fp1, FILE *fp2, char *argv[], intargc); int main(intargc, char *argv[]){ FILE *fp1, *fp2; concatenate(fp1, fp2, argv, argc); return 0; } void concatenate(FILE *fp1, FILE *fp2, char **argv, intargc){ inti, ch; fp2 = fopen("files", "a"); for(i = 1; i<argc - 1; i++){ fp1 = fopen(argv[i], "r"); while((ch = getc(fp1)) != EOF) putc(ch, fp2); }
  • 45. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 45 } Output: File1: studentboxoffice.in. File2: This is Computer Programming Lab. File 3: studentboxoffice.in. This is Computer Programming Lab week 13 a) Write a C program using command line arguments to search for word in file and replace it with the specific word. Program code: // C program to search and replace // all occurrences of a word with // other word. #include <stdio.h> #include <string.h> #include <stdlib.h> // Function to replace a string with another // string char *replaceWord(const char *s, const char *oldW, const char *newW) { char *result; inti, cnt = 0; intnewWlen = strlen(newW); intoldWlen = strlen(oldW); // Counting the number of times old word // occur in the string for (i = 0; s[i] != '0'; i++) { if (strstr(&s[i], oldW) == &s[i]) { cnt++; // Jumping to index after the old word. i += oldWlen - 1; } } // Making new string of enough length result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1);
  • 46. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 46 i = 0; while (*s) { // compare the substring with the result if (strstr(s, oldW) == s) { strcpy(&result[i], newW); i += newWlen; s += oldWlen; } else result[i++] = *s++; } result[i] = '0'; return result; } // Driver Program int main() { charstr[] = "xxforxx"; char c[] = "xx"; char d[] = "Geeks"; char *result = NULL; // oldW string printf("Old string: %sn", str); result = replaceWord(str, c, d); printf("New String: %sn", result); free(result); return 0; } Output: Old string: xxforxx New String: GeeksforGeeks b) 1)To write macro definition to test whether a character is lowercase or not. Program code: #include <stdio.h> //#define IS_UPPER_CASE(n) ((n) >= ‘A’ && (n) <= ‘Z’) #define IS_LOWER_CASE(n) ((n) >= ‘a’ && (n) <= ‘z’) //#define IS_ALPHABETIC(n) (IS_UPPER_CASE(n) || IS_LOWER_CASE(n)) void main() { char CH=’a’; clrscr(); if(IS_LOWER_CASE(CH))
  • 47. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 47 printf(“nYES, CHARACTER IS A LOWER CASE CHARACTER”); else printf(“nNO, CHARACTER IS NOT A LOWER CASE CHARACTER”); getch(); } Output: YES, CHARACTER IS A LOWER CASE CHARACTER 2)To check whether a character is alphabet or not. Program code: #include <stdio.h> int main() { char c; printf("Enter a character: "); scanf("%c",&c); if( (c>='a' && c<='z') || (c>='A' && c<='Z')) printf("%c is an alphabet.",c); else printf("%c is not an alphabet.",c); return 0; } Output: Enter a character: * * is not an alphabet 3) c program to find the largest of two numbers Program code: /* C Program to Find Largest of Two numbers */ #include <stdio.h> int main() { int a, b; printf("Please Enter Two different valuesn"); scanf("%d %d", &a, &b); if(a > b) { printf("%d is Largestn", a); } else if (b > a) { printf("%d is Largestn", b); } else { printf("Both are Equaln"); } return 0;
  • 48. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 48 } Output: Please Enter Two different values 65 5 65 is Largest c) Write a C program to concatenate two strings using command line arguments. Program code: // C program to concatenate the two Strings // using command line arguments #include <stdio.h> #include <stdlib.h> /* atoi */ #include <string.h> // Function to concatenate the Strings char* concat(char dest[], char src[]) { // Appends the entire string // of src to dest strcat(dest, src); // Return the concatenated String returndest; } // Driver code int main(intargc, char* argv[]) { // Check if the length of args array is 1 if (argc == 1) printf("No command line arguments found.n"); else { // Get the command line arguments // and concatenate them printf("%sn", concat(argv[1], argv[2])); } return 0; } Output: ./main No command line arguments found ./main hello world helloworld ./main Geeks ForGeeks GeeksForGeeks
  • 49. C Practical Programs Vikram Neerugatti, Assistant Professor, SVCET, Chittoor Page 49