0% found this document useful (0 votes)
26 views34 pages

C Lab

The document contains a series of programming exercises in C, covering various topics such as arithmetic, logical, bitwise, and control statements. Each exercise includes a brief description and the corresponding C code to implement the functionality, such as calculating roots of quadratic equations, reversing digits, and converting between number systems. The document serves as a practical guide for students to practice and enhance their programming skills.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views34 pages

C Lab

The document contains a series of programming exercises in C, covering various topics such as arithmetic, logical, bitwise, and control statements. Each exercise includes a brief description and the corresponding C code to implement the functionality, such as calculating roots of quadratic equations, reversing digits, and converting between number systems. The document serves as a practical guide for students to practice and enhance their programming skills.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

St.

PAUL’S DEGREE & PG COLLEGE


(Affiliated to Osmania University)
Street No. 8, Himayathnagar, Hyderabad. Ph.No: 27602533

Programming in C
Lab

1) Write a program using arithmetic operator.

//Arithmetic.cpp
#include<stdio.h>
#include<conio.h>
int main( )
{
clrscr( );
int a,b;
int op;
printf(" 1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division\n");
printf("Enter the values of a & b: ");
scanf("%d %d",&a,&b);
printf("Enter your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1:
printf("Sum of %d and %d is : %d",a,b,a+b);
break;
case 2:
printf("Difference of %d and %d is : %d",a,b,a-b);
break;
case 3:
printf("Multiplication of %d and %d is : %d",a,b,a*b);
break;
case 4:
printf("Division of Two Numbers is %d : ",a/b);
break;
default:
printf(" Enter Your Correct Choice.");
break;
}
getch( );
return 0;
}
2) Write a program using logical operator.

//Logical.cpp
#include<stdio.h>
#include<conio.h>
int main( )
{
clrscr( );
int a = 5, b = 10 ,ret;
ret = ( (a <= b) || (a != b) );
// 5 <= 10 ==> true. 5 != 10 ==> true. So, 1 || 1 will return 1.
printf("Return value of above expression is %d\n",ret);

ret = ( ( a < b) && (a == b ) );


// 5 < 10 ==>true. 5 == 10 ==> false. So, 1 && 0 will return 0;
printf("Return value of above expression is %d\n",ret);

ret = ! ( ( a < b) && (a == b ) );


/*we have used the same expression here.
And its result was 0. So !0 will be 1.*/
printf("Return value of above expression is %d\n",ret);
getch( );
return 0;
}

3) Write a program using bitwise operator.

//Bitwise.cpp
#include<stdio.h>
#include<conio.h>
int main( )
{
clrscr( );
int num1,num2;
printf(“Enter two integers:”);
scanf(“%d %d”,&num1 , &num2);
//Bitwise AND
int bitwiseAND = num1 & num2;
printf(“Bitwise AND :%d\n”,bitwiseAND);

//Bitwise OR
int bitwiseOR = num1 | num2;
printf(“Bitwise OR:%d\n”,bitwiseOR );

//Bitwise XOR
int bitwiseXOR = num1 ^ num2;
printf(“Bitwise XOR :%d\n”,bitwiseXOR );

//Bitwise left shift


int leftshift = num1 <<1;
printf(“Left shift by 1:%d\n”,leftshift) ;

//Bitwise right shift


int rightshift = num2 >>1;
printf(“Right shift by 1: %d\n” ,rightshift );
getch( );
return 0;
}

4)Write a program using ternary operator.


Ternary.cpp
#include<stdio.h>
#include<conio.h>
int main( )
{
clrscr( );
int age;
printf(“Enter your age:”);
scanf(“%d”,&age);
(age >= 18 ? printf(“You can vote”) : printf(“You cannot vote”));
getch( );
return 0;
}

5) Write a program using simple control statements for Roots of a Quadratic Equation.
//Roots of a Quadratic equation.
//Quadratic.cpp
#include <math.h>
#include<conio.h>
#include <stdio.h>
int main( ) {
clrscr( );
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);
}
getch( );
return 0;
}

