C Arrays Questions

1. Write a function to reverse an array in place. (Do not use a second array.)
We swap every element a[i] with a[l-1-i] where l is the length of the array. We swap until we reach the mid point of the array. That is as long as i is less than j.
 

void reverse_array(int array[],int size) { int i,j; for(i=0,j=size-1;i<j;i++,j--) { int temp = array[i]; array[i]= array[j]; array[j] = temp; } }


2. Write a program to check if the elements of an integer array are in an arithmetic sequence or arithmetic progression. (AP)

An arithmeitc sequence is a series of numbers where the difference between any two consecutive numbers is a constant d.
e.g. 1 4 7 10 13 16 19 22 25 ...

#include<stdio.h>
int elements_in_ap(int arr[],int n);
int main()
{
   int arr[30];
   int n;
   int i;
   int ap;
   printf("size of array:");
   scanf("%d",&n);
   for(i=0;i<n;i++)
       scanf("%d",&arr[i]);
   ap = elements_in_ap(arr,n);
   ap?printf("Elements are in AP"):printf("Elements are not in AP");
   return 0;
}
//find the difference between oth and 1st element. And compare consecutive element differences to this.
int elements_in_ap(int *arr,int n)
{

   int diff = arr[1]-arr[0];
   int i;
   for(i=1;i<n;i++)
   {
      if(arr[i]-arr[i-1]!=diff)
      {
         return 0;
      }
    }
    return 1;
}
3. How can you initialize only one element of an array - not the zeroth element but any other element?

To initialize intermediate element, c99 has introduced syntax where you give element designator with its value. Element designator is index and is given in square brackets.

e.g.
int arr[10]={1,3,[8]=10};

Here 0th element is 1, first element is 3 and 8th element is 10.

4. Given an array A[N] containing N numbers. Crate an array Output[N] where Output[i] is equal to the product of all the elements of A[N] except A[i]. For example Output[0] is the product of A[1] to A[N-1] and Output[1] is the product of A[0] and from A[2] to A[N-1].

Find the product of all elements of A and store them this product in each element of Output. Next divide ith element of Output array by ith element of A.
#include<stdio.h>
 int product(int arr[],int size)
 {
     int product=1;
     int i;
     for(i=0;i<size;i++)
        product *=arr[i];
     return product;
 }
 
 int main()
 {
    int  arr[50];
    int output[50];
    int size,i,k;
    int pr;
    printf("Enter size of array:");
    scanf("%d",&size);
    printf("Elements of the array:");
    for(i=0;i<size;i++)
        scanf("%d",&arr[i]);
    pr = product(arr,size);
    for(i=0;i<size;i++)
       output[i] = pr/arr[i];
    for(i=0;i<size;i++)
      printf("output[%d]=%d\n",i,output[i]);
    return 0;
 }
5. You have an array of 99 numbers. The array contains the numbers 1 to 100 with one number missing. Write C functions to find the missing number for speed optimization

We use a temporary array which is initialized with 0 for all elements. Then for each element of arr[i]=n, temp[n] will be set to 1. e.g. if arr[0] =3, temp[3] will be set to 1. If arr[1]=4, temp[4] will be set to 1.
So the only element which will be 0 will be the element missing from array.
#include<stdio.h>
int fillSecondArray(int arr[],int temp[],int sz)
{
   int i;
   for(i=0;i<=sz;i++)
   {
       int n = arr[i];
       if(n<100)
        temp[n]=1;
   }
}

int findMissingElement(int temp[],int sz)
{
   int i;
   for(i=0;i<=sz;i++)
      if(temp[i]==0)
        return i+1;
   return -1;
}
/*sample program with one element missing from array*/
int main()
{
   int arr[99];
   int num;
   int i,j;
   printf("Enter num:");
   scanf("%d",&num);
   for(i=0;i<=100;i++)
   {
      if(i!=num)
        arr[i]=i+1;
    }
   int temp[101]={0};
   fillSecondArray(arr,temp,100);
   i = findMissingElement(temp,100);
   printf("The missing element is %d\n",i);
}

    
6. Write a function for matrix multiplication

