Friday, 30 December 2016

C Program to search a number in an array

#include<stdio.h>
#include<conio.h>
main()
{
 int a[20],i,key,n;
 clrscr();
 printf("Enter the number of elements in the array\t");
 scanf("%d",&n);
 printf("Enter the elements of the array\n");
 for(i=0;i<n;i++)
   scanf("%d",&a[i]);
 printf("Enter the element to be searched\t");
 scanf("%d",&key);
 for(i=0;i<=n;i++)
 {
   if (a[i]==key)
   {
    printf("The element %d occurs at location %d of the array\n",key,i+1);
    break;
   }
 }
 if (i>n)
   printf("The element %d does not exist in the array\n",key);
 getch();
}
/*
OUTPUT
--------
Enter the number of elements in the array       5
Enter the elements of the array                                              
1                                                                            
2                                                                            
3                                                                            
4                                                                            
5                                                                            
Enter the element to be searched        1                                    
The element 1 occurs at location 1 of the array

Enter the number of elements in the array       5
Enter the elements of the array                                              
2                                                                            
3                                                                            
1                                                                            
5                                                                            
7                                                                            
Enter the element to be searched        8
The element 8 does not exist in the array
*/                                                            

Tuesday, 27 December 2016

C Program to count the number of times an element occurs in an array

This program searches and counts the number of times the given element is present in an array. If the number is not found then an appropriate message "Number not present in the array" is displayed.

Algortihm

1. Read the array elements

2. Input the element whose occurrence is to be counted

3. Compare the array elements one by one with the search element

4. If there is a match, the counter is incremented

5. At the end of the array,
                   if counter=0  print "number not present in the array"
                    else
                        print Counter

Program

//Program to count the number of occurrences of an element in an array
#include<stdio.h>
#include<conio.h>
#define SIZE 20
main()
{
  int arr[SIZE],i,n,found=0,key;

  clrscr();
  printf("Enter the number of elements in the array\n");
  scanf("%d",&n);
  printf("\nEnter the array elements one by one\n");
  for(i=0;i<n;i++)
   scanf("%d",&arr[i]);
  printf("\nEnter the element to be searched\n");
  scanf("%d",&key);

  for(i=0;i<n;i++)
    if (arr[i]==key)
       found++;

  if (found==0)
     printf("\nThe element %d does not occur in the array\n",key);
  else
     printf("\nThe element %d occurs %d times in the array",key,found);

  getch();
}

/*
OUTPUT
--------
Enter the number of elements in the array
10                                                                            
                                                                               
Enter the array elements one by one                                            
1                                                                              
2                                                                              
3                                                                              
1                                                                              
4                                                                              
5                                                                              
1                                                                              
67                                                                            
1                                                                              
8                                                                              
                                                                               
Enter the element to be searched                                              
1                                                                              
                                                                               
The element 1 occurs 4 times in the array
*/        


Wednesday, 21 December 2016

C Program for Decimal to Binary, Octal and Hexadecimal

Converting a decimal number to other number systems like binary, octal and hexadecimal is usually done separately. In the following program, it is enough to specify the decimal number and the radix or the base.

Algorithm
1. Read the decimal number and the base
2. Divide the number by base and get the remainder
3. Store the remainder in an array
4. Divide the number by base and set the quotient as the number
5. Repeat steps 2 to 4 till the number reaches zero
6. Display the contents of the array in reverse order
7. For hexadecimal check the array values before display


//Program for number system conversion
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main()
{
  int n,radix,result[16],i=0,rem,num;
  char c;

  clrscr();
  printf("Enter the decimal number\n");
  scanf("%d",&n);
  do
  {
    printf("\nEnter radix for conversion\n");
    printf("2 --> Binary   8 --> Octal 16 --> Hexadecimal\n");
    scanf("%d",&radix);
    num=n;i=0;
    while (n>0)
    {
      rem=n%radix;
      result[i++]=rem;
      n=n/radix;
    }
    n=num;
    printf("The result\n");
    for(i-=1;i>=0;i--)
    {
      if (radix==16)
      {
switch (result[i])
{
  case 10 : printf("A");
    break;
  case 11:  printf("B");
    break;
  case 12 : printf("C");
    break;
  case 13 : printf("D");
    break;
  case 14 : printf("E");
    break;
  case 15 : printf("F");
    break;
  default : printf("%d",result[i]);
}
      }
      else
printf("%d",result[i]);
   }
   printf("\nWant to convert to other number system? Y(y) / N(n)\n");
   c=getche();
   }while (toupper(c)=='Y');
  getch();
}


