C Programming

1. Wap to check if the given number is armstrong number or not.

#include<stdio.h>
#include<conio.h>
void main(){
	int a,t,l,sum=0;
	printf("\nPlease enter your number\n");
	scanf("%d",&a);
	t=a;
	while(a>0){
		l=a%10;
		sum=sum+l*l*l;
		a=a/10;
	}
	if(sum==t)
		printf("Given number is the armstrong number");
	else
		printf("Given number is not the armstrong number");
	getch();
}

 
2. Wap to implement binary search.

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main(){
	int arr[10],num,i,n,pos=-1,beg,end,found=0,mid;
	printf("\n PLease enter the number of elements");
	scanf("%d",&n);
	printf("\n Enter the elements");
	for(i=0;i<n;i++){
		scanf("%d",&arr[i]);
	}
	printf("\n Enter the element that is to be searched");
	scanf("%d",&num);
	beg=0;
	end=n-1;
	while(beg<=end){
		mid=(beg+end)/2;
		if(arr[mid]==num){
			printf("\n %d is present in the array at the position = %d ",num,mid+1);
			found=1;
			break;
		}
		else if(arr[mid]>num)
			end=mid-1;
		else//(arr[mid]<mid)
			beg=mid+1;
	}
	if(beg>end&&found==0)
		printf("\n Sorry that element is not present in the array");
	getch();
}

3. Wap to print Fibonacci Series.

#include<stdio.h>
#include<conio.h>
void main(){
	int a=0,b=1,n,c,i;
	printf("\n Enter the no of times to generate fiboacci");
	scanf("%d",&n);
	printf("\n HERE COMES YOUR FIBONACCI ");
	printf("%d %d ",a,b);
	for(i=0;i<n;i++){
		c=a+b;
		a=b;
		b=c;
		printf("%d ",c);
	}
	getch();
}

4. Wap to implement palindrome. 

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main(){
	char a[100],b[100];
	printf("\n Enter the string for the pallindorme");
	gets(a);
	strcpy(b,a);
	strrev(a);
	if(strcmp(a,b)==0)
		printf("Given string is pallindrome");
	else
		printf("Given string is not pallindrome");
	getch();
}

5. Wap to check if given number is prefect number or not.

#include<stdio.h>
#include<conio.h>
void main(){
	// for example 6 is 1+2+3
	int n,i=1,sum=0;
	printf("Please Enter the number\n");
	scanf("%d",&n);
	while(i<n){
		if(n%i==0)
			sum=sum+i;
		i++;
	}
	if(sum==n)
		printf("Entered number is the perfect number");
	else
		printf("Entered number is not perfect");
	getch();
}

6. Wap to reserve a given number.

#include<stdio.h>
#include<conio.h>
void main(){
	int n,rev=0;
	printf("\nPlease enter the number\n");
	scanf("%d",&n);
	while(n!=0){
		rev=rev*10;
		rev=rev+n%10;
		n=n/10;
	}
	printf("Reversed number is %d",rev);
getch();
}

7. Wap to swap two number.

#include<stdio.h>
#include<conio.h>
void main(){
	int a,b,temp;
	printf("Enter the first no.\n");
	scanf("%d",&a);
	printf("Enter the second no.\n");
	scanf("%d",&b);
	printf("\n Before swapping the values are %d %d",a,b);
	temp=a;
	a=b;
	b=temp;
	printf("\n After swapping the values are %d %d",a,b);
	getch();
}

8. Wap to swap two number without using third variable.

#include<stdio.h>
#include<conio.h>
void main(){
	int a,b;
	printf("\n Enter the first number");
	scanf("%d",&a);
	printf("\n Enter the second number");
	scanf("%d",&b);
	printf("\n Before swap the values are %d %d",a,b);
	a=a+b;
	b=a-b;
	a=a-b;
	printf("\n After the swap the values are %d %d",a,b);
	getch();
}

9. Wap to convert decimal to binary.

#include <stdio.h>
#include<math.h>
int main(void) {
	// your code goes here
	int i=0,a,b=0,no;
	printf("Enter the number : ");
	scanf("%d",&no);
	while(no>0)
	{
		a = no%2;
		no = no/2;
		b = b + a*pow(10,i);
		i++;
	}
	printf("%d",b);
	return 0;
}

10. Wap to convert decimal to octal.

#include <stdio.h>
int main(void) {
	int a,no,b=0,i=0;
	printf("Enter a number : ");
	scanf("%d",&no);
	while(no>0)
	{
		a = no%8;
		no = no/8;
		b = b + a*pow(10,i);
		i++;
	}
	printf("%d",b);
	return 0;
}

11. Wap to find divisors  of a given number.

#include <stdio.h>
int main(void) {
	// your code goes here
	int a,i;
	printf("Enter the number whose divisor we have to find : ");
	scanf("%d",&a);
	printf("\n");
	printf("Divisor of %d are : ",a);
	for(i=1;i<=a;i++){
		if(a % i ==0){
			printf("%d",i);
			printf(" ");
		}
	}
	return 0;
}

12. Wap to find factorial of a given number.

#include <stdio.h>
int main(void) {
	// your code goes here
	int a,i,b,fac=1;
	printf("Enter the number whose factorial we have to find : ");
	scanf("%d",&a);
	printf("\n");
	printf("Factorial of %d is : ",a);
	for(i=a;i>=1;i--){
		fac = fac * i;
	}
	printf("%d",fac);
	return 0;
}

13. Wap to check if given year is leap year or not.

#include <stdio.h>
int main(void) {
	int a;
	printf("Enter year to be checked");
	scanf("%d",&a);
	printf("\n");
	if(a % 4 == 0){
		if(a % 100 == 0){
			if(a % 400 == 0){
				printf("%d is a leap year",a);
			}
			else{
				printf("%d is not a leap year",a);
			}
		}
		else{
				printf("%d is a leap year",a);
		}
	}
	else{
		printf("%d is not a leap year",a);
	}
	return 0;
}

14. Wap to check if given number is odd or even.

#include <stdio.h>
int main(void) {
	int a;
	// your code goes here
	printf("Enter number which is to be checked");
	scanf("%d",&a);
	printf("\n");
	if(a % 2 == 0){
		printf("%d is even number",a);
	}
	else{
		printf("%d is odd number",a);
	}
	return 0;
}

15. Wap to find Quotient remainder.

#include <stdio.h>
int main(void) {
	int a,b,c,d;
	printf("Enter the Dividend : ");
	scanf("%d",&a);
	printf("\n");
	printf("Enter the Divisor : ");
	scanf("%d",&b);
	printf("\n");
	c = a/b;
	d = a%b;
	printf("Quotient is : %d",c);
	printf("\n");
	printf("Remainder is : %d",d);
	return 0;
}

16. Wap to check if given string is anagram or not.

#include<stdio.h>
#include <stdbool.h>
#include <string.h>
/* Must have matching character counts , position may not match
*  This is same as str2 is one of the permutation of
   str1, e.g str1= cat, str2=act, or tac or tca, or cta */
bool anagram (char *str1, char *str2) {
    int A[256];
    int i = 256;
    /* Logic
       count each char in string1 using CHAR hash/array
       decrement for each char in string2 using same CHAR hash/array
       If char count is less than zero, indicating that there was no matching char
       in previous string, so return false
       At the end return TRUE.
    */
    if( str1 == NULL || str2 == NULL){
        printf("Invalid Input strings \n");
        return false;
    }
    if ( *str1 == 0 || *str2 == 0){
        printf("Empty Input strings \n");
        return false;
    }
    printf("%ld %ld\n",strlen(str1),strlen(str2));
    //Initialize array to zero val
    for(i=0; i < 256; i++) {
        A[i] = 0;
    }
    //Loop until NULL char
    while (*str1) {
        A[*str1]++;
        printf("%d ",*str1);
        ++str1;
    }
    printf("\n");
    //Loop until NULL char
    while (*str2) {
        printf("%d ",*str2);
        A[*str2]--;
        if(A[*str2] < 0)
            return false;
        ++str2;
    }
    return true;
}
int main(int argc, char *argv[])
{
    char str1[256];
    char str2[256];
    printf("Enter String1 for Anagram Test:");
    gets(str1);
    printf("Enter String2 for Anagram Test:");
    gets(str2);
    printf("Input %s and %s \n",str1,str2 );
    printf("%s and %s are %s anagram",str1,str2, anagram(str1,str2) ? " ":"NOT");
}

17. Wap to multiply two floating numbers.

#include <stdio.h>
int main()
{
    double firstNumber, secondNumber, product;
    printf("Enter two numbers: ");
    scanf("%lf %lf", &firstNumber, &secondNumber);
    // Performs multiplication and stores the result in variable productOfTwoNumbers
    product = firstNumber * secondNumber;
    // Result up to 2 decimal point is displayed using %.2lf
    printf("Product = %.2lf", product);
    return 0;
}
Output
Enter two numbers: 5.2
2.3
Product = 7.5

18. Wap to get ASCII value of a given character.

include <stdio.h>
int main()
{
    char c;
    printf("Enter a character: ");
    scanf("%c", &c);
    // %d displays the integer value of a character
    // %c displays the actual character
    printf("ASCII value of %c = %d", c, c);
    return 0;
}
Output
Enter a character: K
ASCII value of K = 107

19. Wap to find the size of datatypes.

#include <stdio.h>
int main()
{
    int integerType;
    float floatType;
    double doubleType;
    char charType;
    printf("Size of int: %ld bytes\n",sizeof(integerType));
    printf("Size of float: %ld bytes\n",sizeof(floatType));
    printf("Size of double: %ld bytes\n",sizeof(doubleType));
    printf("Size of char: %ld byte\n",sizeof(charType));
    return 0;
}
Output
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte

20. Wap to check if given character is vowel or consonant.

#include <stdio.h>
int main()
{
    char c;
    int isLowercaseVowel, isUppercaseVowel;
    printf("Enter an alphabet: ");
    scanf("%c",&c);
    // this will check for the lower case vowels.
    isLowercaseVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
    // this will check for the upper case vowels.
    isUppercaseVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
    if (isLowercaseVowel || isUppercaseVowel)
        printf("%c is a vowel.", c);
    else
        printf("%c is a consonant.", c);
    return 0;
}
Output
Enter an alphabet: I
I is a vowel.