When you multiply two matrices A and B, each element of product C will be obtained by Ci,j= ΣAi,k*Bk,j

e.g. C[0,0] = A[0,0]*B[0,0]+A[0,1]*B[1,0]+A[0,2]*B[2,0]+....+A[0,n]*B[n,0]
void multiplication(int a[][10],int b[][10],int prod[][10],int r1,int c1,int r2,int c2)
{
    int i,j,k;
/* Initializing elements of product  matrix  to 0.*/
    for(i=0; i<r1; ++i)
    for(j=0; j<c2; ++j)
    {
       prod[i][j]=0;
    }
/* Multiplying matrix a and b and storing in array mult. */
    for(i=0; i<r1; ++i)
    for(j=0; j<c2; ++j)
    for(k=0; k<c1; ++k)
    {
        prod[i][j]+=a[i][k]*b[k][j];
    }
}
7. Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Return count of such pairs.
Example k=4 and a[]={7,623,19,10,11,9,3,15}
Output should be : 6
Pairs can be: 7,11 7,3 6,10 19,23 15,19 15,11

 int find_pairs(int arr[],int size,int k)
 {
     int i,j;
     int count = 0;
     for(i=0;i<size;i++)
        for(j=i+1;j<size;j++)
          {
              int diff = arr[i]-arr[j];
              if (abs(diff)==k)
                  count++;
           }
     return count;
 }

8. Given two sorted arrays, A and B, write a method to merge the elements of B into A in sorted order. Assume A has a large enough buffer at the end to hold all of B’s elements.

 #include<stdio.h>
void read_array(int arr[],int size)
{
    int i;
    for(i=0;i<size;i++)
      scanf("%d",&arr[i]);
}
/*s1 is size of arr1, s2 is size of arr2*/
void merge_arrays(int arr1[],int s1,int arr2[],int s2)
{
     int i,j; i=j=0;
     int temp[100];
     int k=0;
     while (i<s1 && j<s2)
     {
          if(arr1[i]<arr2[j])
              temp[k++]=arr1[i++];
          else
              temp[k++]=arr2[j++];
     }
     while(i<s1)
         temp[k++]=arr1[i++];
     while(j<s2)
         temp[k++]=arr2[j++];
     /*now copy back to arr1*/
     for(i=0;i<k;i++)
        arr1[i]=temp[i];

}
int main()
{
   int arr1[50],arr2[20];
   int i,num;
   int size1,size2;
   int k;

   printf("The size of array 1 is ");
   scanf("%d",&size1);
   printf("The size of array 2 is ");
   scanf("%d",&size2);
   read_array(arr1,size1);
   read_array(arr2,size2);
   merge_arrays(arr1,size1,arr2,size2);
   for(i=0;i<size1+size2;i++)
   {
     printf("arr1[%d]=%d\n",i,arr1[i]);
   }
   return 0;
} 
9. In an array of integers, every element appears twice except for one. Find this element which is not repeated.
Note:Your algorithm should have a linear runtime complexity. O(n) Could you implement it without using extra memory?

When you exor and array element a[i] with a[j] when both of them have same value, they cancel out and give a result of 1. Which means that when you exor all the elements, all of them cancel out except for the unique element. So the final result of this exor will be the element which is not a duplicate.

int find_unique_element(int arr[],int size)
 {
    int exor_prod=arr[0];
    int i;
    for(i=1;i<size;i++)
       exor_prod = exor_prod^arr[i];
    return exor_prod;
 }
10. Find the count k by which array has been rotated in a rotated sorted array.

For example we have a sorted array as 2,3,6,12, 15, 18. Now suppose the array is rotated k times such that array becomes 15, 18,2,3,6,12 We have to find K (in this case k is 4)

Let us the array is rotated once. Then arr[0] will be arr[n-1]- the last element which is also largest element. And arr[1] will become arr[0] - smallest element. So, arr[0]>arr[1].

If instead the array is rotated twice, last two elements will be moved 0th and 1st positions, followed previous arr[0], arr[1] etc. In this case, arr[1]>arr[2].