6) Write a program using simple control statements for extracting digits of integers.

//Extracting digits of integers.


//Integers.cpp
#include <stdio.h>
#include<conio.h>
int main( )
{
clrscr( );
int num = 1024;
while(num != 0){
int digit = num % 10;
num = num / 10;
printf("%d\n", digit);
}
getch( );
return 0;
}

7) Write a program using simple control statements for reversing digits.

//Reversing Digits:
//Reversing.cpp
#include <stdio.h>
#include<conio.h>
int main( ) {
clrscr( );
int n, reverse = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0) {
remainder = n % 10;
reverse = reverse * 10 + remainder;
n = n/ 10;
}
printf("Reversed number = %d", reverse);
getch( );
return 0;
}

8)Write a program using simple control statements for finding sum of digits.
//Finding Sum of Digit.
//Sumofdigit.cpp
#include<stdio.h>
#include<conio.h>
int main( )
{
clrscr( );
int n,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);
getch( );
return 0;
}

9)Write a program using simple control statements for printing multiplication tables.
//Printing multiplication tables.
//Multitables.cpp
#include <stdio.h>
#include<conio.h>
int main( ) {
clrscr( );
int n, i;
printf("Enter an integer: ");
scanf("%d", &n);
for (i = 1; i <= 10; ++i) {
printf("%d * %d = %d \n", n, i, n * i);
}
getch( );
return 0;
}

10) Write a program using simple control statements for Armstrong Numbers.
//Armstrong.cpp

#include <stdio.h>
#include<conio.h>
int main( ) {
clrscr( );
int num, originalNum, remainder, result = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num;
while (originalNum != 0) {
// remainder contains the last digit
remainder = originalNum % 10;
result += remainder * remainder * remainder;
// removing last digit from the orignal number
originalNum /= 10;
}
if (result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
getch( );
return 0;
}

11) Write a program using simple control statements for checking for prime.
//Checkprime.cpp
#include <stdio.h>
#include<conio.h>
int main( ) {
clrscr( );
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
// 0 and 1 are not prime numbers
// change flag to 1 for non-prime number
if (n == 0 || n == 1)
flag = 1;
for (i = 2; i <= n / 2; ++i) {
// if n is divisible by i, then n is not prime
// change flag to 1 for non-prime number
if (n % i == 0) {
flag = 1;
break;
}
}
// flag is 0 for prime numbers
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
getch( );
return 0;
}

12) Write a program using simple control statements for magic numbers.
//Magicnum.cpp
#include <stdio.h>
#include <conio.h>
int main ( )
{
clrscr( );
// declare integer variables
int n, temp, rev = 0, digit, sum_of_digits = 0;
printf (" Enter a Number: \n");
scanf (" %d", &n); // get the number
temp = n; // assign the number to temp variable
// use while loop to calculate the sum of digits
while ( temp > 0)
{
// extract digit one by one and store into the sum_of_digits
sum_of_digits = sum_of_digits + temp % 10;
/* use modulus symbol to get the remainder of each iteration by temp % 10 */
temp = temp / 10;
}
temp = sum_of_digits; // assign the sum_of_digits to temp variable
printf (" \n The sum of the digits = %d", temp);

// get the reverse sum of given digits


while ( temp > 0)
{
rev = rev * 10 + temp % 10;
temp = temp / 10;
}

printf (" \n The reverse of the digits = %d", rev);


printf (" \n The product of %d * %d = %d", sum_of_digits, rev, rev *
sum_of_digits);
// use if else statement to check the magic number
if ( rev * sum_of_digits == n)
{
printf (" \n %d is a Magic Number. ", n);
}
else
{
printf (" \n %d is not a Magic Number. ", n);
}
getch( );
return 0;
}

13) Write a program to find the value of sin(x) using series expansion.
/* A C program to computer value of sin(x) using series expansion */