/*
OUTPUT
________
Enter the decimal number
208                                                                             
                                                                                
Enter radix for conversion                                                      
2 --> Binary   8 --> Octal      16 --> Hexadecimal                              
2                                                                               
The result                                                                      
11010000                                                                        
Want to convert to other number system? Y(y) / N(n)                             
y                                                                               
Enter radix for conversion                                                      
2 --> Binary   8 --> Octal      16 --> Hexadecimal                              
8                                                                               
The result                                                                      
320                                                                             
Want to convert to other number system? Y(y) / N(n)                             
y                                                                               
Enter radix for conversion                                                      
2 --> Binary   8 --> Octal      16 --> Hexadecimal                              
16                                                                              
The result                                                                      
D0                                                                              
Want to convert to other number system? Y(y) / N(n)                             
n                                                                               
*/

Friday, 16 December 2016

C program to find the second largest in an array without sorting

The simplest way to find the second largest number in an array is to sort the numbers in either ascending or descending order and print the second number or last but one number respectively. Even though it is easier to understand, it consumes more time for sorting and also the numbers are reshuffled in the array. The following program finds the second largest without sorting the numbers in the array.

//Program to find the largest and the second largest number in an array
#include<stdio.h>
#include<conio.h>
main()
{
  int i, n, a[10], max, smax;

  clrscr();
  printf("Enter the number of elements in the array\n");
  scanf("%d",&n);
  printf("\nEnter the numbers in the array one by one\n");
  for(i=0;i<n;i++)
  scanf("%d",&a[i]);

  max=a[0];
  for(i=0;i<n;i++)
    if (a[i]>max)
       max=a[i];

  smax=a[0];
  for(i=0;i<n;i++)
    if ((a[i]>smax && a[i]<max) || smax==max)
       smax=a[i];

  printf("the largest number is %d\n",max);
  printf("the second largest number is %d\n",smax);

  getch();
}

/*
OUTPUT
-------
Enter the number of elements in the array
5                                                                              
                                                                               
Enter the numbers in the array one by one                                      
2                                                                              
8                                                                              
7                                                                              
1                                                                              
9                                                                              
the largest number is 9                                                        
the second largest number is 8                                                
*/

Thursday, 15 December 2016

C program for Matrix Manipulation

To understand two-dimensional(2D) arrays in C, quite often matrix data structure is used. Here is a simple program to learn how matrix is created, adding two matrices, multiplying two matrices and how to display the 2D array in the matrix form.

The program is not efficient since static memory allocation is used which will waste more memory space. But this program will surely help to learn the basics behind 2D arrays and passing 2D arrays to functions.

//Program for matrix manipulation
#include<stdio.h>
#include<conio.h>
main()
{
  int mat1[5][5], mat2[5][5],i,j,m1,n1, m2,n2;

  clrscr();
  printf("Enter the order of matrix 1\n");
  scanf("%d%d",&m1,&n1);
  printf("\n Enter matrix 1\n");
  for(i=0;i<m1;i++)
   for(j=0;j<n1;j++)
    scanf("%d", &mat1[i][j]);

  printf("Enter the order of matrix 2\n");
  scanf("%d%d",&m2,&n2);
  printf("\n Enter matrix 2\n");
  for(i=0;i<m2;i++)
   for(j=0;j<n2;j++)
    scanf("%d",&mat2[i][j]);
 
   printf("Given matrix1\n");
   display(mat1,m1,n1);
 
   printf("Given matrix2\n");
   display(mat2,m2,n2);
 
   add(mat1,mat2,m1,n1,m2,n2);
   multiply(mat1,mat2,m1,n1,m2,n2);
   getch();
}

display(int mat[5][5],int m,int n)
{
  int i,j;

  for(i=0;i<m;i++)
  {
    for(j=0;j<n;j++)
    printf("%d\t",mat[i][j]);
    printf("\n");
  }
}