21. Wap to find largest number from given three number.
This program can be solved in three ways:

  1. By using only if
    #include <stdio.h>
    int main()
    {
        double n1, n2, n3;
        printf("Enter three different numbers: ");
        scanf("%lf %lf %lf", &n1, &n2, &n3);
        if( n1>=n2 && n1>=n3 )
            printf("%.2f is the largest number.", n1);
        if( n2>=n1 && n2>=n3 )
            printf("%.2f is the largest number.", n2);
        if( n3>=n1 && n3>=n2 )
            printf("%.2f is the largest number.", n3);
        return 0;
    }

    2. By using if-else

    #include <stdio.h>
    int main()
    {
        double n1, n2, n3;
        printf("Enter three numbers: ");
        scanf("%lf %lf %lf", &n1, &n2, &n3);
        if (n1>=n2)
        {
            if(n1>=n3)
                printf("%.2lf is the largest number.", n1);
            else
                printf("%.2lf is the largest number.", n3);
        }
        else
        {
            if(n2>=n3)
                printf("%.2lf is the largest number.", n2);
            else
                printf("%.2lf is the largest number.",n3);
        }
        return 0;
    }

    3. By using nested if-else

    #include <stdio.h>
    int main()
    {
        double n1, n2, n3;
        printf("Enter three numbers: ");
        scanf("%lf %lf %lf", &n1, &n2, &n3);
        if( n1>=n2 && n1>=n3)
            printf("%.2lf is the largest number.", n1);
        else if (n2>=n1 && n2>=n3)
            printf("%.2lf is the largest number.", n2);
        else
            printf("%.2lf is the largest number.", n3);
        return 0;
    }

     

22. Wap to check if given number is postive or negative number.

#include <stdio.h>
int main()
{
    double number;
    printf("Enter a number: ");
    scanf("%lf", &number);
    if (number <= 0.0)
    {
        if (number == 0.0)
            printf("You entered 0.");
        else
            printf("You entered a negative number.");
    }
    else
        printf("You entered a positive number.");
    return 0;
}

23. Wap to check if given character is alphabet or not.

#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

24. Wap to get sum of Natural number.

#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;   // sum = sum+i;
    }
    printf("Sum = %d",sum);
    return 0;
}

25. Wap to generate a table of given number.

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

26.  Wap to find Greatest Common Divisor (GCD) of given two numbers.

#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)
    {
        // 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;
}

27. Wap to find Lowest Common Multiple(LCM) of given two numbers.

#include <stdio.h>
int main()
{
    int n1, n2, minMultiple;
    printf("Enter two positive integers: ");
    scanf("%d %d", &n1, &n2);
    // maximum number between n1 and n2 is stored in minMultiple
    minMultiple = (n1>n2) ? n1 : n2;
    // Always true
    while(1)
    {
        if( minMultiple%n1==0 && minMultiple%n2==0 )
        {
            printf("The LCM of %d and %d is %d.", n1, n2,minMultiple);
            break;
        }
        ++minMultiple;
    }
    return 0;
}

28. Wap to count number of digits in an integer.

#include <stdio.h>
int main()
{
    long long n;
    int count = 0;
    printf("Enter an integer: ");
    scanf("%lld", &n);
    while(n != 0)
    {
        // n = n/10
        n /= 10;
        ++count;
    }
    printf("Number of digits: %d", count);
}
Output
Enter an integer: 12465
Number of digits: 5

29. Wap to calculate the power of a number.

#include <stdio.h>
int main()
{
    int base, exponent;
    long long 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;
}

30. Wap to generate Prime Numbers between two numbers.

#include <stdio.h>
int checkPrimeNumber(int n);
int main()
{
    int n1, n2, i, flag;
    printf("Enter two positive integers: ");
    scanf("%d %d", &n1, &n2);
    printf("Prime numbers between %d and %d are: ", n1, n2);
    for(i=n1+1; i<n2; ++i)
    {
        // i is a prime number, flag will be equal to 1
        flag = checkPrimeNumber(i);
        if(flag == 1)
            printf("%d ",i);
    }
    return 0;
}
// user-defined function to check prime number
int checkPrimeNumber(int n)
{
    int j, flag = 1;
    for(j=2; j <= n/2; ++j)
    {
        if (n%j == 0)
        {
            flag =0;
            break;
        }
    }
    return flag;
}

31. Wap to print Hello World without using any semicolon.

void main(){
    if(printf("Hello world")){
    }
}
OR
void main(){
    while(!printf("Hello world")){
    }
}
OR
void main(){
    switch(printf("Hello world")){
    }
}

32. Wap to convert uppercase character to lowercase.

#include<stdio.h>
#include<string.h>
int main(){
  char str[20];
  int i;
  printf("Enter any string->");
  scanf("%s",str);
  printf("The string is->%s",str);
  for(i=0;i<=strlen(str);i++){
      if(str[i]>=65&&str[i]<=90)
       str[i]=str[i]+32;
  }
  printf("\nThe string in lower case is->%s",str);
  return 0;
}

33. Wap to convert lowecase character to uppercase.

#include<stdio.h>
int main(){
  char str[20];
  int i;
  printf("Enter any string->");
  scanf("%s",str);
  printf("The string is->%s",str);
  for(i=0;i<=strlen(str);i++){
            if(str[i]>=97&&str[i]<=122)
            str[i]=str[i]-32;
  }
  printf("\nThe string in lowercase is->%s",str);
  return 0;
}

34. Wap to print initial of  any given name.

#include<stdio.h>
int main(){
   char str[20];
   int i=0;
   printf("Enter a string: ");
   gets(str);
   printf("%c",*str);
   while(str[i]!='\0'){
       if(str[i]==' '){
            i++;
            printf("%c",*(str+i));
       }
       i++;
   }
   return 0;
}
Output:
Enter a string: Mahendra Singh Dhoni
MSD

35. Wap to check if given string palindrome or not.

#include<string.h>
#include<stdio.h>
int main(){
  char *str,*rev;
  int i,j;
  printf("\nEnter a string:");
  scanf("%s",str);
  for(i=strlen(str)-1,j=0;i>=0;i--,j++)
      rev[j]=str[i];
      rev[j]='\0';
  if(strcmp(rev,str))
      printf("\nThe string is not a palindrome");
  else
      printf("\nThe string is a palindrome");
  return 0;
}

36. Wap to sort given string.

#include<stdio.h>
int main(){
  int i,j,n;
  char str[20][20],temp[20];
  puts("Enter the no. of string to be sorted");
  scanf("%d",&n);
  for(i=0;i<=n;i++)
      gets(str[i]);
  for(i=0;i<=n;i++)
      for(j=i+1;j<=n;j++){
           if(strcmp(str[i],str[j])>0){
               strcpy(temp,str[i]);
              strcpy(str[i],str[j]);
              strcpy(str[j],temp);
           }
      }
  printf("The sorted string\n");
  for(i=0;i<=n;i++)
      puts(str[i]);
  return 0;
}

37. Wap to copy string without using any string methods.

#include<stdio.h>
void stringCopy(char[],char[]);
int main(){
    char str1[100],str2[100];
    printf("Enter any string: ");
    scanf("%s",str1);
    stringCopy(str1,str2);
    printf("After copying: %s",str2);
    return 0;
}
void stringCopy(char str1[],char str2[]){
    int i=0;
    while(str1[i]!='\0'){
         str2[i] = str1[i];
         i++;
    }
    str2[i]='\0';
}
Sample output:
Enter any string: training.kodnest.com
After copying: training.kodnest.com

38. Wap to  combine two string using pointer.

include<stdio.h>
int main(){
  int i=0,j=0;
  char *str1,*str2,*str3;
  puts("Enter first string");
  gets(str1);
  puts("Enter second string");
  gets(str2);
  printf("Before concatenation the strings are\n");
  puts(str1);
  puts(str2);
  while(*str1){
      str3[i++]=*str1++;
  }
  while(*str2){
      str3[i++]=*str2++;
  }
  str3[i]='\0';
  printf("After concatenation the strings are\n");
  puts(str3);
  return 0;
}

39. Wap to convert string into ASCII Value.

#include<stdio.h>
int main(){
    char str[100];
    int i=0;
    printf("Enter any string: ");
    scanf("%s",str);
    printf("ASCII values of each characters of given string: ");
    while(str[i])
         printf("%d ",str[i++]);
    return 0;
}

40. Wap to find length of string.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum size of the string
int main()
{
    char text[MAX_SIZE]; /* Declares a string of size 100 */
    int i;
    int count= 0;
    /* Input a string from user */
    printf("Enter any string: ");
    gets(text);
    /* Iterate till the last character of string */
    for(i=0; text[i]!='\0'; i++)
    {
        count++;
    }
    printf("Length of '%s' = %d", text, count);
    return 0;
}

41. Wap to compare given two strings.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
/* Compare function declaration */
int compare(char * str1, char * str2);
int main()
{
    char str1[MAX_SIZE], str2[MAX_SIZE];
    int res;
    /* Input two strings from user */
    printf("Enter first string: ");
    gets(str1);
    printf("Enter second string: ");
    gets(str2);
    /* Call the compare function to compare strings */
    res = compare(str1, str2);
    if(res == 0)
    {
        printf("Both strings are equal.");
    }
    else if(res < 0)
    {
        printf("First string is lexicographically smaller than second.");
    }
    else
    {
        printf("First string is lexicographically greater than second.");
    }
    return 0;
}
/**
 * Compares two strings lexicographically.
 * Returns 0 if both strings are equal,
 *         negative if first string is smaller
 *         otherwise returns a positive value
 */
int compare(char * str1, char * str2)
{
    int i = 0;
    /* Iterate till both strings are equal */
    while(str1[i] == str2[i])
    {
        if(str1[i] == '\0' && str2[i] == '\0')
            break;
        i++;
    }
    // Return the difference of current characters.
    return str1[i] - str2[i];
}

42. Wap to count the number of alphabets, digits  and special character in a given string.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
    char str[MAX_SIZE];
    int alphabets, digits, others, i;
    alphabets = digits = others = i = 0;
    /* Input string from user */
    printf("Enter any string : ");
    gets(str);
    /*
     * Check each character of string for alphabet, digit or special character
     */
    while(str[i]!='\0')
    {
        if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
        {
            alphabets++;
        }
        else if(str[i]>='0' && str[i]<='9')
        {
            digits++;
        }
        else
        {
            others++;
        }
        i++;
    }
    printf("Alphabets = %d\n", alphabets);
    printf("Digits = %d\n", digits);
    printf("Special characters = %d", others);
    return 0;
}