#include<stdio.h>
#include<math.h>
#include<conio.h>
unsigned long int fact(int n);
void main( )
{
clrscr( );
int sign=1,x,i;
double sum=0,r;
printf(“Enter the radius :”);
scanf(“%d”,&x);
r=(x*3.14f)/180; /* Converting radius value */
for(i=1;i<=10;i+=2)
{
sum=sum+( (pow(r,i)/fact(i)) * sign );
sign= -sign;
}
printf(“sin(%d) = %lf\n”,x,sum);
}
unsigned long int fact(int n)
{
unsigned long int f=1;
int i;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}

14) Write a program to find the value of cos(x) using series expansion.

/* A C program to computer value of cos(x) using series expansion */

#include<stdio.h>
#include<math.h>
#include<conio.h>
unsigned long int fact(int n);
void main( )
{
clrscr( );
int sign=1,x,i;
double sum=1,r;
printf(“Enter the radius :”);
scanf(“%d”,&x);
r=(x*3.14f)/180; /* Converting radius value */
for(i=2;i<=10;i+=2)
{
sign= -sign;
sum=sum+( (pow(r,i)/fact(i)) * sign );
}
printf(“Cos(%d) = %lf\n”, x,sum);
}
unsigned long int fact(int n)
{
unsigned long int f=1;
int i;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
15) Write a program to convert Binary to Decimal.
// Convert binary to decimal
//Binarytodec.cpp
#include <stdio.h>
#include <math.h>
#include<conio.h>
// function prototype
int convert(long long);
int main( ) {
clrscr( );
long long n;
printf("Enter a binary number: ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimal", n, convert(n));
getch( );
return 0;
}
// function definition
int convert(long long n) {
int dec = 0, i = 0, rem;
while (n!=0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}

16)Write a program to convert Decimal to Binary.


//Convert decimal to binary
//Dectobinary.cpp
#include <stdio.h>
#include <math.h>
#include<conio.h>
long long convert(int);
int main( ) {
clrscr( );
int n, bin;
printf("Enter a decimal number: ");
scanf("%d", &n);
bin = convert(n);
printf("%d in decimal = %lld in binary", n, bin);
return 0;
}
long long convert(int n) {
long long bin = 0;
int rem, i = 1;
while (n!=0) {
rem = n % 2;
n /= 2;
bin += rem * i;
i *= 10;
}
return bin;
}

17)Write a program to convert Binary to Octal.

//Convert binary to octal.


//Bintooctal.cpp
#include <math.h>
#include <stdio.h>
#include<conio.h>
int convert(long long bin);
int main( ) {
long long bin;
printf("Enter a binary number: ");
scanf("%lld", &bin);
printf("%lld in binary = %d in octal", bin, convert(bin));
getch( );
return 0;
}
int convert(long long bin) {
int oct = 0, dec = 0, i = 0;
// converting binary to decimal
while (bin != 0) {
dec += (bin % 10) * pow(2, i);
++i;
bin /= 10;
}
i = 1;
// converting to decimal to octal
while (dec != 0) {
oct += (dec % 8) * i;
dec /= 8;
i *= 10;
}
return oct;
}
18)Write a program to convert Octal to Binary
//Convert octal to binary:
//Octtobinary.cpp
#include <math.h>
#include <stdio.h>
long long convert(int oct);
int main( ) {
clrscr( );
int oct;
printf("Enter an octal number: ");
scanf("%d", &oct);
printf("%d in octal = %lld in binary", oct, convert(oct));
getch( );
return 0;
}
long long convert(int oct) {
int dec = 0, i = 0;
long long bin = 0;
// converting octal to decimal
while (oct != 0) {
dec += (oct % 10) * pow(8, i);
++i;
oct /= 10;
}
i = 1;
// converting decimal to binary
while (dec != 0) {
bin += (dec % 2) * i;
dec /= 2;
i *= 10;
}
return bin;
}

19) Write a program to convert Binary to Hexadecimal.