When arr[i]>arr[i+1], i is the number of times array is rotated.

int find_k(int *arr,int sz)
 {
     int i;
     for(i=0;i<sz-1;i++)
     {
        if(arr[i]>arr[i+1])
           return i+1;
     }
     return 0;
 

}
11. Point out the error/s in the program
#include<stdio.h>

int main()
{
    int a[] = {10, 20, 30, 40, 50};
    int j;
    for(j=0; j<5; j++)
    {
        printf("%d\n", *a);
        a++;
    }
    return 0;
}

Compilation error
lvalue required for increment operator
An array name is a constant pointer to the first element of the array. It is not an lvalue. Which means it can not be incremented. Hence a++ will throw an error.

12. What is the difference between &a and &a[0]?

&a is pointer to the array. &a[0] is the address of first element of array. It is a int pointer if a is array of int, char pointer if a is array of char etc.

Both give same numerical value. But in expressions they behave differently.


&a + 1 = address of a +(number of elements in a *size of element) . It points to next array.

&a[0] + 1 = address of a + 1 *size of element. This points to next element in the array that is &a[1]

13. Write a function to find all pairs in array of integers whose sum is equal to given number n

int find_pairs(int *arr,int size,int sum,int *arr2)
{
     int i,j;
     int k=0;
     for(i=0;i<size;i++)
        {
           int n1 = arr[i];
           for(j=i+1;j<size;j++)
               {
                  if(n1+arr[j]==sum)
                    {
                        arr2[k]=n1;
                        arr2[k+1]=arr[j];
                        k+=2;
                        break;
                     }
                 }
           }
       return k;
}

int main()
{
    int arr[20],pairs[20];
    int len,sum;
    int i,k;
    printf("len=");
    scanf("%d",&len);
    for(i=0;i<len;i++)
       scanf("%d",&arr[i]);
    printf("Sum = ");
    scanf("%d",&sum);
    k = find_pairs(arr,len,sum,pairs);
    for(i=0;i<k;i+=2)
       printf("%d %d\t ",pairs[i],pairs[i+1]);
}
14. Write a function to find first element of an array which is not present in second array. Arrays are of different sizes.

#include<stdio.h>
#define MAX 30
//returns index of n in the array arr, -1 if n is not present
int indexOf(int n,int *arr,int len)
{
   int i;
   for(i=0;i<len;i++)
      if(arr[i]==n)
         return i;
    return -1;
}
int not_common_element(int *arr1,int len1,int *arr2,int
len2)
{
     int i;
     for(i=0;i<len1;i++)
     {
     /*if arr1[i] is not present in arr2, return arr1[i]*/
        if(indexOf(arr1[i],arr2,len2)==-1)
             return arr1[i];
     }       
     return -1;
}
int main()
{
   int arr1[MAX],arr2[MAX];
   int el; int len1,len2,i;
   printf("Size of first array:");
   scanf("%d",&len1);
   printf("Size of second array:");
   scanf("%d",&len2);
   printf("First array elements:");
   for(i=0;i<len1;i++)
     scanf("%d",&arr1[i]);
   printf("Second array elements:");
   for(i=0;i<len2;i++)
     scanf("%d",&arr2[i]);

   el= not_common_element(arr1,len1,arr2,len2);
   if(el==-1)
      printf("All elements of first array are present in second array");
   else
      printf("%d is not present in second array ",el);
   return 0;
}
15. Write a function to check if an array is in ascending order and return the number of elements which are out of order

#include<stdio.h>
int read_array(int *arr)
{
   int len;
   int i;
   printf("Enter size of array:");
   scanf("%d",&len);
   for(i=0;i<len;i++)
      scanf("%d",&arr[i]);
   return len;
}
int out_of_order(int *arr,int len)
{
    int i;
    int count = 0;
    for(i=0;i<len-1;i++)
      if(arr[i]>arr[i+1])
         count++;
/*count is number of out of order elements*/
    return count;
}
int main()
{
   int arr[20];
   int len;
   int num;
   len = read_array(arr);
   num= out_of_order(arr,len);
   if(num==0)
        printf("Array is in ascending order\n");
   else
        printf("The number of elements out of order is %d\n",num);
   return 0;
}
16. Given an array, write a program to find two elements whose difference is closest to zero.