43. Wap to check whether given string is palindrome or not.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
    char str[MAX_SIZE];
    int len, startIndex, endIndex;
    /* Input string from user */
    printf("Enter any string: ");
    gets(str);
    /* Find length of the string */
    len = 0;
    while(str[len] != '\0') len++;
    startIndex = 0;
    endIndex   = len-1;
    while(startIndex <= endIndex)
    {
        if(str[startIndex] != str[endIndex])
            break;
        startIndex++;
        endIndex--;
    }
    if(startIndex >= endIndex)
    {
        printf("String is Palindrome.");
    }
    else
    {
        printf("String is Not Palindrome.");
    }
    return 0;
}

44. Wap to find first occurrence of given character in a string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declaration */
int indexOf(const char * str, const char toFind);
int main()
{
    char str[MAX_SIZE];
    char toFind;
    int index;
    /* Input string from user and character to be searched */
    printf("Enter any string: ");
    gets(str);
    printf("Enter character to be searched: ");
    toFind = getchar();
    index = indexOf(str, toFind);
    if(index == -1)
        printf("'%c' not found.", toFind);
    else
        printf("'%c' is found at index %d.", toFind, index);
    return 0;
}
/**
 * Returns the first index of the given character toFind in the string.
 * If returns -1 if the given character toFind does not exists in the string.
 */
int indexOf(const char * str, const char toFind)
{
    int i = 0;
    while(str[i] != '\0')
    {
        if(str[i] == toFind)
            return i;
        i++;
    }
    // Return -1 as character not found
    return -1;
}
Example
Input
Input string: I love India.
Input character to search: o
Output
'o' is found at index 3

45. Wap to find last occurrence of given character in a string.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
/*  Function declaration */
int lastIndexOf(const char * str, const char toFind);
int main()
{
    char str[MAX_SIZE];
    char toFind;
    int index;
    printf("Enter any string: ");
    gets(str);
    printf("Enter any character to find: ");
    toFind = getchar();
    index = lastIndexOf(str, toFind);
    printf("\nLast index of '%c' is %d", toFind, index);
    return 0;
}
/**
 * Function to find last index of any character in the given string
 */
int lastIndexOf(const char * str, const char toFind)
{
    int index = -1;
    int i = 0;
    while(str[i] != '\0')
    {
        // Update index if match is found
        if(str[i] == toFind)
        {
            index = i;
        }
        i++;
    }
    return index;
}
Input
Input string: I love India.
Input character to search: i
Output
Last index of 'i' is 8.

46. Wap to find all occurrence of a given character in a string.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
    char str[MAX_SIZE];
    char toSearch;
    int i;
    /* Input string and character to search from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter any character to search: ");
    toSearch = getchar();
    /* Run loop till the last character of string */
    i=0;
    while(str[i]!='\0')
    {
        /* If character is found in string */
        if(str[i] == toSearch)
        {
            printf("'%c' is found at index %d\n", toSearch, i);
        }
        i++;
    }
    return 0;
}
Example
Input
Input string: I love programming.
Input character to search: o
Output
'o' found at index: 3, 9.

47. Wap to count the occurrence of a given character in a string.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
    char str[MAX_SIZE];
    char toSearch;
    int i, count;
    /* Input string and search character from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter any character to search: ");
    toSearch = getchar();
    count = 0;
    i=0;
    while(str[i] != '\0')
    {
        /*
         * If character is found in string then
         * increment count variable
         */
        if(str[i] == toSearch)
        {
            count++;
        }
        i++;
    }
    printf("Total occurrence of '%c' = %d", toSearch, count);
    return 0;
}
Example
Input
Input string: I love programming.
Input character to search: o
Output
Total occurrences of 'o': 2

48. Wap to find topmost repeated character in a string.

#include <stdio.h>
#define MAX_SIZE 100  // Maximum string size
#define MAX_CHARS 255 // Maximum characters allowed
int main()
{
    char str[MAX_SIZE];
    int freq[MAX_CHARS]; // Store frequency of each character
    int i = 0, max;
    int ascii;
    printf("Enter any string: ");
    gets(str);
    /* Initializes frequency of all characters to 0 */
    for(i=0; i<MAX_CHARS; i++)
    {
        freq[i] = 0;
    }
    /* Finds frequency of each characters */
    i=0;
    while(str[i] != '\0')
    {
        ascii = (int)str[i];
        freq[ascii] += 1;
        i++;
    }
    /* Finds maximum frequency */
    max = 0;
    for(i=0; i<MAX_CHARS; i++)
    {
        if(freq[i] > freq[max])
            max = i;
    }
    printf("Maximum occurring character is '%c' = %d times.", max, freq[max]);
    return 0;
}
Input
Input string: I love my India.
Output
Maximum occurring character: 'I'

49. Wap to find lowest repeated character in a string.

#include <stdio.h>
#define MAX_SIZE 100  // Maximum string size
#define MAX_CHARS 255 // Maximum characters allowed
int main()
{
    char str[MAX_SIZE];
    int freq[MAX_CHARS]; //Stores frequency of each character
    int i = 0, min;
    int ascii;
    printf("Enter any string: ");
    gets(str);
    /* Initialize frequency of all characters to 0 */
    for(i=0; i<MAX_CHARS; i++)
    {
        freq[i] = 0;
    }
    /* Finds frequency of each characters */
    i=0;
    while(str[i] != '\0')
    {
        ascii = (int)str[i];
        freq[ascii] += 1;
        i++;
    }
    /* Finds minimum frequency */
    min = 0;
    for(i=0; i<MAX_CHARS; i++)
    {
        if(freq[i] != 0)
        {
            if(freq[min] == 0 || freq[i] < freq[min])
                min = i;
        }
    }
    printf("Minimum occurring character is '%c' = %d.", min, freq[min]);
    return 0;
}
Example
Input
Input string: I love learning programming.
Minimum occurring character is '.' = 1

50. Wap to find a count of each character in a given string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
    char str[MAX_SIZE];
    int i, len;
    int freq[26];
    /* Input string from user */
    printf("Enter any string: ");
    gets(str);
    len = strlen(str);
    /* Initialize frequency of each character to 0 */
    for(i=0; i<26; i++)
    {
        freq[i] = 0;
    }
    /* Find total number of occurrences of each character */
    for(i=0; i<len; i++)
    {
        /* If the current character is lowercase alphabet */
        if(str[i]>='a' && str[i]<='z')
        {
            freq[str[i] - 97]++;
        }
        else if(str[i]>='A' && str[i]<='Z')
        {
            freq[str[i] - 65]++;
        }
    }
    /* Print the frequency of all characters in the string */
    printf("\nFrequency of all characters in the given string: \n");
    for(i=0; i<26; i++)
    {
        /* If current character exists in given string */
        if(freq[i] != 0)
        {
            printf("'%c' = %d\n", (i + 97), freq[i]);
        }
    }
    return 0;
}

51. Wap to delete first occurrence of a given character in a string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declaration */
void removeFirst(char *, const char);
int main()
{
    char str[MAX_SIZE];
    char toRemove;
    printf("Enter any string: ");
    gets(str);
    printf("Enter character to remove from string: ");
    toRemove = getchar();
    removeFirst(str, toRemove);
    printf("String after removing first '%c' : %s", toRemove, str);
    return 0;
}
/**
 * Function to remove first occurrence of a character from the string.
 */
void removeFirst(char * str, const char toRemove)
{
    int i = 0;
    int len = strlen(str);
    /* Run loop till the first occurrence of the character is not found */
    while(i<len && str[i]!=toRemove)
        i++;
    /* Shift all characters right to the position found above, to one place left */
    while(i < len)
    {
        str[i] = str[i+1];
        i++;
    }
}

52. Wap to delete last occurrence of a given character in a string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declaration */
void removeLast(char *, const char);
int main()
{
    char str[MAX_SIZE];
    char toRemove;
    printf("Enter any string: ");
    gets(str);
    printf("Enter character to remove from string: ");
    toRemove = getchar();
    removeLast(str, toRemove);
    printf("String after removing last '%c' : %s", toRemove, str);
    return 0;
}
/**
 * Function to remove last occurrence of a character from the string.
 */
void removeLast(char * str, const char toRemove)
{
    int i, lastPosition;
    int len = strlen(str);
    /* Assume that character does not exist in string */
    lastPosition = -1;
    i=0;
    while(i<len)
    {
        if(str[i] == toRemove)
        {
            lastPosition = i;
        }
        i++;
    }
    /* If character exists in string */
    if(lastPosition != -1)
    {
        i = lastPosition;
        /*
         * Shift all characters right to the position found above to left
         */
        while(i<len)
        {
            str[i] = str[i+1];
            i++;
        }
    }
}

53. Wap to delete all occurrence of a given character in a string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
/** Function declaration */
void removeAll(char *, const char);
int main()
{
    char str[MAX_SIZE];
    char toRemove;
    printf("Enter any string: ");
    gets(str);
    printf("Enter character to remove from string: ");
    toRemove = getchar();
    removeAll(str, toRemove);
    printf("String after removing '%c': %s", toRemove, str);
    return 0;
}
/**
 * Function to remove all occurrences of a character from the string.
 */
void removeAll(char * str, const char toRemove)
{
    int i, j;
    int len = strlen(str);
    for(i=0; i<len; i++)
    {
        /*
         * If the character to remove is found then shift all characters to one
         * place left and decrement the length of string by 1.
         */
        if(str[i] == toRemove)
        {
            for(j=i; j<len; j++)
            {
                str[j] = str[j+1];
            }
            len--;
            // If a character is removed then make sure i doesn't increments
            i--;
        }
    }
}

54. Wap to delete all repeated character in a string.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declarations */
void removeDuplicates(char * str);
void removeAll(char * str, const char toRemove, int index);
int main()
{
    char str[MAX_SIZE];
    /* Input string from user */
    printf("Enter any string: ");
    gets(str);
    printf("String before removing duplicates: %s\n", str);
    removeDuplicates(str);
    printf("String after removing duplicates: %s\n", str);
    return 0;
}
/**
 * Remove all duplicate characters from the given string
 */
void removeDuplicates(char * str)
{
    int i = 0;
    while(str[i] != '\0')
    {
        /* Remove all duplicate of character string[i] */
        removeAll(str, str[i], i + 1);
        i++;
    }
}
/**
 * Remove all occurrences of a given character from string.
 */