//Bintohex.cpp

#include<stdio.h>
#include<conio.h>
void main( )
{
long int binary_number, hexadecimal_number = 0, i = 1, remainder;
clrscr();
printf("Please Enter any Binary Number: ");
scanf("%ld", &binary_number);
while (binary_number != 0)
{
remainder = binary_number % 10;
hexadecimal_number = hexadecimal_number + remainder * i;
i = i * 2;
binary_number = binary_number / 10;
}
printf("Equivalent Hexadecimal Number %lX", hexadecimal_number);
getch( ); }

20)Write a program to convert Hexadecimal to Binary.


//Hextobin.cpp

#include<stdio.h>
#include<conio.h>
#define MAX 1000
void main()
{
char binary_number[MAX], hexa[MAX];
long int i = 0;
clrscr();

printf("Enter the value for Hexadecimal ");


scanf("%s", hexa);
printf("\n Equivalent Binary value: ");
while (hexa[i])
{
switch (hexa[i])
{
case '0':
printf("0000"); break;
case '1':
printf("0001"); break;
case '2':
printf("0010"); break;
case '3':
printf("0011"); break;
case '4':
printf("0100"); break;
case '5':
printf("0101"); break;
case '6':
printf("0110"); break;
case '7':
printf("0111"); break;
case '8':
printf("1000"); break;
case '9':
printf("1001"); break;
case 'A':
printf("1010"); break;
case 'B':
printf("1011"); break;
case 'C':
printf("1100"); break;
case 'D':
printf("1101"); break;
case 'E':
printf("1110"); break;
case 'F':
printf("1111"); break;
case 'a':
printf("1010"); break;
case 'b':
printf("1011"); break;
case 'c':
printf("1100"); break;
case 'd':
printf("1101"); break;
case 'e':
printf("1110"); break;
case 'f':
printf("1111"); break;
default:
printf("\n Invalid hexa digit %c ", hexa[i]);
}
i++;
}
getch();
}

21)Write a program to create a Pascal triangle.


//Pascal.cpp
#include <stdio.h>
#include<conio.h>
int main( ) {
clrscr( );
int rows, coef = 1, space, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 0; i < rows; i++) {
for (space = 1; space <= rows - i; space++)
printf(" ");
for (j = 0; j <= i; j++) {
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%4d", coef);
}
printf("\n");
}
getch();
return 0;
}

22)Write a program to create Pyramid of numbers.


//Pyramid.cpp
#include <stdio.h>
#include<conio.h>
int main( ) {
clrscr( );
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));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
getch( );
return 0;
}

23)Write a program to find the factorial of a number using recursion.


//Factorial.cpp
#include<stdio.h>
#include<conio.h>
long int multiplyNumbers(int n);
int main( ) {
clrscr( );
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
getch( );
return 0;
}
long int multiplyNumbers(int n) {
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}

24)Write a program to fibnocci series using recursion.


//Fibnocci.cpp

#include<stdio.h>
#include<conio.h>
int main( )
{
clrscr( );
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements:");
scanf("%d",&number);
printf("\n%d %d",n1,n2);//printing 0 and 1
for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
getch( );
return 0;
}
25)Write a program to GCD of two numbers.
//GCD.cpp

#include <stdio.h>
#include<conio.h>
int hcf(int n1, int n2);
int main( ) {
clrscr( );
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));
getch( );
return 0;
}
int hcf(int n1, int n2) {
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}

26)Write a program to find the maximum, minimum, average and standard deviation
of given set of numbers using arrays.

//Array.cpp
#include<stdio.h>
#include<conio.h>
int main( )
{
clrscr( );
int a[1000],i,n,min,max,sum=0,SD,sum1;
float average,mean;
printf("Enter size of the array : ");
scanf("%d",&n);
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
sum1 += (a[i] - mean) * (a[i] - mean);
}
min=max=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i]; }
average = 1.0*sum/n;
SD = sqrt(sum1 / n);
printf("sum is : %d\n ",sum);
printf("mean is : %d\n ",sum1);
printf("standard deviation is : %d\n ",SD);
printf("Your average is %.2f\n",average);
printf("minimum of array is : %d",min);
printf("\nmaximum of array is : %d",max);
getch( );
return 0;
}