#include<stdio.h>
int read_array(int *arr);
void diff_closest_to_0(int *arr,int n,int*aptr,int*bptr);
int main()
{
   int arr[30];
   int el1,el2;
   int len = read_array(arr);
    diff_closest_to_0(arr,len,&el1,&el2);
   printf("the elements are %d and %d\n",el1,el2);
   return 0;
}
int read_array(int *arr)
{
   int len;
   int i;
   printf("Enter size of array:");
   scanf("%d",&len);
   for(i=0;i<len;i++)
      scanf("%d",&arr[i]);
   return len;
}
void diff_closest_to_0(int *arr,int n,int *aptr,int *bptr)
{
      int i,j;
      int zr_sum=10000;
      int a,b;
      for(i=0;i<n;i++)
         for(j=0;j<n;j++)
            {
               if(i==j)
                 continue;
               int diff = arr[i]-arr[j];
               if(abs(diff)<abs(zr_sum))
                   {
                      a = arr[i];
                      b = arr[j];
                      zr_sum = diff;
                    }
              }
       *aptr = a;
       *bptr = b;
}
  

The function diff_closeset_to_0() is unique because, it must return two array elements which produce the difference. As a function can return only one value, we are returning two pointers - aptr and bptr.

17. Write a function has_zero_diagonal which checks if a 5X5 integer matrix has all the elements in major diagonal as zero.

The function checks all diagonal elements for non-zero value and returns 0 if it finds any. If not, the function returns 1 - for true.
int has_zero_diagonal(int arr[][5])
{
     int i,j;
     for(i=0;i<5;i++)
         if(arr[i][i]!=0)
           return 0;
           /* if non zero diagonal element*/
     return 1;
}
18. Write a function to bubble sort an array.

In bubble sort, each element is compared with its next element and if out of order, the elements are swapped. This is continued for all elements. Once the first iteration is completed, the largest element sinks to bottom and smaller elements bubble up to the top.

In second iteration, the comparison and swapping is continued for n-1 elements and so on. There are totally n-1 iterations.

If none of the elements are swapped in an iteration, it indicates that all elements are already in order and does not need any more sorting. In this case, the loop stops.
void bubble_sort(int *arr,int n)
{
   int i,j;
   int swapped= 1;
   for(i=0;i<n-1  && swapped;i++)
     {
        swapped = 0;
        for(j=0;j<n-i-1 ; j++)
             if(arr[j+1]<arr[j])
                 {
                    int temp=arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    swapped = 1;
                  }
     }
}
19. Write a function to insert an element in a sorted array.

When we insert an element to a sorted array, we should insert it in the correct location. Which requires us to shift the elements greater than the new element, to the right.
void insert_element(int *arr,int n,int new_element)
{
    int i,j,location;
     /*find location where new element gets inserted*/
    for(i=0;i<n && arr[i]<new_element; i++)
    ;
    location = i;
    /*move elements to the right*/

       for(j=n;j>location;j--)
            arr[j]=arr[j-1];

    arr[location] = new_element;
    /*insert new element*/
}
20. Write a function to search an element in an unsorted array using linear search.

In linear search, the search-value is compared with all elements in the array from 0th to n-1th. When and if a match is found, the search is stopped.

The complexity of linear search is O(N).

For an unsorted small sized array, linear search is convenient algorith.
int linear_search(int *arr,int size,int n)
{
   int i;
   for(i=0;i<size ;i++)
       if(arr[i]==n)
         return i;
   return -1;
}
21. Write a function to search an element in a sorted array using binary search.

Binary search is an efficient search algorithm to search a sorted array. It finds the midpoint of the array and compares search value with middle element. Depending on whether the search value is larger than or smaller than the middle element, first half or the second half of the array are searched respectively.

Next midpoint of this sub-array is found, and its element is compared with search value.

This procedure is continued until either the value is found or the sub-array is empty - in which case search value is not present in the array.