add(int a[5][5],int b[5][5],int m1,int n1,int m2,int n2)
{
  int i,j;
  int result[5][5];

  if ((m1==m2) && (n1==n2))
  {
    for(i=0;i<m1;i++)
      for(j=0;j<n1;j++)
      result[i][j]=a[i][j] + b[i][j];
    printf("The sum matrix \n");
    display(result,m1,n1);
  }
  else
  printf("The matrices cannot be added because their orders are not same\n");
}

multiply(int a[5][5],int b[5][5],int m1,int n1,int m2,int n2)
{
  int i,j,k;
  int result[5][5];

  if (n1==m2)
  {
    for(i=0;i<m1;i++)
      for(j=0;j<n2;j++)
      {
result[i][j]=0;
for(k=0;k<n1;k++)
  result[i][j]=result[i][j]+a[i][k] * b[k][j];
       }
    printf("The product matrix \n");
    display(result,m1,n1);
  }
  else
  printf("The matrices cannot be multiplied because the number of columns in matrix1 is not equal to the number of rows in matrix2\n");
}

/*
OUTPUT
--------
Enter the order of matrix 1
2 2

Enter matrix 1
1 1 1 1
Enter the order of matrix 2
2 2

Enter matrix 2
3 3 3 3
Given matrix1
1       1
1       1
Given matrix2
3       3
3       3
The sum matrix
4       4
4       4
The product matrix
6       6
6       6
*/

Monday, 12 December 2016

C program to insert an element into an array using pointers

In C, an array is a static data structure to store data of similar data type. But using pointers the array can be made dynamic. That is, the array size can be changed to accommodate more values as and when necessary. Using pointers the storage space is not wasted.

In this program, malloc() function is used to allocate memory dynamically for the array and afterwards realloc() function is used to increase the memory for array to insert more values into the array.

//Program to insert elements into an array
#include<stdio.h>
#include<conio.h>
#include<alloc.h>

int size;
main()
{
  int pos, n, i, size, j, choice;
  int *arr;

  clrscr();
  printf("Enter the number of elements in the array\n");
  scanf("%d",&size);
  arr=(int *)malloc(size*sizeof(int));
  printf("Enter the elements in the array\n");
  for(i=0;i<size;i++)
  scanf("%d",(arr+i));

  do
  {
    printf("Enter the number to be inserted into the array\n");
    scanf("%d",&n);
    printf("Enter the position at which the number is to be inserted\n");
    scanf("%d",&pos);
    printf("The elements in the array before insertion\n");
    for(i=0;i<size;i++)
     printf("%d\n",*(arr+i));

    ++size;
    arr=(int *)realloc(arr, size+1);
    for(i=size-1,j=i-1;i>pos;i--,j--)
     *(arr+i)=*(arr+j);
     *(arr+pos)=n;

    printf("The elements in the array after insertion\n");
    for(i=0;i<size;i++)
    printf("%d\n",*(arr+i));
   printf("Do you want to insert more elements? 1.Yes 2. No\n");
   scanf("%d",&choice);
  }while (choice==1);
    getch();
}

/*
OUTPUT
-------
Enter the number of elements in the array
4
Enter the elements in the array
1
2
3
4
Enter the number to be inserted into the array
5
Enter the position at which the number is to be inserted
0
The elements in the array before insertion
1
2
3
4
The elements in the array after insertion
5
1
2
3
4

Do you want to insert more elements? 1.Yes 2. No
1
Enter the number to be inserted into the array
6
Enter the position at which the number is to be inserted
5
The elements in the array before insertion
5
1
2
3
4
The elements in the array after insertion
5
1
2
3
4
6
Do you want to insert more elements? 1.Yes 2. No
1
Enter the number to be inserted into the array
7
Enter the position at which the number is to be inserted
3
The elements in the array before insertion
5
1
2
3
4
6
The elements in the array after insertion
5
1
2
7
3
4
6

Do you want to insert more elements? 1.Yes 2. No
2

*/

Thursday, 8 December 2016

C Program to print the matrix elements forming the "z" locations

This is a challenging program asked in one of the campus interviews asked in our college.

Display the matrix elements from the first row, diagonal elements and last row using single loop. The display should contain elements in a z form from the given matrix.