27)Write a program to reverse an array ,removal of duplicates from array.


//Array1.cpp
#include<stdio.h>
#include<conio.h>
int main( ) {
int arr[20], i, j, k, size;
printf("\nEnter array size : ");
scanf("%d", &size);
printf("\nAccept Numbers : ");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("\nArray with Unique list : ");
for (i = 0; i < size; i++) {
for (j = i + 1; j < size;) {
if (arr[j] == arr[i]) {
for (k = j; k < size; k++) {
arr[k] = arr[k + 1];
}
size--;
} else
j++;
}
}
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
getch( );
return (0);
}

28)Write a program to Matrix addition using functions.


#include <stdio.h>
// Function to read a matrix from the user
void readMatrix(int matrix[][100], int rows, int columns) {
printf("Enter the elements of the matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
scanf("%d", &matrix[i][j]);
}
}
}

// Function to add two matrices and store the result in a third matrix
void addMatrices(int matrix1[][100], int matrix2[][100], int result[][100], int rows, int
columns) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}

// Function to display a matrix


void displayMatrix(int matrix[][100], int rows, int columns) {
printf("Matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}

int main() {
int rows, columns;

printf("Enter the number of rows and columns of the matrices: ");


scanf("%d %d", &rows, &columns);

int matrix1[100][100], matrix2[100][100], result[100][100];

printf("For the first matrix:\n");


readMatrix(matrix1, rows, columns);

printf("For the second matrix:\n");


readMatrix(matrix2, rows, columns);

addMatrices(matrix1, matrix2, result, rows, columns);


printf("Result of matrix addition:\n");
displayMatrix(result, rows, columns);

return 0;
}

29) Write a program to Matrix multiplication using functions.


#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");
}
else
{
int m1[r1][c1],m2[r2][c2];
printf("Enter first matrix elements \n");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
{
scanf("%d",&m1[i][j]);
}
}
printf("Enter Second matrix elements\n");
for(int i=0;i<r2;i++)
{
for(int j=0;j<c2;j++)
{
scanf("%d",&m2[i][j]);
}
}
int mul[r1][c2];
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
{
mul[i][j]=0;

// Multiplying i’th row with j’th column


for(int k=0;k<c1;k++)
{
mul[i][j]+=m1[i][k]*m2[k][j];
}
}
}
printf("Multiplied matrix\n");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
}
return 0;
}

30) Write a program to find the transpose of a square matrix using functions.

#include <stdio.h>
void transpose(int p[3][3], int t[3][3]);
int main() {
int i, j;
int p[3][3], t[3][3];
printf("Enter matrix P\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("Enter the elements of matrix P [%d,%d]: ", i, j);
scanf("%d", & p[i][j]);
}
}
transpose(p, t);
printf("Transpose of matrix P is:\n\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", t[i][j]);
}
printf("\n");
}}
void transpose(int p[3][3], int t[3][3]) {
int row, col;
for (row = 0; row < 3; row++) {
for (col = 0; col < 3; col++) {
t[row][col] = p[col][row];
} }}

31) Write a program for functions of string manipulation: inputting and outputting string , using
string functions such as strlen( ), strcat( ), strcpy( ) ………etc.

#include <stdio.h>
#include <string.h>
int main() {
char inputString[100]; // To store user input
char resultString[200]; // To store manipulated strings

// Input a string
printf("Enter a string: ");
scanf("%s", inputString);

// Calculate and print the length of the input string


int length = strlen(inputString);
printf("Length of the string: %d\n", length);

// Copy the input string to the result string


strcpy(resultString, inputString);
printf("Copied string: %s\n", resultString);

// Concatenate a second string to the result string


char appendString[100];
printf("Enter a string to concatenate: ");
scanf("%s", appendString);
strcat(resultString, appendString);
printf("Concatenated string: %s\n", resultString);

return 0;
}