void removeAll(char * str, const char toRemove, int index)
{
    int i;
    while(str[index] != '\0')
    {
        /* If duplicate character is found */
        if(str[index] == toRemove)
        {
            /* Shift all characters from current position to one place left */
            i = index;
            while(str[i] != '\0')
            {
                str[i] = str[i + 1];
                i++;
            }
        }
        else
        {
            index++;
        }
    }
}

55. Wap to change first occurrence of given character with another in a string.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declaration */
void replaceFirst(char * str, char oldChar, char newChar);
int main()
{
    char str[MAX_SIZE], oldChar, newChar;
    printf("Enter any string: ");
    gets(str);
    printf("Enter character to replace: ");
    oldChar = getchar();
    // Used to skip extra ENTER character
    getchar();
    printf("Enter character to replace '%c' with: ", oldChar);
    newChar = getchar();
    printf("\nString before replacing: %s\n", str);
    replaceFirst(str, oldChar, newChar);
    printf("String after replacing first '%c' with '%c' : %s", oldChar, newChar, str);
    return 0;
}
/**
 * Replace first occurrence of a character with
 * another in given string.
 */
void replaceFirst(char * str, char oldChar, char newChar)
{
    int i=0;
    /* Run till end of string */
    while(str[i] != '\0')
    {
        /* If an occurrence of character is found */
        if(str[i] == oldChar)
        {
            str[i] = newChar;
            break;
        }
        i++;
    }
}
Input
Input string: I love programming.
Input character to replace: .
Input character to replace with: ^
Output
String after replacing '.' with '^': I love programming^

56. Wap to change last occurance of  a given character with another in a string.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declaration */
void replaceLast(char * str, char oldChar, char newChar);
int main()
{
    char str[MAX_SIZE], oldChar, newChar;
    printf("Enter any string: ");
    gets(str);
    printf("Enter character to replace: ");
    oldChar = getchar();
    // Dummy getchar() to eliminate extra ENTER character
    getchar();
    printf("Enter character to replace '%c' with: ", oldChar);
    newChar = getchar();
    printf("\nString before replacing: \n%s", str);
    replaceLast(str, oldChar, newChar);
    printf("\n\nString after replacing '%c' with '%c': \n%s", oldChar, newChar, str);
    return 0;
}
/**
 * Replace last occurrence of a character with
 * another in given string.
 */
void replaceLast(char * str, char oldChar, char newChar)
{
    int i, lastIndex;
    lastIndex = -1;
    i = 0;
    /* Run till end of string */
    while(str[i] != '\0')
    {
        /* If an occurrence of character is found */
        if(str[i] == oldChar)
        {
            lastIndex = i;
        }
        i++;
    }
    if(lastIndex != -1)
    {
        str[lastIndex] = newChar;
    }
}
Example
Input
Input string: Do you love programming.
Input character to replace: .
Input character to replace with: !
Output
String after replacing last '.' with '!' : Do you love programming!

57. Wap to replace all occurrences of  a given string with another in a string.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declaration */
void replaceAll(char * str, char oldChar, char newChar);
int main()
{
    char str[MAX_SIZE], oldChar, newChar;
    printf("Enter any string: ");
    gets(str);
    printf("Enter character to replace: ");
    oldChar = getchar();
    // Dummy getchar() to eliminate extra ENTER character
    getchar();
    printf("Enter character to replace '%c' with: ", oldChar);
    newChar = getchar();
    printf("\nString before replacing: \n%s", str);
    replaceAll(str, oldChar, newChar);
    printf("\n\nString after replacing '%c' with '%c' : \n%s", oldChar, newChar, str);
    return 0;
}
/**
 * Replace all occurrence of a character in given string.
 */
void replaceAll(char * str, char oldChar, char newChar)
{
    int i = 0;
    /* Run till end of string */
    while(str[i] != '\0')
    {
        /* If occurrence of character is found */
        if(str[i] == oldChar)
        {
            str[i] = newChar;
        }
        i++;
    }
}
Example
Input
Input string: I_love_learning.
Input character to replace: _
Input character to replace with: -
Output
String after replacing '_' with '-': I-love-learning.

58. Wap to find first occurrence of a given word in a string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
    char str[MAX_SIZE], word[MAX_SIZE];
    int i, index, found = 0;
    /* Input string and word from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter word to be searched: ");
    gets(word);
    /* Run loop from start to end of string */
    index = 0;
    while(str[index] != '\0')
    {
        /* If first character of word matches with the given string */
        if(str[index] == word[0])
        {
            /* Match entire word with current found index */
            i=0;
            found = 1;
            while(word[i] != '\0')
            {
                if(str[index + i] != word[i])
                {
                    found = 0;
                    break;
                }
                i++;
            }
        }
        /* If the word is found then get out of loop */
        if(found == 1)
        {
            break;
        }
        index++;
    }
    /*  Print success message if the word is found */
    if(found == 1)
    {
        printf("\n'%s' is found at index %d.", word, index);
    }
    else
    {
        printf("\n'%s' is not found.", word);
    }
    return 0;
}
Example
Input
Input string: I love programming!
Input word to search: love
Output
'love' is found at index 2.

59. Wap to find last occurrence of a given word in a string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
    char str[MAX_SIZE];
    char word[MAX_SIZE];
    int i, j, index, found;
    int strLen, wordLen;
    /* Input string and word from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter any word to search: ");
    gets(word);
    index = -1;
    strLen  = strlen(str);   // Find length of string
    wordLen = strlen(word);  // Find length of word
    /*
     * Runs a loop from starting index of string to
     * length of string - word length
     */
    for(i=0; i<=strLen - wordLen; i++)
    {
        // Match word at current position
        found = 1;
        for(j=0; j<wordLen; j++)
        {
            //If word is not matched
            if(str[i + j] != word[j])
            {
                found = 0;
                break;
            }
        }
        // If word have been found then store the current found index
        if(found == 1)
        {
            index = i;
        }
    }
    if(index == -1)
    {
        printf("\n'%s' not found.", word);
    }
    else
    {
        printf("\nLast index of '%s' = %d", word, index);
    }
    return 0;
}
Example
Input
Input string: I love programming. I love PHP.
Input word: love
Output
'love' is found at index: 22

60. Wap to find all occurrence of a given word in a string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
    char str[MAX_SIZE];
    char word[MAX_SIZE];
    int i, j, found;
    int strLen, wordLen;
    /* Input string and word from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter any word to search: ");
    gets(word);
    strLen  = strlen(str);  // Find length of string
    wordLen = strlen(word); // Find length of word
    /*
     * Run a loop from starting index of string to
     * length of string - word length
     */
    for(i=0; i<strLen - wordLen; i++)
    {
        // Match word at current position
        found = 1;
        for(j=0; j<wordLen; j++)
        {
            // If word is not matched
            if(str[i + j] != word[j])
            {
                found = 0;
                break;
            }
        }
        // If word have been found then print found message
        if(found == 1)
        {
            printf("'%s' found at index: %d \n", word, i);
        }
    }
    return 0;
}
Example
Input
Input string: I love programming. I love PHP.
Input word to search: love
Output
'love' is found at index: 2
'love' is found at index: 22

61. Wap to count number of occurrence of a given word in a string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declaration */
int countOccurrences(char * str, char * toSearch);
int main()
{
    char str[MAX_SIZE];
    char toSearch[MAX_SIZE];
    int count;
    /* Input string and word from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter word to search occurrences: ");
    gets(toSearch);
    count = countOccurrences(str, toSearch);
    printf("Total occurrences of '%s': %d", toSearch, count);
    return 0;
}
/**
 * Get, total number of occurrences of a word in a string
 */
int countOccurrences(char * str, char * toSearch)
{
    int i, j, found, count;
    int stringLen, searchLen;
    stringLen = strlen(str);      // length of string
    searchLen = strlen(toSearch); // length of word to be searched
    count = 0;
    for(i=0; i <= stringLen-searchLen; i++)
    {
        /* Match word with string */
        found = 1;
        for(j=0; j<searchLen; j++)
        {
            if(str[i + j] != toSearch[j])
            {
                found = 0;
                break;
            }
        }
        if(found == 1)
        {
            count++;
        }
    }
    return count;
}
Example
Input
Input string: I love programming. I love PHP.
Input word to search: love
Output
Total occurrences of 'love': 2

62. Wap to delete first occurrence of a given word in a string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
/** Function declaration */
void removeFirst(char * str, const char * toRemove);
int main()
{
    char str[MAX_SIZE];
    char toRemove[MAX_SIZE];
    /* Input string and word to be removed from user  */
    printf("Enter any string: ");
    gets(str);
    printf("Enter string to be removed: ");
    gets(toRemove);
    removeFirst(str, toRemove);
    printf("\nString after removing '%s': \n%s", toRemove, str);
    return 0;
}
/**
 * Remove first occurrence of a word from string
 */
void removeFirst(char * str, const char * toRemove)
{
    int i, j;
    int len, removeLen;
    int found = 0;
    len = strlen(str);
    removeLen = strlen(toRemove);
    for(i=0; i<len; i++)
    {
        found = 1;
        for(j=0; j<removeLen; j++)
        {
            if(str[i+j] != toRemove[j])
            {
                found = 0;
                break;
            }
        }
        /* If word has been found then remove it by shifting characters  */
        if(found == 1)
        {
            for(j=i; j<=len-removeLen; j++)
            {
                str[j] = str[j + removeLen];
            }
            // Terminate from loop so only first occurrence is removed
            break;
        }
    }
}
nput
Input string : Learn programming at Kodnest.
Input word to remove : Learn
Output
String after removing 'Learn':
programming at Kodnest.

63. Wap to delete last occurrence of a given word in a string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
    char str[MAX_SIZE];
    char word[MAX_SIZE];
    int i, j, found, index;
    int stringLen, wordLen;
    /* Input string and word from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter word to remove: ");
    gets(word);
    stringLen = strlen(str);  // Length of string
    wordLen   = strlen(word); // Length of word
    /*
     * Run loop from start to end of string - word length
     */
    index = -1;
    for(i=0; i<stringLen - wordLen; i++)
    {
        // Match word at current position
        found = 1;
        for(j=0; j<wordLen; j++)
        {
            // If word is not matched
            if(str[i+j] != word[j])
            {
                found = 0;
                break;
            }
        }
        // If word is found then update index
        if(found == 1)
        {
            index = i;
        }
    }
    // If word not found
    if(index == -1)
    {
        printf("'%s' not found.");
    }
    else
    {
        /*
         * Shift all characters from right to left
         */
        for(i=index; i <= stringLen - wordLen; i++)
        {
            str[i] = str[i + wordLen];
        }
        printf("String after removing last '%s': \n%s", word, str);
    }
    return 0;
}
Example
Input
Input string: I am a programmer. I learn at Kodnest.
Input word to remove: I
Output
String after removing last occurrence of 'I':
I am a programmer.  learn at Kodnest.