Complexity of binary search is O(logn)
int binary_search(int *arr,int size,int n)
{
    int start = 0;int end=size-1;
    int mid = (end+start)/2;
    while( end>=start)
        {
           if(arr[mid]>n)
              end = mid-1;
           else if (arr[mid]<n)
              start = mid+1;
           else
             return mid;
           mid = (end+start)/2;
         }

    return -1;
}
22. Write a recursive function to search an element in a sorted array using binary search.

#include<stdio.h>
int binary_search(int *arr,int start,int end,int num)
{
    if(start>end)
      return -1;
    int mid = (start+end)/2;
    if(arr[mid]==num)
      return mid;
    else if(arr[mid]>num)
      return binary_search(arr,start,mid-1,num);
    else
      return binary_search(arr,mid+1,end,num);
 }
 
int main()
{
    int num;
    int array[] = {2,11,26,67,89,111,334,849};        
    printf("Enter a number");
    scanf("%d",&num); 
    if(binary_search(array,0,8,num)!=-1)
       printf("Element found");
    else
       printf("Element not found");
    return 0;
}
 
23. Write code to evaluate a polynomial

#include<stdio.h>
#include<math.h>
float evaluate(float x, int *coeffs,int size);
float power(float x,int i);
int main()
{
   int coeffs[5]={0};
   float x,sum=0;
   int i;
   printf("Enter co-effecients (-1 to end)");
   for(i=0;i<5;i++)
     {
       printf("x^%d * ",i);
       scanf("%d",&coeffs[i]);
       if(coeffs[i]==-1)
        {
           coeffs[i]=0;
           break;
         }
      }
   printf("What is value of x");
   scanf("%f",&x);
   sum = evaluate(x,coeffs,5);
   printf("for x = %.2f equation has value %.2f\n",x,sum);
   return 0;
}

float evaluate(float x, int *coeffs,int size)
{
   int i;
   float s = 0;
   for(i=0;i<size;i++)
     s+= coeffs[i]*pow(x,i);
   return s;
}
      
24. Write a program to add two polynomials.

#include<stdio.h>
#include<stdlib.h> 
void print_polynomial(int *coeff,int size);
int* add_polynomial(int *coeff1,int *coeff2,int order);
void read_polynomial(int *coeffs,int size)
{
   int i;
   printf("Enter co-effecients (-1 to end)");
   for(i=0;i<size;i++)
     {
       printf("x^%d * ",i);
       scanf("%d",&coeffs[i]);
       if(coeffs[i]==-1)
        {
           coeffs[i]=0;
           break;
         }
      }
}
int main()
{
   int coeff1[10],coeff2[10];
   int *coeff3;
   float x,sum=0;
   int order;
   int i;
   printf("What is highest order of eqns");
   scanf("%d",&order);
   printf("First equation");
   read_polynomial(coeff1,order);
   printf("Second equation");
   read_polynomial(coeff2,order);
   coeff3 = add_polynomial(coeff1,coeff2,order);
   print_polynomial(coeff3,order);
   return 0;
}
float power(float x,int i)
{
    if(i==0)
       return 1;
    else
       return x* power(x,i-1);
}

int* add_polynomial(int *coeff1,int *coeff2,int order)
{
    int i;
    int *temp = (int*)malloc(sizeof(int)*order);
    for(i=0;i<order;i++)
      temp[i] = coeff1[i]+coeff2[i];
    return temp;
}

void print_polynomial(int *coeff,int order)
{
   int i;
   printf("The equation is");
   for(i=order-1;i>0;i--)
      if(coeff[i]==0)
        continue;
      else if(i>1) printf("%dx^%d+",coeff[i],i);
      else printf("%dx+",coeff[i]);
   printf("%d",coeff[0]);
}

      
25. Write a program to find a prime number after a given prime number.

#include<stdio.h>

int is_prime(int n,int primearray[])
{
     int i;
     for(i=0;i<400 && primearray[i]>0;i++)
        if((n% primearray[i]) == 0)
           return 0;
     printf("%d ",n);
     return 1;
}