32) Write a simple programs for strings without using string functions.

#include <stdio.h>
#include <string.h>
int main( ) {
char inputString[100]; // To store user input
char resultString[200]; // To store manipulated strings
// Input a string
printf("Enter a string: ");
scanf("%s", inputString);
// Calculate and print the length of the input string
int length = strlen(inputString);
printf("Length of the string: %d\n", length);
// Copy the input string to the result string
strcpy(resultString, inputString);
printf("Copied string: %s\n", resultString);
// Concatenate a second string to the result string
char appendString[100];
printf("Enter a string to concatenate: ");
scanf("%s", appendString);
strcat(resultString, appendString);
printf("Concatenated string: %s\n", resultString);
return 0;
}

33) Write a program to find the No. of characters, words and lines of given text file.

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char path[100];
char ch;
int characters, words, lines;
/* Input path of files to merge to third file */
printf("Enter source file path: ");
scanf("%s", path);
/* Open source files in 'r' mode */
file = fopen(path, "r");
/* Check if file opened successfully */
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");

exit(EXIT_FAILURE);
}
/*
* Logic to count characters, words and lines.
*/
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;
/* Check new line */
if (ch == '\n' || ch == '\0')
lines++;
/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
/* Increment words and lines for last word */
if (characters > 0)
{
words++;
lines++;
}
/* Print file statistics */
printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);
/* Close files to release resources */
fclose(file);
return 0;
}

34)Write a program for file handling programs : student memo printing.

#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[50];
int rollNumber;
float marks;
} Student;

int main() {
FILE *inputFile, *outputFile;
char inputFileName[] = "student_info.txt";
char outputFileName[] = "student_memos.txt";

// Open the input file for reading


inputFile = fopen(inputFileName, "r");
if (inputFile == NULL) {
printf("Error opening input file %s.\n", inputFileName);
return 1;
}
// Open the output file for writing
outputFile = fopen(outputFileName, "w");
if (outputFile == NULL) {
printf("Error opening output file %s.\n", outputFileName);
return 1;
}

// Read student information from the input file and generate memos
Student student;
while (fscanf(inputFile, "%s %d %f", student.name, &student.rollNumber,
&student.marks) != EOF) {
// Generate the student memo
fprintf(outputFile, "Student Name: %s\n", student.name);
fprintf(outputFile, "Roll Number: %d\n", student.rollNumber);
fprintf(outputFile, "Marks: %.2f\n", student.marks);
fprintf(outputFile, "----------------------------------\n");
}

// Close the input and output files


fclose(inputFile);
fclose(outputFile);

printf("Student memos have been generated in %s.\n", outputFileName);

return 0;
}

35)Write a program in C to copy the elements of one array into another array using for loop.
#include <stdio.h>
int main()
{
//Initialize array
int arr1[] = {1, 2, 3, 4, 5};

//Calculate length of array arr1


int length = sizeof(arr1)/sizeof(arr1[0]);

//Create another array arr2 with the size of arr1.


int arr2[length];

//Copying all elements of one array into another


for (int i = 0; i < length; i++) {
arr2[i] = arr1[i];
}
//Displaying elements of array arr1
printf("Elements of original array: \n");
for (int i = 0; i < length; i++) {
printf("%d ", arr1[i]);
}

printf("\n");

//Displaying elements of array arr2


printf("Elements of new array: \n");
for (int i = 0; i < length; i++) {
printf("%d ", arr2[i]);
}
return 0;
}

36)Write a C program to check whether a given number is positive or negative using conditional
statement.
#include <stdio.h>
int main() {
int number;

// Input
printf("Enter a number: ");
scanf("%d", &number);

// Check if the number is positive or negative


if (number > 0) {
printf("The number is positive.\n");
} else if (number < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}

return 0;
}