//Program to display Z position elements in a matrix with single loop
#include<stdio.h>
#include<conio.h>
main()
{
  int a[10][10];
  int i,j;
  int m,n;

  clrscr();
  printf("Enter Row & Column Value \n");
  scanf("%d%d",&m,&n);

  printf("Enter Matrix Elements\n");
   for(i=0;i<m;i++)
    for(j=0;j<n;j++)
     scanf("%d",&a[i][j]);

   printf("\n The given matrix\n");
   for(i=0;i<m;i++)
   {
    for(j=0;j<n;j++)
      printf("%d\t",a[i][j]);
    printf("\n");
   }

   printf("\n The matrix elements in Z position\n");
   for(i=0;i<m;i++)
  {
     printf("\n\n");
     for(j=0;j<n;j++)
     {
         if(i==0)          // First Row
             printf("%d\t",a[i][j]);
         else if(i==m-1)        // Last Row
              printf("%d\t",a[i][j]);
         else if(j==n-(i+1))         // Diagonal Elements
               printf("%d\t",a[i][j]);
      else
       printf("\t");

     }
  }
 getch();
}


OUTPUT
-------
Enter Row & Column Value
3 3                                                                          
Enter Matrix Elements                                                        
1 2 3                                                                        
4 5 6                                                                        
7 8 9                                                                        
                                                                             
 The given matrix                                                            
1       2       3                                                            
4       5       6                                                            
7       8       9                                                            

 The matrix elements in Z position


1       2       3

  5

7       8       9












                                                                             
                                                                             

Wednesday, 7 December 2016

Palindrome Checking

A palindrome is a sequence of characters or numbers, which reads the same both forward and backward.  Example:   madam, kayak, 12321.

//Program to check palindrome
#include<stdio.h>
#include<conio.h>
main()
{
 int choice,i=0,j,n,num,rev=0;
 char *str;
 clrscr();
 do
 {
  printf("1. String Palindrome\n 2. Number Palindrome\n");
  printf("Enter your choice\n");
  scanf("%d",&choice);
  switch (choice)
  {
    case 1: printf("Enter the string\n");
              scanf("%s",str);
              while (str[++i] !='\0');          // To count the number of characters
                 i=i-1;
              for(j=0;j<=i;j++,i--)             // j starts from first character and i starts from last character
if (str[j]!=str[i])
break;
                if (j>i)
printf("The given string is palindrome\n");
               else
printf("The given string is not palindrome\n");
               break;
    case 2: printf("Enter the number\n");
              scanf("%d",&n);
              num=n;                     //the given number is needed for final comparison; hence stored in num
              rev=0;
             while (n>0)
    {
rev=rev*10+n%10;
n=n/10;
             }
             if (num==rev)
printf("The given number %d is palindrome\n",num);
            else
printf("The given number %d is not palindrome\n",num);
             break;
    default: printf("Wrong choice\n");
   }
   printf("Do you want to continue? 1. Yes  2. No\n");
   scanf("%d",&choice);
 }while (choice==1);
getch();
}

/*
OUTPUT
------------
1
Enter the string
mary
The given string is not palindrome
Do you want to continue? (y/n)1. Yes  2. No
1
1. String Palindrome
2. Number Palindrome
Enter your choice
2
Enter the number
12321
The given number 12321 is palindrome
Do you want to continue? (y/n)1. Yes  2. No
1
1. String Palindrome
2. Number Palindrome
Enter your choice
2
Enter the number
1234
The given number 1234 is not palindrome
Do you want to continue? (y/n)1. Yes  2. No
2
*/

Monday, 5 December 2016

C program to display prime numbers in a range

Prime numbers are numbers which are divisible by 1 and itself. Hence the number of divisors for a prime number is exactly two. This logic is used to print the prime numbers between two limits.

//Program to display prime numbers between two limits
#include<stdio.h>
#include<conio.h>
main()
{
int m, n, c, j;

clrscr();
printf("Enter the lower and upper limits \n");
scanf("%d%d",&m,&n);
printf("\n The prime numbers between the limits %d and %d\n",m,n);
printf("-------------------------------------------------\n");
while (m<=n)
{
    c=0;
    for(j=1;j<=m;j++)
    {
        if   (m%j==0)
            c++;
    }
    
    if   (c==2)
          printf("%d\n",m);

    m++;
}

getch();

}


The output of the program is as follows
OUTPUT
------------
Enter the lower and upper limits
5
50

 The prime numbers between the limits 5 and 50
----------------------------------------------------------
5
7
11
13
17
19
23
29
31
37
41
43
47