C Practice Programs

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

C Practice Programs

Write a C program to search an element in an array using binary searching


technique.
Write a C program to sort the given array elements using selection sort technique.
Write a C program to insert an element into an array at a given position.

#include<stdio.h>
int main()
{
// original array
int arr[] = {10, 20, 30, 40, 50};

// take position and element


int index, key;
printf("Enter position: ");
scanf("%d", &index);
printf("Enter element to insert: ");
scanf("%d", &key);

// calculate size of the array


int n = sizeof(arr)/sizeof(arr[0]);

// check position
if(index < 0 || index > n)
{
printf("Error! The position is not valid.");
printf("\nPlease, Enter position from 0 to %d\n", n);
return 0;
}

// create new array of size = n+1


int temp[n+1];

// copy elements
for (int i=0, j=0; i <= n; ++i)
{
if(i == index) temp[i] = key;
else temp[i] = arr[j++];
}

// display new array


printf("Array elements are: \n");
for (int i = 0; i <= n; ++i)
{
printf("%d ", temp[i]);
}

return 0;
}
Write a C program to read two matrices A (M x N) and B (P x Q) and compute the
sum of A and B after checking compatibility for addition. Output the input matrices
and the resultant matrix with suitable headings and format.

#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the 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]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%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];
}
// printing 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("\n\n");
}
}

return 0;
}
Write a C program to copy one string to another string without using inbuilt
function.

// CPP program to copy one string to other


// without using in-built function
  
#include <stdio.h>
int main()
{
    // s1 is the source( input) string and s2 is the destination string
    char s1[] = "GeeksforGeeks", s2[100], i;
  
    // Print the string s1
    printf("string s1 : %s\n", s1);
  
    // Execute loop till null found
    for (i = 0; s1[i] != '\0'; ++i) {
        // copying the characters by
        // character to str2 from str1
        s2[i] = s1[i];
    }
  
    s2[i] = '\0';
  
    // printing the destination string
    printf("String s2 : %s", s2);
  
    return 0;
}

Write a C program to concatenate two strings without using inbuilt function.

// C Program to concatenate
// two strings without using strcat
  
#include <stdio.h>
  
int main()
{
  
    // Get the two Strings to be concatenated
    char str1[100] = "Geeks", str2[100] = "World";
  
    // Declare a new Strings
    // to store the concatenated String
    char str3[100];
  
    int i = 0, j = 0;
  
    printf("\nFirst string: %s", str1);
    printf("\nSecond string: %s", str2);
  
    // Insert the first string in the new string
    while (str1[i] != '\0') {
        str3[j] = str1[i];
        i++;
        j++;
    }
  
    // Insert the second string in the new string
    i = 0;
    while (str2[i] != '\0') {
        str3[j] = str2[i];
        i++;
        j++;
    }
    str3[j] = '\0';
  
    // Print the concatenated string
    printf("\nConcatenated string: %s", str3);
  
    return 0;
}

Write a user defined function Factorial(num) that accepts an integer argument and
returns its factorial value. Write a C program that invokes this function to find
factorial of a given number.

#include <stdio.h>
  
long factorial(int num)     //function for calculating factorial which takes an
integer value as a parameter and returns an int type value
{
  int i;
  long fact = 1;
  
  for (i = 1; i <= num; i++)
    fact = fact * i;
 return fact;       //returns to function call
}
  
int main()          //execution begins from main() method
{
  int num;
  
  printf("Enter a number to calculate its factorialn");
  scanf("%d", &num);
  if(num<0) //if the input is a negative integer
  {
   printf("Factorial is not defined for negative numbers.");
   }
  printf("Factorial of %d = %dn", num,
factorial(num));                                 //call to factorial function
passing  the input as parameter
   return 0;
}

Write a user defined function Greatest(num1,num2,num3) that accepts three


integer arguments and returns the greatest element. Write a C program that
invokes this function to find greatest of three numbers.

#include<stdio.h>

// function to find largest among three number


float large(float a, float b, float c)
{
if(a>=b && a>=c) return a;
else if(b>=a && b>=c) return b;
else return c;
}

int main()
{
float num1, num2, num3, largest;

printf("Enter three numbers: ");


scanf("%f %f %f", &num1, &num2, &num3);

largest = large(num1, num2, num3);


printf("Largest number = %.2f",largest);
return 0;
}