37)Write a program in C to print the current date and time.


#include <stdio.h>
#include <time.h>

int main() {
time_t rawtime;
struct tm *timeinfo;

time(&rawtime);
timeinfo = localtime(&rawtime);

printf("Current date and time: %s", asctime(timeinfo));

return 0;
}

38)Write a program in C to reverse a string using recursion.


#include <stdio.h>
void reverseString(char *str, int start, int end) {
if (start >= end) {
return;
}

// Swap the characters at the start and end positions


char temp = str[start];
str[start] = str[end];
str[end] = temp;

// Recursively call the function with updated start and end positions
reverseString(str, start + 1, end - 1);
}

int main() {
char str[100];

printf("Enter a string: ");


scanf("%s", str);

int length = 0;
while (str[length] != '\0') {
length++;
}
reverseString(str, 0, length - 1);
printf("Reversed string: %s\n", str);
return 0;
}

39)Write a program in C to add numbers using call by reference.


#include <stdio.h>
#include<stdio.h>
void addNumbers(int num1,int num2,int *result){
*result = num1+num2}
int main( ) {
int num1, num2, sum;

printf("Enter the first number: ");


scanf("%d", &num1);

printf("Enter the second number: ");


scanf("%d", &num2);

// Call the addNumbers function with call by reference


addNumbers(num1, num2, &sum);

printf("The sum of %d and %d is: %d\n", num1, num2, sum);

return 0;
}

40)Write a program to print ASCII Value of a Character.


#include <stdio.h>
int main() {
char character;
printf("Enter a character: ");
scanf("%c", &character);
int asciiValue = character; // Implicitly converts the character to its ASCII value
printf("The ASCII value of %c is %d\n", character, asciiValue);
return 0;
}

41)Write a program to check leap year.


#include <stdio.h>
int main( ) {
int year;

// Input the year from the user


printf("Enter a year: ");
scanf("%d", &year);

// Check if it's a leap year


if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
printf("%d is a leap year.\n", year);
} else {
printf("%d is not a leap year.\n", year);
}
return 0;
}

42)Write a program to concatenate strings using pointers.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( ) {
char *str1, *str2, *result;
int len1, len2;

// Input the first string


printf("Enter the first string: ");
scanf("%m[^\n]s", &str1); // %m is used for dynamic memory allocation

// Input the second string


getchar(); // Consume the newline character
printf("Enter the second string: ");
scanf("%m[^\n]s", &str2);

// Calculate the lengths of the two strings


len1 = strlen(str1);
len2 = strlen(str2);

// Allocate memory for the result string


result = (char *)malloc(len1 + len2 + 1); // +1 for the null-terminator

if (result == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
return 1;
}

// Copy the first string to the result


strcpy(result, str1);

// Concatenate the second string to the result


strcat(result, str2);

// Print the concatenated string


printf("Concatenated string: %s\n", result);

// Free the allocated memory


free(str1);
free(str2);
free(result);

return 0;
}

43)Write a program to check square matrix using for loop.


#include <stdio.h>
int main( ) {
int n; // The order of the matrix (number of rows and columns)
printf("Enter the order of the matrix: ");
scanf("%d", &n);
int matrix[n][n]; // Declare a square matrix of size n x n

// Input the elements of the matrix


printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
} }

// Check if the matrix is square


if (n <= 0) {
printf("The order of the matrix should be a positive integer.\n");
} else if (n == 1) {
printf("The matrix is square (1x1 matrix).\n");
} else {
int isSquare = 1; // Assume the matrix is square by default
for (int i = 0; i < n; i++) {
if (n != n) {
isSquare = 0;
break;
}
}

if (isSquare) {
printf("The matrix is square (%dx%d matrix).\n", n, n);
} else {
printf("The matrix is not square.\n");
}
}
return 0;
}

44) Write a program to find strong number using functions.