64. Wap to remove all occurrence of a given word in a string.

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declaration */
void removeAll(char * str, char * toRemove);
int main()
{
    char str[MAX_SIZE];
    char toRemove[MAX_SIZE];
    /* Input string and word from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter word to remove: ");
    gets(toRemove);
    printf("String before removing '%s' : \n%s", toRemove, str);
    removeAll(str, toRemove);
    printf("\n\nString after removing '%s' : \n%s", toRemove, str);
    return 0;
}
/**
 * Remove all occurrences of a given word in string.
 */
void removeAll(char * str, char * toRemove)
{
    int i, j, stringLen, toRemoveLen;
    int found;
    stringLen   = strlen(str);      // Length of string
    toRemoveLen = strlen(toRemove); // Length of word to remove
    for(i=0; i <= stringLen - toRemoveLen; i++)
    {
        /* Match word with string */
        found = 1;
        for(j=0; j<toRemoveLen; j++)
        {
            if(str[i + j] != toRemove[j])
            {
                found = 0;
                break;
            }
        }
        /* If it is not a word */
        if(str[i + j] != ' ' && str[i + j] != '\t' && str[i + j] != '\n' && str[i + j] != '\0')
        {
            found = 0;
        }
        /*
         * If word is found then shift all characters to left
         * and decrement the string length
         */
        if(found == 1)
        {
            for(j=i; j<=stringLen - toRemoveLen; j++)
            {
                str[j] = str[j + toRemoveLen];
            }
            stringLen = stringLen - toRemoveLen;
            // We will match next occurrence of word from current index.
            i--;
        }
    }
}
Example
Input
Input string: I love programming. I love PHP.
Input word to remove: I
Output
String after removing 'I':
 love programming.  love PHP.

65. Wap to add two numbers using pointers.

#include <stdio.h>
int main()
{
    int num1, num2, sum;
    int *ptr1, *ptr2;
    ptr1 = &num1; // ptr1 stores the address of num1
    ptr2 = &num2; // ptr2 stores the address of num2
    printf("Enter any two numbers: ");
    scanf("%d%d", ptr1, ptr2);
    sum = *ptr1 + *ptr2;
    printf("Sum = %d", sum);
    return 0;
}

66. Wap to swap two number using pointers.

#include <stdio.h>
/* Swap function declaration */
void swap(int * num1, int * num2);
int main()
{
    int num1, num2;
    /* Input numbers */
    printf("Enter two numbers: ");
    scanf("%d%d", &num1, &num2);
    /* Print original values of num1 and num2 */
    printf("Before swapping in main n");
    printf("Value of num1 = %d \n", num1);
    printf("Value of num2 = %d \n\n", num2);
    /* Pass the addresses of num1 and num2 */
    swap(&num1, &num2);
    /* Print the swapped values of num1 and num2 */
    printf("After swapping in main n");
    printf("Value of num1 = %d \n", num1);
    printf("Value of num2 = %d \n\n", num2);
    return 0;
}
/**
 * Function to swap two numbers
 */
void swap(int * num1, int * num2)
{
    int temp;
    // Copy the value of num1 to some temp variable
    temp = *num1;
    // Copy the value of num2 to num1
    *num1= *num2;
    // Copy the value of num1 stored in temp to num2
    *num2= temp;
    printf("After swapping in swap function n");
    printf("Value of num1 = %d \n", *num1);
    printf("Value of num2 = %d \n\n", *num2);
}

67. Wap to take input and display element using pointers.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
    int arr[MAX_SIZE];
    int N, i;
    int * ptr = arr;    // Pointer to arr[0]
    printf("Enter size of array: ");
    scanf("%d", &N);
    printf("Enter elements in array:\n");
    for (i = 0; i < N; i++)
    {
        scanf("%d", ptr);
        // Move pointer to next array element
        ptr++;
    }
    // Make sure that pointer again points back to first array element
    ptr = arr;
    printf("Array elements: ");
    for (i = 0; i < N; i++)
    {
        // Print value pointed by the pointer
        printf("%d, ", *ptr);
        // Move pointer to next array element
        ptr++;
    }
    return 0;
}
OR
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
    int arr[MAX_SIZE];
    int N, i;
    int * ptr = arr;    // Pointer to arr[0]
    printf("Enter size of array: ");
    scanf("%d", &N);
    printf("Enter elements in array:\n");
    for (i = 0; i < N; i++)
    {
        // (ptr + i) is equivalent to &arr[i]
        scanf("%d", (ptr + i));
    }
    printf("Array elements: ");
    for (i = 0; i < N; i++)
    {
        // *(ptr + i) is equivalent to arr[i]
        printf("%d, ", *(ptr + i));
    }
    return 0;
}

68. Wap to copy one array to another using pointers.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
/* Function declaration to print array */
void printArray(int arr[], int size);
int main()
{
    int source_arr[MAX_SIZE], dest_arr[MAX_SIZE];
    int size, i;
    int *source_ptr = source_arr;   // Pointer to source_arr
    int *dest_ptr   = dest_arr;     // Pointer to dest_arr
    int *end_ptr;
    /*
     * Input size and elements in source array
     */
    printf("Enter size of array: ");
    scanf("%d", &size);
    printf("Enter elements in array: ");
    for (i = 0; i < size; i++)
    {
        scanf("%d", (source_ptr + i));
    }
    // Pointer to last element of source_arr
    end_ptr = &source_arr[size - 1];
    /* Print source and destination array before copying */
    printf("\nSource array before copying: ");
    printArray(source_arr, size);
    printf("\nDestination array before copying: ");
    printArray(dest_arr, size);
    /*
     * Run loop till source_ptr exists in source_arr
     * memory range.
     */
    while(source_ptr <= end_ptr)
    {
        *dest_ptr = *source_ptr;
        // Increment source_ptr and dest_ptr
        source_ptr++;
        dest_ptr++;
    }
    /* Print source and destination array after copying */
    printf("\n\nSource array after copying: ");
    printArray(source_arr, size);
    printf("\nDestination array after copying: ");
    printArray(dest_arr, size);
    return 0;
}
void printArray(int *arr, int size)
{
    int i;
    for (i = 0; i < size; i++)
    {
        printf("%d, ", *(arr + i));
    }
}

69. Wap to swap two arrays using pointers.

#include <stdio.h>
#define MAX_SIZE 100    // Maximum array size
/* Function declarations */
void inputArray(int *arr, int size);
void printArray(int *arr, int size);
void swapArray(int *sourceArr, int *destArr, int size);
int main()
{
    int sourceArr[MAX_SIZE];
    int destArr[MAX_SIZE];
    int size;
    // Input array size
    printf("Enter size of array: ");
    scanf("%d", &size);
    // Input elements of destination array
    printf("Enter %d elements in source array: ", size);
    inputArray(sourceArr, size);
    // Input element of destination array
    printf("Enter %d elements in destination array: ", size);
    inputArray(destArr, size);
    /*
     * Print elements of both arrays before swapping
     */
    printf("\n\nSource array before swapping: ");
    printArray(sourceArr, size);
    printf("\nDestination array before swapping: ");
    printArray(destArr, size);
    /* Swap elements of both arrays. */
    swapArray(sourceArr, destArr, size);
    /*
     * Print elements of both arrays after swapping
     */
    printf("\n\nSource array after swapping: ");
    printArray(sourceArr, size);
    printf("\nDestination array after swapping: ");
    printArray(destArr, size);
    return 0;
}
/**
 * Function used to read input from user in an array.
 *
 * @arr     Pointer to array to store input
 * @size    Size of the array
 */
void inputArray(int *arr, int size)
{
    // Pointer to last element of array.
    int *arrEnd = (arr + (size - 1));
    // Input elements in array using pointer
    while(arr <= arrEnd)
        scanf("%d", arr++);
}
/**
 * Function used to print elements of array.
 *
 * @arr     Pointer to array, which is to print.
 * @size    Size of the array
 */
void printArray(int *arr, int size)
{
    // Pointer to last element of array.
    int *arrEnd = (arr + (size - 1));
    // Print elements of array one by one
    while(arr <= arrEnd)
        printf("%d, ", *(arr++));
}
/**
 * Function to swap elements of two arrays.
 *
 * @sourceArr       Pointer to source array to swap.
 * @destArr         Pointer to destination array to swap.
 * @size            Size of array.
 */
void swapArray(int * sourceArr, int * destArr, int size)
{
    // Pointer to last element of source array
    int * sourceArrEnd = (sourceArr + (size - 1));
    // Pointer to last element of destination array
    int * destArrEnd   = (destArr + (size - 1));
    /*
     * Swap individual element of both arrays
     */
    while(sourceArr <= sourceArrEnd && destArr <= destArrEnd)
    {
        *sourceArr ^= *destArr;
        *destArr   ^= *sourceArr;
        *sourceArr ^= *destArr;
        // Increment source array to point to next element
        sourceArr++;
        // Increment destination array to point to next element
        destArr++;
    }
}
Output

70. Wap to reverse an array using pointer.

#include <stdio.h>
#define MAX_SIZE 100
/* Function declaration */
void printArr(int *arr, int size);
int main()
{
    int arr[MAX_SIZE];
    int size;
    int *left = arr;  // Pointer to arr[0]
    int *right;
    // Input size of array
    printf("Enter size of array: ");
    scanf("%d", &size);
    right = &arr[size - 1];  // Pointer to arr[size - 1]
    /*
     * Input elements in array
     */
    printf("Enter elements in array: ");
    while(left <= right)
    {
        scanf("%d", left++);
    }
    printf("\nArray before reverse: ");
    printArr(arr, size);
    // Make sure that left points to arr[0]
    left = arr;
    // Loop to reverse array
    while(left < right)
    {
        /*
         * Swap element from left of array to right of array.
         */
        *left    ^= *right;
        *right   ^= *left;
        *left    ^= *right;
        // Increment left array pointer and decrement right array pointer
        left++;
        right--;
    }
    printf("\nArray after reverse: ");
    printArr(arr, size);
    return 0;
}
/**
 * Function to print array using pointer.
 *
 * @arr     Pointer to array.
 * @size    Size of the array.
 */