int main()
{
     int l_prime;int i;
     int prime_arr[400]={2};int p=1;
     printf("Prime number after which number:");
     scanf("%d",&l_prime);
     /* fill the prime array */

    /* store all primes till l_prime in array*/
     for(i=3;i<=l_prime;i+=2)
       if(is_prime(i,prime_arr))
           prime_arr[p++]=i;
      
    /* find next one prime number*/
     while(!is_prime(i++,prime_arr));

     printf("Prime number after %d is %d",l_prime,i-1);
     return 0;
}
26. Write a program to merge two sorted arrays in sorted order avoiding duplicates.

To merge two sorted arrays A and B, each a[i] is compared with b[j] and smaller of these two is added to C and its index is incremented. This process is continued until we reach the end of one of the arrays. Next all the elements of the remaining array is added to C.

To avoid duplicates, if both elements are equal, one index is incremented and that value is skipped.
#include<stdio.h>
void shift_elements(int arr[],int size,int k)
{
     int i;
     for(i=size-1;i>=k;i--)
       arr[i+1]= arr[i];
}
int merge_arrays(int arr1[],int s1,int arr2[],int s2)
{
     int i,j; i=j=0;
     while(i<s1 && j<s2)
     {
       if(arr2[j]==arr1[i])
           j++;
       else if(arr2[j]<arr1[i])
       {
          shift_elements(arr1,s1,i);
          arr1[i]=arr2[j++];s1++;
       }
       else{
           i++;
       }
      }
      if(j<s2)
      {
         for(;j<s2;j++)
           {
               arr1[i++]=arr2[j];
            }
      }
      return i;/*return final size of array*/
}
void print(int *arr,int n)
{
   int i;
   for( i=0;i<n;i++)
      printf("%d ",arr[i]);
}
int main()
{
    int a1[]={11,33,44,55,66};
    int a2[]={1,11,111,1111};
    merge_arrays(a1,5,a2,4);
    print(a1,9);
    return 0;
}
27. Write a program to check if a given matrix is an identity matrix.

A matrix is identity matrix if all the major diagonal elements are 1 and all the other elements are 0

int is_identity(int arr[][10],int nr)
{
     int i,j;

     for(i=0;i<nr;i++)
        for(j=0;j<nr;j++)
           if(i==j)
             {
              if(arr[i][j]!=1)
                 return 0;
              }
           else
              if(arr[i][j]!=0)
                 return 0;
     return 1;
}
28. Write a function that swaps the first half of an array with the second half. Within each half of the array, keep the elements in their original order.

If the array is [2,3,4,6,7,8] ,after swapping it must become
[6,7,8,2,3,4]

#include<stdio.h>
#define MAX 30
void swap_elements(int *arr,int size)
{
   int i,j;
   int mid = size/2;
   
   if(size&1) mid= mid+1;
   for(i=0,j=mid;i<mid&&j<size;i++,j++)
   {
      if(i==j) continue;
      int temp = arr[i];
      arr[i]=arr[j];
      arr[j]=temp;
    }
}
int main()
{
   int arr[MAX];
   int i;int len;
   printf("Size of array:");
   scanf("%d",&len);
   printf("Array elements:");
   for(i=0;i<len;i++)
     scanf("%d",&arr[i]);
   swap_elements(arr,len);
   for(i=0;i<len;i++)
      printf("%d ",arr[i]);
   return 0;
}
29. Write a function to determine if the given 3X3 matrix is triangular or not.
A matrix is upper triangular if every element below the diagonal is 0.
A matrix is lower triangular if every element above the diagonal is 0. Your program should test whether the matrix is either of these two.