#include <stdio.h>
// Function to calculate the factorial of a number
int factorial(int num) {
if (num == 0 || num == 1) {
return 1;
} else {
return num * factorial(num - 1);
}
}
// Function to check if a number is a strong number
int isStrongNumber(int num) {
int originalNum = num;
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += factorial(digit);
num /= 10;
}
return (sum == originalNum);
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
if (isStrongNumber(n)) {
printf("%d is a strong number.\n", n);
} else {
printf("%d is not a strong number.\n", n);
}
return 0;
}

45) Write a program to create a calculator using functions.


#include <stdio.h>
// Function to add two numbers
double add(double a, double b) {
return a + b;
}
// Function to subtract two numbers
double subtract(double a, double b) {
return a - b;
}
// Function to multiply two numbers
double multiply(double a, double b) {
return a * b;
}
// Function to divide two numbers
double divide(double a, double b) {
if (b != 0) {
return a / b;
} else {
printf("Error: Division by zero is not allowed.\n");
return 0;
}
}
int main() {
double num1, num2;
char operator;
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
double result;
switch (operator) {
case '+':
result = add(num1, num2);
break;
case '-':
result = subtract(num1, num2);
break;
case '*':
result = multiply(num1, num2);
break;
case '/':
result = divide(num1, num2);
break;
default:
printf("Error: Invalid operator\n");
return 1;
}
printf("Result: %lf\n", result);
return 0;
}

46) Write a program to find natural numbers.


#include <stdio.h>
int main() {
int limit;
printf("Enter the limit: ");
scanf("%d", &limit);

if (limit < 1) {
printf("Please enter a positive limit.\n");
return 1; // Exit with an error code.
}
printf("Natural numbers up to %d are:\n", limit);
for (int i = 1; i <= limit; i++) {
printf("%d ", i);
}
printf("\n");
return 0; // Exit successfully.
}

47) Write a program to print array in reverse.


#include <stdio.h>
int main() {
int array[] = {1, 2, 3, 4, 5};
int size = sizeof(array) / sizeof(array[0]);
printf("Original Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
printf("Array in Reverse Order: ");
for (int i = size - 1; i >= 0; i--) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}

48) Write a program to convert lowercase string to uppercase string.


#include <stdio.h>
#include <ctype.h>
int main( ) {
char inputString[100];
char outputString[100];
printf("Enter a lowercase string: ");
fgets(inputString, sizeof(inputString), stdin);
int i = 0;
while (inputString[i] != '\0') {
if (islower(inputString[i])) {
outputString[i] = toupper(inputString[i]);
} else {
outputString[i] = inputString[i];
}
i++;
}
outputString[i] = '\0';
printf("Uppercase string: %s", outputString);
return 0;
}

49) Write a C program to find the sum of the series 12 + 22+ 32 + …….n2.
#include <stdio.h>
int main() {
int n, sum = 0;
// Prompt the user to enter the value of n
printf("Enter the value of n: ");
scanf("%d", &n);
// Calculate the sum of the series
for (int i = 1; i <= n; i++) {
sum += i * i;
}
// Display the sum
printf("The sum of the series is: %d\n", sum);
return 0;
}

50)Write a C program to accept and display the details of an employee using


structures.
#include <stdio.h>
// Define a structure for an employee
struct Employee {
char name[50];
int employeeID;
float salary;
};
int main() {
// Declare a variable of type 'struct Employee'
struct Employee emp;
// Input employee details
printf("Enter Employee Details:\n");
printf("Name: ");
scanf("%s", emp.name); // Note: Using %s for strings without spaces
printf("Employee ID: ");
scanf("%d", &emp.employeeID);
printf("Salary: ");
scanf("%f", &emp.salary);
// Display employee details
printf("\nEmployee Details:\n");
printf("Name: %s\n", emp.name);
printf("Employee ID: %d\n", emp.employeeID);
printf("Salary: $%.2f\n", emp.salary);
return 0;}

You might also like