void printArr(int * arr, int size)
{
    // Pointer to arr[size - 1]
    int * arrEnd = (arr + size - 1);
    /* Loop till last array element */
    while(arr <= arrEnd)
    {
        printf("%d, ", *arr);
        // Move pointer to next array element.
        arr++;
    }
}

71. Wap to find element in an array using pointer.

#include <stdio.h>
#define MAX_SIZE 100
/* Function declaration */
void inputArray(int * arr, int size);
int search(int * arr, int size, int toSearch);
int main()
{
    int array[MAX_SIZE];
    int size, toSearch, searchIndex;
    /*
     * Input size and elements in array
     */
    printf("Enter size of array: ");
    scanf("%d", &size);
    printf("Enter elements in array: ");
    inputArray(array, size);
    // Input element to search from user
    printf("Enter element to search: ");
    scanf("%d", &toSearch);
    // Call search funtion to search element in array
    searchIndex = search(array, size, toSearch);
    // Print search results
    if(searchIndex == -1)
        printf("%d does not exists in array.", toSearch);
    else
        printf("%d is found at %d position.", toSearch, searchIndex + 1);
    return 0;
}
/**
 * Function to input elements in array.
 *
 * @arr     Pointer to integer array
 * @size    Size of the array
 */
void inputArray(int * arr, int size)
{
    // Pointer to last array element arr[0]
    int * arrEnd = (arr + size - 1);
    // Run loop till last array element
    while(arr <= arrEnd)
    {
        scanf("%d", arr++);
    }
}
/**
 * Function to perform linear search in array. The function
 * returns an integer between 0 to size-1 specifying first
 * index of successful searched element in array.
 *
 * @arr      Pointer to integer array.
 * @size     Size of the array.
 * @toSearch Element to search within array.
 *
 * @return   Returns -1 if element does not exists in array,
 *           otherwise returns element index.
 */
int search(int * arr, int size, int toSearch)
{
    int index = 0;
    // Pointer to last array element arr[size - 1]
    int * arrEnd = (arr + size - 1);
    /*
     * Run a loop from start of array to last array element (arr <= arrEnd),
     * until current array element does not match element to search.
     */
    while(arr <= arrEnd && *arr != toSearch) {
        arr++;
        index++;
    }
    // If element is found
    if(arr <= arrEnd)
        return index;
    return -1;
}

72. Wap to find the length of string using pointer.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum size of the string
int main()
{
    char text[MAX_SIZE]; /* Declares a string of size 100 */
    char * str = text; /* Declare pointer that points to text */
    int count = 0;
    /* Input string from user */
    printf("Enter any string: ");
    gets(text);
    /* Iterate though last element of the string */
    while(*(str++) != '\0') count++;
    printf("Length of '%s' = %d", text, count);
    return 0;
}

73. Wap to copy one string to another using pointers.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum size of the string
int main()
{
    char text1[MAX_SIZE], text2[MAX_SIZE];
    char * str1 = text1;
    char * str2 = text2;
    /* Input string from user */
    printf("Enter any string: ");
    gets(text1);
    /* Copy text1 to text2 character by character */
    while(*(str2++) = *(str1++));
    printf("First string = %s\n", text1);
    printf("Second string = %s\n", text2);
    return 0;
}

74. Wap to combine two string using pointers.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
    char str1[MAX_SIZE], str2[MAX_SIZE];
    char * s1 = str1;
    char * s2 = str2;
    /* Input two strings from user */
    printf("Enter first string: ");
    gets(str1);
    printf("Enter second string: ");
    gets(str2);
    /* Move till the end of str1 */
    while(*(++s1));
    /* Copy str2 to str1 */
    while(*(s1++) = *(s2++));
    printf("Concatenated string = %s", str1);
    return 0;
}

75. Wap to compare two string using pointers.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
/* Compare function declaration */
int compare(char * str1, char * str2);
int main()
{
    char str1[MAX_SIZE], str2[MAX_SIZE];
    int res;
    /* Input two strings from user */
    printf("Enter first string: ");
    gets(str1);
    printf("Enter second string: ");
    gets(str2);
    /* Call the compare function to compare strings */
    res = compare(str1, str2);
    if(res == 0)
    {
        printf("Both strings are equal.");
    }
    else if(res < 0)
    {
        printf("First string is lexicographically smaller than second.");
    }
    else
    {
        printf("First string is lexicographically greater than second.");
    }
    return 0;
}
/**
 * Compares two strings lexicographically.
 */
int compare(char * str1, char * str2)
{
    while((*str1 && *str2) && (*str1 == *str2)) { str1++; str2++; }
    return *str1 - *str2;
}

76. Wap to reverse a string using pointers.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
    char str[MAX_SIZE], reverse[MAX_SIZE];
    char *s = str;
    char *r = reverse;
    int len = 0;
    /* Input string from user */
    printf("Enter any string: ");
    gets(str);
    /* Find length of string */
    while(*(s++)) len++;
    /*
     * Store each character from end of original string
     * to reverse string
     */
    s--;
    while(len >= 0)
    {
        *(r++) = *(--s);
        len--;
    }
    *r = '\0';
    printf("\nOriginal string = %s\n", str);
    printf("Reverse string = %s", reverse);
    return 0;
}

77. Wap to sort array using pointers.

#include <stdio.h>
#define MAX_SIZE 100
void inputArray(int * arr, int size);
void printArray(int * arr, int size);
int sortAscending(int * num1, int * num2);
int sortDescending(int * num1, int * num2);
void sort(int * arr, int size, int (* compare)(int *, int *));
int main()
{
    int arr[MAX_SIZE];
    int size;
    printf("Enter array size: ");
    scanf("%d", &size);
    printf("Enter elements in array: ");
    inputArray(arr, size);
    printf("\n\nElements before sorting: ");
    printArray(arr, size);
    // Sorting and printing sorted array in ascending order.
    printf("\n\nArray in ascending order: ");
    sort(arr, size, sortAscending);
    printArray(arr, size);
    // Sorting and printing sorted array in descending order.
    printf("\nArray in descending order: ");
    sort(arr, size, sortDescending);
    printArray(arr, size);
    return 0;
}
void inputArray(int * arr, int size)
{
    // Pointer to last element of array
    int * arrEnd = (arr + size - 1);
    // (arr++) Input in current array element and move to next element.
    // Till last array element (arr <= arrEnd)
    while(arr <= arrEnd)
        scanf("%d", arr++);
}
void printArray(int * arr, int size)
{
    // Pointer to last element of array
    int * arrEnd = (arr + size - 1);
    // *(arr++) Print current array element and move to next element.
    // Till last array element (arr <= arrEnd)
    while(arr <= arrEnd)
        printf("%d, ", *(arr++));
}
int sortAscending(int * num1, int * num2)
{
    return (*num1) - (*num2);
}
int sortDescending(int * num1, int * num2)
{
    return (*num2) - (*num1);
}
void sort(int * arr, int size, int (* compare)(int *, int *))
{
    // Pointer to last array element
    int * arrEnd  = (arr + size - 1);
    // Pointer to current array element
    int * curElem = arr;
    int * elemToSort;
    // Iterate over each array element
    while(curElem <= arrEnd)
    {
        elemToSort = curElem;
        // Compare each successive elements with current element
        // for proper order.
        while(elemToSort <= arrEnd)
        {
            /*
             * Compare if elements are arranged in order
             * or not. If elements are not arranged in order
             * then swap them.
             */
            if(compare(curElem, elemToSort) > 0)
            {
                *curElem    ^= *elemToSort;
                *elemToSort ^= *curElem;
                *curElem    ^= *elemToSort;
            }
            elemToSort++;
        }
        // Move current element to next element in array.
        curElem++;
    }
}

78. Wap to read and print element in an array.

#include <stdio.h>
#define MAX_SIZE 1000 // Maximum array size
int main()
{
    int arr[MAX_SIZE]; // Declare an array of MAX_SIZE
    int i, N;
    /* Input array size */
    printf("Enter size of array: ");
    scanf("%d", &N);
    /* Input elements in array */
    printf("Enter %d elements in the array : ", N);
    for(i=0; i<N; i++)
    {
        scanf("%d", &arr[i]);
    }
    printf("\nElements in array are: ");
    for(i=0; i<N; i++)
    {
        printf("%d, ", arr[i]);
    }
    return 0;
}

79. Wap to print all negative element in an array.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
    int arr[MAX_SIZE];
    int i, N;
    /* Input size of the array */
    printf("Enter size of the array : ");
    scanf("%d", &N);
    /* Input elements in the array */
    printf("Enter elements in array : ");
    for(i=0; i<N; i++)
    {
        scanf("%d", &arr[i]);
    }
    printf("\nAll negative elements in array are : ");
    for(i=0; i<N; i++)
    {
        /* If current array element is negative */
        if(arr[i] < 0)
        {
            printf("%d\t", arr[i]);
        }
    }
    return 0;
}

80. Wap to sum all the element in an array.

#include <stdio.h>
#define MAX_SIZE 100
int main()
{
    int arr[MAX_SIZE];
    int i, n, sum=0;
    /* Input size of the array */
    printf("Enter size of the array: ");
    scanf("%d", &n);
    /* Input elements in array */
    printf("Enter %d elements in the array: ", n);
    for(i=0; i<n; i++)
    {
        scanf("%d", &arr[i]);
    }
        for(i=0; i<n; i++)
    {
        sum = sum + arr[i];
    }
    printf("Sum of all elements of array = %d", sum);
    return 0;
}

81. Wap to find minimum and maximum element in an array.