Write a C program to compute the roots of a quadratic equation by accepting the


coefficients. Print appropriate messages.

#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;

// condition for real and different roots


if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart,
realPart, imagPart);
}
return 0;
}
Write a C program to reverse the given number and check whether it is palindrome
or not.

#include <stdio.h>
int main() {
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;

// reversed integer is stored in reversed variable


while (n != 0) {
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}

// palindrome if orignal and reversed are equal


if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);

return 0;
}

An electricity board charges the following rates for the use of electricity: for the first
200 units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units
Rs. 1 per unit. All users are charged a minimum of Rs. 100 as meter charge. If the
total amount is more than Rs. 400, then an additional subcharge of 15% of total
amount is charged. Write a program to read the name of the user, number of units
consumed and print out the charges.

#include<stdio.h>

void main()
{
char name[20];
float unit,price,extra;
clrscr();
printf("\nEnter Consumer's name:");
gets(name);
printf("\nEnter units of electricity used:");
scanf("%f",&unit);
if(unit<=200)
{
price=(80*unit)/100 + 100;
puts(name);
printf("\nUnits = %.2f  Rate = 80 paise/unit  meter charges = 100 price = %.2f",unit,price);
}
else if(unit>200 && unit<=300)
{
extra=unit-200;
price=(80*unit)/100 + 90*extra/100 + 100;
puts(name);
printf("\nUnits = %.2f  Rate = 80 paise/unit for 200 units and 90 paise/unit above  meter charges = 100 price =
%.2f",unit,price);
}
else if(unit>300 && unit <=400)
{
price=unit +100 ;
puts(name);
printf("\nUnits = %.2f  Rate = 1 rupees/unit  meter charges = 100 price = %.2f",unit,price);
}
else if(unit>400)
{
price=unit + unit*(15/100) + 100;
puts(name);
printf("\nUnits = %.2f  Rate = 1 rupees/unit  extra charges = 15/100 of total   meter charges = 100    price =
%.2f",unit,price);
}

}
Write a C program to accept and check the given number is Armstrong or not.
[Armstrong number is a number that is equal to the sum of cubes of its digits. For
example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.

153= (1*1*1)+(5*5*5)+(3*3*3)  where:  (1*1*1)=1 ,(5*5*5)=125 , (3*3*3)=27  
So: 1+125+27=153]

#include <stdio.h>
int main() {
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);

return 0;
}
Write a C program to input a number and check whether the number is perfect
number or not. [Perfect number is a positive integer which is equal to the sum of its
proper positive divisors. For example: 6 is the first perfect number.

Proper divisors of 6 are 1, 2, 3

Sum of its proper divisors = 1 + 2 + 3 = 6.

Hence 6 is a perfect number.]

/*C program to check whether the given number is the Perfect number*/  
#include<stdio.h>  
#include<conio.h>  
void main()  
{  
// declare and initialize the variables  
int num, rem, sum = 0, i;  
// take an input from the user.  
printf("Enter a number\n");  
scanf("%d", &num);      
// find all divisors and add them  
for(i = 1; i < num; i++)  
                     {  
                              rem = num % i;  
                             if (rem == 0)  
                                        {  
                                               sum = sum + i;  
                                         }  
                        }  
if (sum == num)  
                      printf(" %d is a Perfect Number");  
           else  
                      printf("\n %d is not a Perfect Number");  
getch();  
}  
Write a C program to find sum of digits in a given number.

[Example: Num =123 sum = 1+2+3= 6]


#include <stdio.h>
int main()
{
   int n, sum = 0, r;

   printf("Enter a number\n");

   for (scanf("%d", &n); n != 0; n = n/10) {
      r = n % 10;
      sum = sum + r;
   }

   printf("Sum of digits of a number = %d\n", sum);

   return 0;
}

Write a C program to check whether a given year is leap year or not.


Note: There are two conditions for leap year: 1- If year is divisible by 400 (for
Century years), 2- If year is divisible by 4 and must not be divisible by 100 (for Non
Century years).

#include <stdio.h>

int main()
{
int yr;

printf("\n Please Enter any number you wish \n ");


scanf("%d", &yr);

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


printf("\n %d is a Leap. \n", yr);
else
printf("\n %d is not. \n", yr);

return 0;
}
Write a C program to find the factorial of a number, where the number n is entered
by user.

#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);

// shows error if the user enters a negative integer


if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for (i = 1; i <= n; ++i) {
fact *= i;
}
printf("Factorial of %d = %llu", n, fact);
}