We are writing two functions is_lower_tri() which checks whether all the elements above the principal diagonal are zero and is_upper_tri() which checks whether all the elements below the principal diagonal are 0.
#include<stdio.h>
int is_lower_tri(int arr[][3])
{
   int i,j;
   for(i=0;i<3;i++)
     for(j=i+1;j<3;j++)
        if(arr[i][j]!=0)
           return 0;
   return 1;
}
int is_upper_tri(int arr[][3])
{
   int i,j;
   for(i=0;i<3;i++)
     for(j=0;j<i;j++)
        if(arr[i][j]!=0)
           return 0;
   return 1;
}
int main()
{
   int mat[3][3];
   int i,j;
   for(i=0;i<3;i++)
    for(j=0;j<3;j++)
     scanf("%d",&mat[i][j]);

   if(is_upper_tri(mat))
      printf("The matrix is upper triangular");
   else if (is_lower_tri(mat))
     printf("The matrix is lower triangular matrix");
   else
     printf("The matrix is not triangular matrix");

  return 0;
}
30. Write a program to print the frequency of even and odd numbers in a matrix.

#include<stdio.h>
#define NC 3
#define NR 3
void freq(int mat[][NC] )
{
    int neven = 0;
    int nodd = 0;
    int i,j;
    for(i=0;i<NR;i++)
     for(j=0;j<NC;j++)
        if(mat[i][j]%2==0)
           neven ++;
        else
           nodd++;
     printf("Number of even elements is %d\n",neven);
     printf("Number of odd elements is %d\n",nodd);
}
int main()
{
    int mat[NR][NC];
    int i,j;
    printf("Enter the elements of matrix:");    
    for(i=0;i<NR;i++)
      for(j=0;j<NC;j++)
         scanf("%d",&mat[i][j]);
    freq(mat);
    return 0;
}
31. Write a program to find transpose of given square matrix

Transpose of a matrix is obtained by flipping the matrix over its principal diagonal. Every a[i,j] is swapped with a[j,i].
#include<stdio.h>
#define N  3 
void swap(int *p1,int *p2)
{
   int temp = *p1;
   *p1 = *p2;
   *p2 = temp;
}
void transpose(int mat[][N] )
{
    
    int i,j;
    for(i=0;i<N;i++)
      for(j=i+1;j<N;j++)
       if(i!=j)
        swap(&mat[i][j],&mat[j][i]);          
}
int main()
{
    int mat[N][N];
    int i,j;
    printf("Enter the elements of matrix:");    
    for(i=0;i<N ;i++)
      for(j=0;j<N ;j++)
         scanf("%d",&mat[i][j]);
  transpose(mat);
  for(i=0;i<N ;i++)
   {
      for(j=0;j<N ;j++)
         printf("%d ",mat[i][j]);
      printf("\n");
    }
    return 0;
}
32. What is an array? How do you define an array in C?

An array is a collection of similar items with a common name e.g. an array of integers, an array of characters, an array of structures.

Each element of the array is accessed with array name and its index.e.g. num[0], a1[2]

In C, an array definition must specify its name, type of its elements and its size. Size is enclosed in square brackets.

The initial values of elements can be specified optionally.
Syntax

    data-type   name[size]; 
e.g.
   int arr[10];   
   float arr2[5];
   char arr3[12];

In the above examples, arr is an array of 10 integers. arr2 is an array of 5 floating point numbers. and arr3 is an array of 12 characters.

Initial values if specified, must be enclosed in curly brackets. If initializers are specified, array size need not be given.
int a1[4]={11,22,33,44};
int a2[]={1,3,4,5};
Size of a2 is 4.

Initializer can specify partial values. In which case rest of values are taken as zero.
int a1[10]={11};

In the above example, a1[0] is 11 and a1[1] to a1[9] are all 0.

33. Can an array initializer specify only an intermediate value? If yes, how?

Yes.

To initialize a specific element, the index of the element has to be given in square brackets followed by value.

float arr[10]={[3]=9.1};

Here arr[3] is initialized to 9.1 and rest of elements are all set to 0

34. What does the following code print?
    int arr[10]={1,2,3,4};
    printf("%d",arr);

It prints the address of 0th element of the array. Array name always refers to base address of array.

35. What are the valid indices for an array of size 10?

Valid indices for array of size 10 are 0 to 9.

In C, an array index starts with 0 and ends with size-1.

36. How do you define a two dimensional array of 3 rows and 4 columns and has integer elements?

A two dimensional array is defined with its number of rows and number of columns in two pairs of square brackets.

 
    data-type name[nr][nc];
    e.g.

int mat[4][5];