#include <stdio.h>
#define MAX_SIZE 100   // Maximum array size
int main()
{
    int arr[MAX_SIZE];
    int i, max, min, size;
    /* Input size of the array */
    printf("Enter size of the array: ");
    scanf("%d", &size);
    /* Input array elements */
    printf("Enter elements in the array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    /* Assume first element as maximum and minimum */
    max = arr[0];
    min = arr[0];
    /*
     * Find maximum and minimum in all array elements.
     */
    for(i=1; i<size; i++)
    {
        /* If current element is greater than max */
        if(arr[i] > max)
        {
            max = arr[i];
        }
        /* If current element is smaller than min */
        if(arr[i] < min)
        {
            min = arr[i];
        }
    }
    /* Print maximum and minimum element */
    printf("Maximum element = %d\n", max);
    printf("Minimum element = %d", min);
    return 0;
}

82. Wap to find second largest element in an array.

#include <stdio.h>
#include <limits.h> // For INT_MIN
#define MAX_SIZE 1000
int main()
{
    int arr[MAX_SIZE], size, i;
    int max1, max2;
    /* Input size of the array */
    printf("Enter size of the array (1-1000): ");
    scanf("%d", &size);
    /* Input array elements */
    printf("Enter elements in the array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    max1 = max2 = INT_MIN;
    /*
     * Check for first largest and second
     */
    for(i=0; i<size; i++)
    {
        if(arr[i] > max1)
        {
            max2 = max1;
            max1 = arr[i];
        }
        else if(arr[i] > max2 && arr[i] < max1)
        {
            max2 = arr[i];
        }
    }
    printf("First largest = %d\n", max1);
    printf("Second largest = %d", max2);
    return 0;
}

83. Wap to count total number of even and odd element in an array.

#include <stdio.h>
#define MAX_SIZE 100 //Maximum size of the array
int main()
{
    int arr[MAX_SIZE];
    int i, size, even, odd;
    /* Input size of the array */
    printf("Enter size of the array: ");
    scanf("%d", &size);
    /* Input array elements */
    printf("Enter %d elements in array: ", size);
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    /* Assuming that there are 0 even and odd elements */
    even = 0;
    odd  = 0;
    for(i=0; i<size; i++)
    {
        /* If the current element of array is even then increment even count */
        if(arr[i]%2 == 0)
        {
            even++;
        }
        else
        {
            odd++;
        }
    }
    printf("Total even elements: %d\n", even);
    printf("Total odd elements: %d", odd);
    return 0;
}

84. Wap to count number of negative element in an array.

#include <stdio.h>
#define MAX_SIZE 100    // Maximum array size
int main()
{
    int arr[MAX_SIZE];  // Declares array of size 100
    int i, size, count = 0;
    /* Input size of array */
    printf("Enter size of the array : ");
    scanf("%d", &size);
    /* Input array elements */
    printf("Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    /*
     * Count total negative elements in array
     */
    for(i=0; i<size; i++)
    {
        /* Increment count if current array element is negative */
        if(arr[i] < 0)
        {
            count++;
        }
    }
    printf("\nTotal negative elements in array = %d", count);
    return 0;
}

85. Wap to copy all element of one array to another.

#include <stdio.h>
#define MAX_SIZE 100
int main()
{
    int source[MAX_SIZE], dest[MAX_SIZE];
    int i, size;
    /* Input size of the array */
    printf("Enter the size of the array : ");
    scanf("%d", &size);
    /* Input array elements */
    printf("Enter elements of source array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &source[i]);
    }
    /*
     * Copy all elements from source array to dest array
     */
    for(i=0; i<size; i++)
    {
        dest[i] = source[i];
    }
    /*
     * Print all elements of source array
     */
    printf("\nElements of source array are : ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", source[i]);
    }
    /*
     * Print all elements of dest array
     */
    printf("\nElements of dest array are : ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", dest[i]);
    }
    return 0;
}

86. Wap to insert an element in an array.

#include <stdio.h>
#define MAX_SIZE 100
int main()
{
    int arr[MAX_SIZE];
    int i, size, num, pos;
    /* Input size of the array */
    printf("Enter size of the array : ");
    scanf("%d", &size);
    /* Input elements in array */
    printf("Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    /* Input new element and position to insert */
    printf("Enter element to insert : ");
    scanf("%d", &num);
    printf("Enter the element position : ");
    scanf("%d", &pos);
    /* If position of element is not valid */
    if(pos > size+1 || pos <= 0)
    {
        printf("Invalid position! Please enter position between 1 to %d", size);
    }
    else
    {
        /* Make room for new array element by shifting to right */
        for(i=size; i>=pos; i--)
        {
            arr[i] = arr[i-1];
        }
        /* Insert new element at given position and increment size */
        arr[pos-1] = num;
        size++;
        /* Print array after insert operation */
        printf("Array elements after insertion : ");
        for(i=0; i<size; i++)
        {
            printf("%d\t", arr[i]);
        }
    }
    return 0;
}

87. Wap to remove at element at specific position from an array.

#include <stdio.h>
#define MAX_SIZE 100
int main()
{
    int arr[MAX_SIZE];
    int i, size, pos;
    /* Input size and element in array */
    printf("Enter size of the array : ");
    scanf("%d", &size);
    printf("Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    /* Input element position to delete */
    printf("Enter the element position to delete : ");
    scanf("%d", &pos);
    /* Invalid delete position */
    if(pos < 0 || pos > size)
    {
        printf("Invalid position! Please enter position between 1 to %d", size);
    }
    else
    {
        /* Copy next element value to current element */
        for(i=pos-1; i<size-1; i++)
        {
            arr[i] = arr[i + 1];
        }
        /* Decrement array size by 1 */
        size--;
    }
    /* Print array after deletion */
    printf("\nElements of array after delete are : ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}

88. Wap to count occurrence of each element in an array.

#include <stdio.h>
int main()
{
    int arr[100], freq[100];
    int size, i, j, count;
    /* Input size of array */
    printf("Enter size of array: ");
    scanf("%d", &size);
    /* Input elements in array */
    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
        /* Initially initialize frequencies to -1 */
        freq[i] = -1;
    }
    for(i=0; i<size; i++)
    {
        count = 1;
        for(j=i+1; j<size; j++)
        {
            /* If duplicate element is found */
            if(arr[i]==arr[j])
            {
                count++;
                /* Make sure not to count frequency of same element again */
                freq[j] = 0;
            }
        }
        /* If frequency of current element is not counted */
        if(freq[i] != 0)
        {
            freq[i] = count;
        }
    }
    /*
     * Print frequency of each element
     */
    printf("\nFrequency of all elements of array : \n");
    for(i=0; i<size; i++)
    {
        if(freq[i] != 0)
        {
            printf("%d occurs %d times\n", arr[i], freq[i]);
        }
    }
    return 0;
}
Example
Input
Input array elements: 5, 10, 2, 5, 50, 5, 10, 1, 2, 2
Output
Frequency of 5 = 3
Frequency of 10 = 2
Frequency of 2 = 3
Frequency of 50 = 1
Frequency of 1 = 1

89. Wap to count number of duplicate element in an array.

#include <stdio.h>
#define MAX_SIZE 100  // Maximum array size
int main()
{
    int arr[MAX_SIZE];
    int i, j, size, count = 0;
    /* Input size of array */
    printf("Enter size of the array : ");
    scanf("%d", &size);
    /* Input elements in array */
    printf("Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    /*
     * Find all duplicate elements in array
     */
    for(i=0; i<size; i++)
    {
        for(j=i+1; j<size; j++)
        {
            /* If duplicate found then increment count by 1 */
            if(arr[i] == arr[j])
            {
                count++;
                break;
            }
        }
    }
    printf("\nTotal number of duplicate elements found in array = %d", count);
    return 0;
}
Example
Input
Input array elements: 1, 10, 20, 1, 25, 1, 10, 30, 25, 1
Output
Total number of duplicate elements = 5

90. Wap to remove all duplicate element from an array.

#include <stdio.h>
#define MAX_SIZE 100 // Maximum size of the array
int main()
{
    int arr[MAX_SIZE]; // Declares an array of size 100
    int size;          // Total number of elements in array
    int i, j, k;       // Loop control variables
    /* Input size of the array */
    printf("Enter size of the array : ");
    scanf("%d", &size);
    /* Input elements in the array */
    printf("Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    /*
     * Find duplicate elements in array
     */
    for(i=0; i<size; i++)
    {
        for(j=i+1; j<size; j++)
        {
            /* If any duplicate found */
            if(arr[i] == arr[j])
            {
                /* Delete the current duplicate element */
                for(k=j; k<size; k++)
                {
                    arr[k] = arr[k + 1];
                }
                /* Decrement size after removing duplicate element */
                size--;
                /* If shifting of elements occur then don't increment j */
                j--;
            }
        }
    }
    /*
     * Print array after deleting duplicate elements
     */
    printf("\nArray elements after deleting duplicates : ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}
Example
Input
Input array elements: 10, 20, 10, 1, 100, 10, 2, 1, 5, 10
Output
After removing all duplicate elements
Elements of array are: 10, 20, 1, 100, 2, 5

91. Wap to reverse  an array.

#include <stdio.h>
#define MAX_SIZE 100      // Defines maximum size of array
int main()
{
    int arr[MAX_SIZE];
    int size, i;
    /* Input size of array */
    printf("Enter size of the array: ");
    scanf("%d", &size);
    /* Input array elements */
    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    /*
     * Print array in reversed order
     */
    printf("\nArray in reverse order: ");
    for(i = size-1; i>=0; i--)
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}
Example
Input
Input array elements: 10, 5, 16, 35, 500
Output
Array elements after reverse: 500, 35, 16, 5, 10

92. Wap to search an element in an array.

#include <stdio.h>
#define MAX_SIZE 100  // Maximum array size
int main()
{
    int arr[MAX_SIZE];
    int size, i, toSearch, found;
    /* Input size of array */
    printf("Enter size of array: ");
    scanf("%d", &size);
    /* Input elements of array */
    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    printf("\nEnter element to search: ");
    scanf("%d", &toSearch);
    /* Assume that element does not exists in array */
    found = 0;
    for(i=0; i<size; i++)
    {
        /*
         * If element is found in array then raise found flag
         * and terminate from loop.
         */
        if(arr[i] == toSearch)
        {
            found = 1;
            break;
        }
    }
    /*
     * If element is not found in array
     */
    if(found == 1)
    {
        printf("\n%d is found at position %d", toSearch, i + 1);
    }
    else
    {
        printf("\n%d is not found in the array", toSearch);
    }
    return 0;
}
Example
Input
Input size of array: 10
Input elements in array: 10, 12, 20, 25, 13, 10, 9, 40, 60, 5
Output
Element to search is: 25
Element found at index 3

93. Wap to sort array element in ascending and descending order.

#include <stdio.h>
#define MAX_SIZE 100    // Maximum array size
int main()
{
    int arr[MAX_SIZE];
    int size;
    int i, j, temp;
    /* Input size of array */
    printf("Enter size of array: ");
    scanf("%d", &size);
    /* Input elements in array */
    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }
    for(i=0; i<size; i++)
    {
        /*
         * Place currently selected element array[i]
         * to its correct place.
         */
        for(j=i+1; j<size; j++)
        {
            /*
             * Swap if currently selected array element
             * is not at its correct position.
             */
            if(arr[i] > arr[j])
            {
                temp     = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    /* Print the sorted array */
    printf("\nElements of array in ascending order: ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}
Example
Input
Input size of array: 10
Input array elements: 20, 2, 10, 6, 52, 31, 0, 45, 79, 40
Output
Array sorted in ascending order: 0, 2, 6, 10, 20, 31, 40, 45, 52, 79

94. Wap to sort even and odd element of array separately.

#include <stdio.h>
#include <limits.h> //Used for INT_MAX
#define MAX_SIZE 1000 //Maximum size of the array
/*
 * Functions used in this program
 */
void arrange(int arr[], int len, int pivot);
void sort(int arr[], int start, int end);
void print(int arr[], int len);
int main()
{
    int arr[MAX_SIZE], i, n;
    int pivot, evenCount, oddCount;
    pivot = 0;
    evenCount = oddCount = 0;
    /*
     * Reads size and elements in the array
     */
    printf("Enter size of the array: ");
    scanf("%d", &n);
    printf("Enter elements in the array: ");
    for(i=0; i<n; i++)
    {
        scanf("%d", &arr[i]);
        // If current element is odd then increase pivot
        if(arr[i] & 1)
            oddCount++;
        else
            evenCount++;
    }
    /*
     * Pivot is position that separates even and odd elements
     */
    pivot = (evenCount > oddCount) ? evenCount : oddCount;
    print(arr, n);
    // Arranges all even and odd elements sequentially
    arrange(arr, n, pivot);
    // Print elements after arranging even and odd elements
    printf("\nElements after arranging even and odd elements separately\n");
    print(arr, n);
    //Sorts even part of the array
    sort(arr, pivot, n);
    //Sorts odd part of the array
    sort(arr, 0, pivot);
    //Prints the final sorted array
    printf("\nFinal array after sorting even and odd elements separately\n");
    print(arr, n);
    return 0;
}
/**
 * Arranges all even and odd elements of the array separately. Puts
 * all even elements first then all odd elements.
 */
void arrange(int arr[], int len, int pivot)
{
    int i, j, temp;
    for(i=0; i<pivot; i++)
    {
        /*
         * If current element of array is odd put it into
         * odd element place
         */
        if(arr[i] & 1)
        {
            for(j=pivot; j<len; j++)
            {
                //Look for an even element then swap with odd element
                if(!(arr[j] & 1))
                {
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                    break;
                }
            }
        }
    }
}
/**
 * Sorts the elements of array within a range
 */
void sort(int arr[], int start, int end)
{
    int i, j, temp;
    int len = start + end;
    for(i=start; i<len; i++)
    {
        for(j=i+1; j<len; j++)
        {
            if(arr[j] < arr[i])
            {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}
/**
 * Prints the entire integer array
 */
void print(int arr[], int len)
{
    int i;
    printf("Elements in the array: ");
    for(i=0; i<len; i++)
    {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
Example
Input
Input size of array: 10
Input elements of array: 0 5 1 2 3 4 6 12 10 9
Output
Output in sorted order: 0 2 4 6 10 12 1 3 5 9

95. Wap to perform all arithmetic operations on two given numbers.

#include <stdio.h>
int main()
{
    int num1, num2;
    int sum, sub, mult, mod;
    float div;
    /*
     * Input two numbers from user
     */
    printf("Enter any two numbers: ");
    scanf("%d%d", &num1, &num2);
    /*
     * Perform all arithmetic operations
     */
    sum = num1 + num2;
    sub = num1 - num2;
    mult = num1 * num2;
    div = (float)num1 / num2;
    mod = num1 % num2;
    /*
     * Print result of all arithmetic operations
     */
    printf("SUM = %d\n", sum);
    printf("DIFFERENCE = %d\n", sub);
    printf("PRODUCT = %d\n", mult);
    printf("QUOTIENT = %f\n", div);
    printf("MODULUS = %d", mod);
    return 0;
}
Example
Input
First number: 10
Second number: 5
Output
Sum = 15
Difference = 5
Product = 50
Quotient = 2
Modulus = 0

96. Wap to maximum number between two number with the help of conditional operator.

#include <stdio.h>
int main(){
int num1, num2, max;
/** Input two number from user*/
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
/** If num1 > num2 then* assign num1 to max* else* assign num2 to max*/
max = (num1 > num2) ? num1 : num2;
printf("Maximum between %d and %d is %d", num1, num2, max);
return 0;
}
Example:
Input first number: 10
Input second number: 20
OutputMaximum: 20

97. Wap to check whether number is odd or even with the help of conditional operator.

#include <stdio.h>
int main()
{
    int num;
    /* Input a number from user */
    printf("Enter any number to check even or odd: ");
    scanf("%d", &num);
    /*
     * If n%2==0 then
     *     print it is even
     * else
     *     print it is odd
     */
    (num%2 == 0)
        ? printf("The number is EVEN")
        : printf("The number is ODD");
    return 0;
}
Example
Input
Input num: 10
Output
10 is even.

98. Wap to check whether given year is leap year or not with the help of conditional operator.

#include <stdio.h>
int main()
{
    int year;
    /*
     * Input year from user
     */
    printf("Enter any year: ");
    scanf("%d", &year);
    /*
     * If year%4==0 and year%100==0 then
     *     print leap year
     * else if year%400==0 then
     *     print leap year
     * else
     *     print common year
     */
    if(year%4==0 && year%100!=0) ? printf("LEAP YEAR") :
        (year%400 ==0 ) ? printf("LEAP YEAR") : printf("COMMON YEAR");
    return 0;
}
Example
Input
Input year: 2016
Output
2016 is Leap Year

99. Wap to check if given character is alphabet or not with the help of conditional operator.

#include <stdio.h>
int main()
{
    char ch;
    /*
     * Input character from user
     */
    printf("Enter any character: ");
    scanf("%c", &ch);
    /*
     * If (ch>'a' and ch<'z') or (ch>'A' and ch<'Z') then
     *     print alphabet
     * else
     *     print not alphabet
     */
    (ch>='a' && ch<='z') || (ch>='A' && ch<='Z')
        ? printf("It is ALPHABET")
        : printf("It is NOT ALPHABET");
    return 0;
}
Example
Input
Enter any character: a
Output
It is ALPHABET

100. Wap to find maximum between three given number with the help of conditional operator.

#include <stdio.h>
int main()
{
    int num1, num2, num3, max;
    /*
     * Input three numbers from user
     */
    printf("Enter three numbers: ");
    scanf("%d%d%d", &num1, &num2, &num3);
    /*
     * If num1 > num2 and num1 > num3 then
     *     assign num1 to max
     * else if num2 > num3 then
     *     assign num2 to max
     * else
     *     assign num3 to max
     */
    max = (num1 > num2 && num1 > num3) ? num1 :
          (num2 > num3) ? num2 : num3;
    printf("\nMaximum between %d, %d and %d = %d", num1, num2, num3, max);
    return 0;
}
Example
Input
Input num1: 10
Input num2: 20
Input num3: 30
Output
Maximum is 30

101. Wap to print week days name with the help of switch case.

#include <stdio.h>
int main()
{
    int week;
    /* Input week number from user */
    printf("Enter week number(1-7): ");
    scanf("%d", &week);
    switch(week)
    {
        case 1:
            printf("Monday");
            break;
        case 2:
            printf("Tuesday");
            break;
        case 3:
            printf("Wednesday");
            break;
        case 4:
            printf("Thursday");
            break;
        case 5:
            printf("Friday");
            break;
        case 6:
            printf("Saturday");
            break;
        case 7:
            printf("Sunday");
            break;
        default:
            printf("Invalid input! Please enter week number between 1-7.");
    }
    return 0;
}
Example
Input
Input week number(1-7): 2
Output
Tuesday

102. Wap to print total number of days in a month with the help of switch case.

#include <stdio.h>
int main()
{
    int month;
    /* Input month number from user */
    printf("Enter month number(1-12): ");
    scanf("%d", &month);
    switch(month)
    {
        case 1:
            printf("31 days");
            break;
        case 2:
            printf("28/29 days");
            break;
        case 3:
            printf("31 days");
            break;
        case 4:
            printf("30 days");
            break;
        case 5:
            printf("31 days");
            break;
        case 6:
            printf("30 days");
            break;
        case 7:
            printf("31 days");
            break;
        case 8:
            printf("31 days");
            break;
        case 9:
            printf("30 days");
            break;
        case 10:
            printf("31 days");
            break;
        case 11:
            printf("30 days");
            break;
        case 12:
            printf("31 days");
            break;
        default:
            printf("Invalid input! Please enter month number between 1-12");
    }
    return 0;
}
Example
Input
Input month number: 3
Output
Total number of days = 31

103. Wap to check whether given number is positive, negative or zero with the help of switch case.

#include <stdio.h>
int main()
{
    int num;
    printf("Enter any number: ");
    scanf("%d", &num);
    switch (num > 0)
    {
        // Num is positive
        case 1:
            printf("%d is positive.", num);
        break;
        // Num is either negative or zero
        case 0:
            switch (num < 0)
            {
                case 1:
                    printf("%d is negative.", num);
                    break;
                case 0:
                    printf("%d is zero.", num);
                    break;
            }
        break;
    }
    return 0;
}
Example
Input
Input number: 23
Output
23 is positive

104. Wap to create simple calculator with the help of switch case.

#include <stdio.h>
int main()
{
    char op;
    float num1, num2, result=0.0f;
    /* Print welcome message */
    printf("WELCOME TO SIMPLE CALCULATOR\n");
    printf("----------------------------\n");
    printf("Enter [number 1] [+ - * /] [number 2]\n");
    /* Input two number and operator from user */
    scanf("%f %c %f", &num1, &op, &num2);
    /* Switch the value and perform action based on operator*/
    switch(op)
    {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            result = num1 / num2;
            break;
        default:
            printf("Invalid operator");
    }
    /* Prints the result */
    printf("%.2f %c %.2f = %.2f", num1, op, num2, result);
    return 0;
}
Example
Input
5.2 - 3
Output
2.2

 

Related Articles

Core Java

1. What are primitive types in Java ? byte, short, int, long, float, double, char, boolean… 2. What are tokens? Name the 5 types of tokens available in Java with an example…

Advance Java

1. Write an Example Snippet to Connect Java Application with mysql database. 2. Wap to get the object of ResultSetMetaData. The getMetaData() method of ResultSet…

Responses

Your email address will not be published. Required fields are marked *

New Report

Close