return 0;
}

Write a C program using for loop to find out the sum of series 1 2 + 22
+ …. + n2
/* C Program to Calculate Sum of series 1²+2²+3²+....+n² */
#include <stdio.h>

int main()
{
int Number, Sum = 0;

printf("\n Please Enter any positive integer \n");


scanf(" %d",&Number);
Sum = (Number * (Number + 1) * (2 * Number + 1 )) / 6;
printf("\n The Sum of Series for %d = %d ",Number, Sum);

}
Write a C program to search an element in an array using linear
searching technique.

#include<stdio.h>
  
int main()
{
    int a[20],i,x,n;
    printf("How many elements?");
    scanf("%d",&n);
     
    printf("Enter array elements:n");
    for(i=0;i<n;++i)
        scanf("%d",&a[i]);
     
    printf("nEnter element to search:");
    scanf("%d",&x);
     
    for(i=0;i<n;++i)
        if(a[i]==x)
            break;
     
    if(i<n)
        printf("Element found at index %d",i);
    else
        printf("Element not found");
  
    return 0;
}

Write a C program to find smallest and largest element in an array.

#include<stdio.h>
 
int main()
{
int a[50],i,n,large,small;
printf("How many elements:");
scanf("%d",&n);
printf("Enter the Array:");
 
for(i=0;i<n;++i)
scanf("%d",&a[i]);
large=small=a[0];
for(i=1;i<n;++i)
{
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("The largest element is %d",large);
printf("\nThe smallest element is %d",small);
 
return 0;
}

Write a C program to find count of vowels and consonants in a given


string.

#include <string.h>

int main()
{
    char s[1000];  
    int i,vowels=0,consonants=0;

    printf("Enter  the string : ");


    gets(s);
    
    for(i=0;s[i];i++)  
    {
     if((s[i]>=65 && s[i]<=90)|| (s[i]>=97 && s[i]<=122))
     {

            if(s[i]=='a'|| s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O' ||s[i]=='U')


      vowels++;
            else
             consonants++;
        }
 
}

    
    printf("vowels = %d\n",vowels);
    printf("consonants = %d\n",consonants);
    
    return 0;
}
Write a C program to find length of the string without using strlen ( )
function.
// C program to find length of the string without using strlen() function
#include <stdio.h>
int main()
{
char s[100];
int i;

printf(“Enter a string: “);


scanf(“%s”, s);

for(i = 0; s[i] != ‘\0’; ++i);

printf(“Length of string: %d”, i);


return 0;

Write a C program to compare two strings using strcmp ( ) function.


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

int main()
{
char a[100], b[100];
printf("Enter the first string\n");
gets(a);

printf("Enter the second string\n");


gets(b);

if( strcmp(a,b) == 0 )
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");
return 0;
}

Write a C program to read and print two dimensional array.

#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%d ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return 0;
}

Write a C program to find sum of two integer elements using functions.


#include<stdio.h>
void main()
{
       int a,b;
       clrscr();
       printf("Enter Two Number : ");
       scanf("%d%d",&a,&b);
       sum(a,b);
       getch();
}
      sum(int x,int y)
 {
       int z;
       z=x+y;
       printf("Sum of Two Number is : %d",z);
       return 0;
}
Write a C program to find product of n natural numbers.

#include<stdio.h>
int main()
{
int num, rem, prod = 1;
printf("Enter a number: ");
scanf("%d", &num);
while(num != 0)
{
rem = num % 10; // get the last-digit
prod *= rem; // calculate product of digits
num /= 10; // remove the last digit
}
printf("%d", prod);
return 0;
}

Write a C program to find sum of n natural numbers.

#include <stdio.h>
int main() {
int n, i, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &n);

for (i = 1; i <= n; ++i) {


sum += i;
}

printf("Sum = %d", sum);


return 0;
}

You might also like