Single and Multi Dimensional Arrays

Arrays in C

An array is a collection of data items, all of the same type, accessed using a common name.

  • A one-dimensional array is like a list (vector).

  • A two-dimensional array is like a table (matrix).

  • Arrays can also have more dimensions.

Memory Characteristics

  • Array elements are stored in contiguous (adjacent) memory locations.

  • Elements can be randomly accessed.

  • The address of each element can be calculated using:

    • Base address

    • Size of each data element


Declaring Single Dimensional Arrays

Array variables are declared like normal variables, except:

  • The variable name is followed by square brackets [ ]

  • The brackets contain the array dimension (size)

Rules

  • Dimensions must be positive integers or constant expressions.

  • In C99, variables may be used as sizes if they hold a positive value at declaration.

  • Memory is allocated only once when declared.

  • Array size does not change later, even if the variable used changes.


Examples

int A[10]; float F[1000]; char S[100]; const int N = 100; int list[N];

C99 Variable Length Array Example

int n; printf("How big an array do you want? "); scanf("%d", &n); if(n <= 0) { printf("Error - Quitting\n"); exit(0); } double data[n]; // Works only in C99

Initializing Arrays

Arrays can be initialized at the time of declaration.

  • Use curly braces {}

  • Separate values with commas

  • Initialization may be partial

  • Remaining elements automatically become 0

If the array is fully initialized, the size can be omitted.
The compiler will automatically determine the size.


Examples

int A[6] = {1, 2, 3, 4, 5, 6}; float F[100] = {1.0f, 5.0f, 20.0f}; double F[] = {3.141592654, 1.570796327, 0.785398163};

Note: Array size can be omitted when initializing a single-dimensional array.


Initializing Specific Elements Using Index

You can assign values to particular elements using their index.

A[10] = 100;
  • Initializes the 11th element to 100

  • Remember: Array indexing starts from 0


Initializing Arrays After Declaration

Arrays can also be initialized later using assignments:

int A[5]; A[0] = 10; A[1] = 20;

Designated Initializers (C99 Feature)

C99 provides designated initializers, allowing you to initialize specific positions.

  • Elements need not start from index 0

  • Can be mixed with normal initialization

  • Order does not matter

  • Uninitialized elements become 0


Example

int numbers[100] = {1, 2, 3, [10] = 10, 11, 12, [60] = 50, [42] = 420};

Explanation

  • numbers[0] = 1

  • numbers[1] = 2

  • numbers[2] = 3

  • numbers[10] = 10 → 11th element

  • Next values:

    • numbers[11] = 11

    • numbers[12] = 12

  • numbers[60] = 50

  • numbers[42] = 420

  • All other elements = 0

If array size is not specified, the compiler sets the size based on the largest initialized index.




Using Arrays in C

  • Elements of an array are accessed by specifying the index (offset) of the desired element inside square brackets [ ] after the array name.


Array Subscripts

  • Array subscripts must be of integer type:

    • int

    • long int

    • char

    • or other integer-compatible types


Important Rule About Indexing

VERY IMPORTANT:

  • Array indices in C start at 0.

  • They go up to size − 1.

Example

For a 5-element array:

Indices0, 1, 2, 3, 4

Reason

  • The index represents an offset from the beginning of the array.

  • The first element is at the beginning → offset = 0


Common Mistake (Landmine)

⚠ The most common mistake in C arrays is:

  • Forgetting that indexing starts from 0

  • Forgetting that the last index is one less than the array size


Arrays with Loops

  • Arrays are commonly used with loops

  • This helps perform the same operation on:

    • all elements, or

    • part of the array


Examples

Updating an Array Element

A[0] = 12; // stores 12 in the 0th location

Accessing an Array Element

printf("%d", A[2]); // prints the 3rd element of the array





Advantages and Disadvantages of Arrays in C

Advantages of Arrays in C

  1. Random Access
    Elements can be accessed directly using the array index.

  2. Less Code
    A single array can store multiple elements, reducing the number of variables and lines of code.

  3. Easy Element Access
    All elements can be accessed easily using their indices.

  4. Easy Traversal
    Traversing the array becomes simple using one loop.

  5. Easy Searching and Sorting
    Searching and sorting operations are easier since they can be implemented with fewer lines of code.


Disadvantages of Arrays in C

  1. Fixed Size
    Arrays allow only a fixed number of elements, decided at declaration time.
    Unlike a linked list, arrays in C are not dynamic.

  2. Costly Insertion and Deletion
    Adding or removing elements is expensive because:

    • Elements must be shifted, or

    • Memory must be reorganized.

    Sample Programs Using 1-D Arrays

     
     The first sample program uses loops and arrays to calculate the first twenty Fibonacci numbers.
    /* Program to calculate the first 20 Fibonacci numbers. */
    #include <stdlib.h>
    #include <stdio.h>
    int main( void )
    {
    int i, fibonacci[ 20 ];
    fibonacci[ 0 ] = 0;
    fibonacci[ 1 ] = 1;
    for( i = 2; i < 20; i++ )
    fibonacci[ i ] = fibonacci[ i - 2 ] + fibonacci[ i - 1 ];
    for( i = 0; i < 20; i++ )
    printf( "Fibonacci[ %d ] = %f\n", i, fibonacci[ i ] );
    } /* End of sample program to calculate Fibonacci numbers */ 



    Program to read n numbers and find the largest using array(University Question)
    #include <stdlib.h>
    #include <stdio.h>
    int main( void )
    {
    int i, n,a[100],large;
    printf("enter...n\n”);
    scanf(“%d”,&n);
    printf(“Enter the elements\n”);
    for( i = 0; i < n; i++ )
    scanf(“%d”,&a[i]);
    large=a[0];
    f or( i = 1; i < n; i++ )
    if (a[i]>large) large=a[i]
    printf( "Largest Element in the array is %d”,large);
    }

    Write a C program to find the second largest element in an array

    #include <stdio.h>

    int main() {
        int n, i;
        int largest, secondLargest;

        printf("Enter number of elements: ");
        scanf("%d", &n);

        int arr[n];

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

        // Initialize
        largest = secondLargest = -2147483648;  // Minimum int value

        // Find largest and second largest
        for (i = 0; i < n; i++) {
            if (arr[i] > largest) {
                secondLargest = largest;
                largest = arr[i];
            } else if (arr[i] > secondLargest && arr[i] < largest) {
                secondLargest = arr[i];
            }
        }

        if (secondLargest == -2147483648) {
            printf("Second largest element does not exist.\n");
        } else {
            printf("Second largest element is: %d\n", secondLargest);
        }

        return 0;
    }

    A set of N numbers are stored in an integer array. Write a C program to find the sum of odd numbers present in the array. ( University Question)

    #include <stdio.h>

    int main() {
        int arr[100], n, i, sum = 0;

        printf("Enter the number of elements (N): ");
        scanf("%d", &n);

        printf("Enter %d numbers:\n", n);
        for (i = 0; i < n; i++) {
            scanf("%d", &arr[i]);
        }

        // Calculate sum of odd numbers
        for (i = 0; i < n; i++) {
            if (arr[i] % 2 != 0) {
                sum += arr[i];
            }
        }

        printf("Sum of odd numbers = %d\n", sum);

        return 0;
    }


    Merging two sorted arrays
    #include <stdio.h>
    int main()
    {
      int a[100],b[100],c[100],i,j,k,n,m;
      printf("Enter the number of elements in array a:");
      scanf("%d",&n);
      printf("Enter the array elements in sorted order....\n");
      for(i=0;i<n;i++)
        scanf("%d",&a[i]);
      printf("Enter the number of elements in array b:");
      scanf("%d",&m);
      printf("Enter the array elements in sorted order....\n");
      for(i=0;i<m;i++)
        scanf("%d",&b[i]);
      for(i=0,j=0,k=0;i<n&&j<m;k++)
      {
       if(a[i]<b[j])
           c[k]=a[i++];
       else   
          c[k]=b[j++];
       }
       while(i<n) c[k++]=a[i++];
       while(j<m) c[k++]=b[j++];
       printf("The merged array is...\n");
       for(i=0;i<k;i++)
         printf("%d\n",c[i]);
    }

    Write a C program to find the occurrence of each element in an array.(uq)
     #include <stdio.h>   
             
        int main()    
        {    
            //Initialize array     
            int arr[50];    
            int n,i,j,count;  
            //Array fr will store frequencies of element    
            int fr[50];    
            int visited = -1;   // -1 indcated element already considered
            printf("Enter n \n");
            scanf("%d",&n);
            printf("Enter elements\n");
            for(i=0;i<n;i++)
            scanf("%d",&arr[i]);
            for( i = 0; i < n; i++){    
                 count = 1;    
                for(j = i+1; j < n; j++)
                {    
                    if(arr[i] == arr[j]){    
                        count++;    
                        //To avoid counting same element again    
                        fr[j] = visited;    
                    }    
                }    
                if(fr[i] != visited)    
                    fr[i] = count;    
            }    
                
            //Displays the frequency of each element present in array    
            printf("---------------------\n");    
            printf(" Element | Frequency\n");    
            printf("---------------------\n");    
            for(int i = 0; i < n; i++){    
                if(fr[i] != visited){    
                    printf("%5d", arr[i]);    
                    printf("    |  ");    
                    printf("%5d\n", fr[i]);    
                }    
            }    
            printf("---------------------\n");    
            return 0;    
        }    

    Linear Search 
    #include <stdio.h>
    void main()
    {
    int arr[50],key,i,n,flag=0;
    printf("Enter the number of elements n<=50\n");
    scanf("%d",&n);
    printf("Enter %d elements\n",n);
    for(i=0;i<n;i++)
    {
    scanf("%d",&arr[i]);
    }
    printf("Enter a key element to search\n");
    scanf("%d",&key);
    for(i=0;i<n;i++)
    {
    if(arr[i]==key)
    {
    flag=1;
    break;
    }
    }
    if(flag==1)
    printf("%d is found in the list, at position %d\n",key,i+1);
    else
    printf("%d is not in the list\n",key);

    }
     
    Write a C program to check if a number is present in a given list of numbers. If present, give location of the number otherwise insert the number in the list at the end.(uq)
    #include <stdio.h>
    main()
    {
    int arr[51],k,i,n,flag=0;
    printf("Enter the number of elements n<50\n");
    scanf("%d",&n);
    printf("Enter %d elements\n",n);
    for(i=0;i<n;i++)
    {
    scanf("%d",&arr[i]);
    }
    printf("Enter a number to be search\n");
    scanf("%d",&k);
    for(i=0;i<n;i++)
    {
    if(arr[i]==k)
        {
        flag=1;
        break;
        }
    }
    if(flag==1)
        printf("%d is found in the list, at position %d\n",k,i+1);
    else
        {printf("%d is not in the list\n",k);
         printf("element is inserted at end...\n");
         arr[n]=k;
         for(i=0;i<=n;i++)
         printf("%3d",arr[i]);
        }

    Bubble sort
    #include <stdio.h>
    void main()
    {
    int arr[50],i,j,n,exchng,temp;
    printf("Enter the number of elements n<=50\n");
    scanf("%d",&n);
    printf("Enter %d elements\n",n);
    for(i=0;i<n;i++)
        scanf("%d",&arr[i]);

    for(i=0;i<n-1;i++)
    {exchng=0;
    for(j=0;j<n-1-i;j++)
    {
        if (arr[j]>arr[j+1])
        {
        temp=arr[j];
        arr[j]=arr[j+1];
        arr[j+1]=temp;
        exchng=1;
        }
    }
    if(exchng==0) break;
    }
    printf("Sorted List...\n");
    for(i=0;i<n;i++)
        printf("%d\n",arr[i]);
    }
    A set of N numbers are stored in an array. Write a C program to arrange the numbers in descending order using bubble sort algorithm. ( University Question)
    #include <stdio.h>
    void main()
    {
    int arr[50],i,j,n,exchng,temp;
    printf("Enter the number of elements n<=50\n");
    scanf("%d",&n);
    printf("Enter %d elements\n",n);
    for(i=0;i<n;i++)
        scanf("%d",&arr[i]);

    for(i=0;i<n-1;i++)
    {exchng=0;
    for(j=0;j<n-1-i;j++)
    {
        if (arr[j]<arr[j+1])
        {
        temp=arr[j];
        arr[j]=arr[j+1];
        arr[j+1]=temp;
        exchng=1;
        }
    }
    if(exchng==0) break;
    }
    printf("Sorted List...\n");
    for(i=0;i<n;i++)
        printf("%d\n",arr[i]);
    }

    Finding the unique and duplicate element in array 
    #include <stdio.h>
    void main()
    {
    int arr[50],i,j,n,exchng,temp,c;
    printf("Enter the number of elements n<=50\n");
    scanf("%d",&n);
    printf("Enter %d elements\n",n);
    for(i=0;i<n;i++)
    scanf("%d",&arr[i]);
    for(i=0;i<n-1;i++)
    {exchng=0;
    for(j=0;j<n-1-i;j++)
    {
    if (arr[j]>arr[j+1])
    {
    temp=arr[j];
    arr[j]=arr[j+1];
    arr[j+1]=temp;
    exchng=1;
    }
    }
    if(exchng==0) break;
    }
    printf("Sorted List...\n");
    for(i=0;i<n;i++)
    printf("%d\n",arr[i]);
    // finding duplicate elements
    for(i=0;i<n;i+=c)
    {c=1;
    for(j=i+1;j<n;j++)
    if(arr[i]==arr[j]) c++;
    if(c>1) printf("%d is duplicate...occures %d times\n",arr[i],c);
    else printf("%d is unique\n",arr[i]);
    }
    }

    Write a program to count how many times each digit (0–9) occurs in a given number.
    #include <stdio.h>

    int main() {
        long long number;
        int count[10] = {0};
        int digit;

        printf("Enter a number: ");
        scanf("%lld", &number);

        /* Handle case when number is 0 */
        if (number == 0) {
            count[0] = 1;
        }

        /* Count digit occurrences */
        while (number != 0) {
            digit = number % 10;
            count[digit]++;
            number /= 10;
        }

        /* Display results */
        printf("\nDigit occurrences:\n");
        for (digit = 0; digit <= 9; digit++) {
            if (count[digit]!=0) printf("Digit %d occurs %d time(s)\n", digit, count[digit]);
        }

        return 0;
    }


    Write a C program to reverse the content of an array without using another array.(uq)
    #include <stdio.h>
    void reverseArray(int arr[], int size) {
        int start = 0, end = size - 1;
        while (start < end) {
            // Swap elements
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            
            // Move pointers
            start++;
            end--;
        }
    }

    int main() {
        int arr[] = {1, 2, 3, 4, 5};
        int size = sizeof(arr) / sizeof(arr[0]);

        printf("Original array: ");
        for (int i = 0; i < size; i++) {
            printf("%d ", arr[i]);
        }

        reverseArray(arr, size);

        printf("\nReversed array: ");
        for (int i = 0; i < size; i++) {
            printf("%d ", arr[i]);
        }

        return 0;
    }

    Write a C program to rotate (re-insert rightmost element at the left) elements of an array to the right by n-steps. ( uq)
    #include <stdio.h>
    void rotateRight(int arr[], int size, int steps) {
        for (int i = 0; i < steps; i++) {
            int last = arr[size - 1];  // Store the last element

            // Shift elements to the right
            for (int j = size - 1; j > 0; j--) {
                arr[j] = arr[j - 1];
            }

            arr[0] = last;  // Place the last element at the beginning
        }
    }

    int main() {
        int arr[] = {1, 2, 3, 4, 5};
        int size = sizeof(arr) / sizeof(arr[0]);
        int steps = 2;  // Number of steps to rotate

        printf("Original array: ");
        for (int i = 0; i < size; i++) {
            printf("%d ", arr[i]);
        }

        rotateRight(arr, size, steps);

        printf("\nRotated array: ");
        for (int i = 0; i < size; i++) {
            printf("%d ", arr[i]);
        }

        return 0;
    }
    Write a C program to insert a new element into an existing array at a given position, shift the remaining elements accordingly and print the new array ( university question)

    #include <stdio.h>

    int main() {
        int arr[100], n, i, pos, value;

        printf("Enter the number of elements in the array<100: ");
        scanf("%d", &n);

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

        printf("Enter the position to insert the new element (1 to %d): ", n + 1);
        scanf("%d", &pos);

        // Validate position
        if (pos < 1 || pos > n + 1) {
            printf("Invalid position!\n");
            return 1;
        }

        printf("Enter the value to insert: ");
        scanf("%d", &value);

        // Shift elements to the right
        for (i = n; i >= pos; i--) {
            arr[i] = arr[i - 1];
        }

        // Insert the new element
        arr[pos - 1] = value;
        n++; // Increase the size

        printf("Array after insertion:\n");
        for (i = 0; i < n; i++) {
            printf("%d ", arr[i]);
        }
        printf("\n");

        return 0;
    }

    Multidimensional Arrays

    Multi-dimensional arrays are declared by providing more than one set of square [ ] brackets after the variable name in the declaration statement.

    One dimensional arrays do not require the dimension to be given if the array is to be completely initialized. By analogy, multi-dimensional arrays do not require the first dimension to be given if the array is to be completely initialized. All dimensions after the first must be given in any case.

    For two dimensional arrays, the first dimension is commonly considered to be the number of rows, and the second dimension the number of columns.

    Two dimensional arrays are considered by C/C++ to be an array of single dimensional arrays.
    For example:

    • int numbers[5][6] refers to a single dimensional array of 5 elements, where each element is a single dimensional array of 6 integers.

    • By extension, int numbers[12][5][6] refers to an array of 12 elements, each of which is a two dimensional array.

    Another way of looking at this is that C stores two dimensional arrays by rows, with all elements of a row stored together as a single unit. Knowing this can sometimes lead to more efficient programs.


    Initialization of Multidimensional Arrays

    Multidimensional arrays may be completely initialized by listing all data elements within a single pair of curly { } braces, as with single dimensional arrays.

    It is better programming practice to enclose each row within a separate subset of { } braces, to make the program more readable. This is required if any row other than the last is to be partially initialized.

    • When subsets of braces are used, the last item within braces is not followed by a comma.

    • The subsets themselves are separated by commas.

    Multidimensional arrays may be partially initialized by not providing complete initialization data. Individual rows of a multidimensional array may be partially initialized, provided that subset braces are used.


    Accessing Elements

    Individual data items in a multidimensional array are accessed by fully qualifying an array element.

    If data is a three dimensional array of floats:

    • data[1][2][5] → refers to a float

    • data[1][2] → refers to a one-dimensional array of floats

    • data[1] → refers to a two-dimensional array of floats

    These concepts relate to memory-management issues.


    Example: Declaring and Initializing 2D Arrays

    The two-dimensional array can be defined as an array of arrays.
    A 2D array is organized as a matrix (rows and columns).


    Declaration

    int A[3][5]; /* 3 rows by 5 columns */ const int NROWS = 10; const int NCOLS = 20; float matrix[NROWS][NCOLS];

    In a 1D array, we don't need to specify the size if declaration and initialization are done together.
    However, this does not work for 2D arrays — we must define at least the second dimension.


    Initialization

    int arr[2][3] = {{1,2,3},{4,5,6}}; int arr[2][3] = {1,2,3,4,5,6}; int arr[][3] = {1,2,3,4,5,6};

    Invalid Initializations

    int arr[][] = {1,2,3,4,5,6}; int arr[3][] = {1,2,3,4,5,6};

    Accessing Elements

    Elements are accessed using both row and column index.

    arr[2][1] = 10; // stores value in 3rd row, 2nd column printf("%d", arr[2][1]); // prints the same value

    (Indexing starts from 0.)


    Let’s consider a 2D array abc[5][4].
    The conceptual memory representation is shown below.




    Row major and column major order representation

    In computing, row-major order and column-major order are methods for storing multidimensional arrays in linear storage such as random access memory.

    The difference between the orders lies in which elements of an array are contiguous in memory. In row-major order, the consecutive elements of a row reside next to each other, whereas the same holds true for consecutive elements of a column in column-major order.
     
    Example

    Sample Program Using 2-D Arrays


    Write a  C program to initialize a 3x3 matrix and  display its diagonal elements separately.

    #include <stdio.h>
    int main() {
        int matrix[3][3] = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Print the matrix (optional)
        printf("The 3x3 matrix is:\n");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                printf("%d ", matrix[i][j]);
            }
            printf("\n");
        }

        // Print main diagonal
        printf("\nMain Diagonal: ");
        for (int i = 0; i < 3; i++) {
            printf("%d ", matrix[i][i]);
        }

        // Print secondary diagonal
        printf("\nSecondary Diagonal: ");
        for (int i = 0; i < 3; i++) {
            printf("%d ", matrix[i][2 - i]);
        }

        printf("\n");

        return 0;
    }
    Output:
    The 3x3 matrix is:
    1 2 3 
    4 5 6 
    7 8 9 

    Main Diagonal: 1 5 9 
    Secondary Diagonal: 3 5 7 

    Sum of the elements in each row of a matrix
    #include <stdio.h>
    void main()
    {
    int A[50][50],B[50][50],rsum;
    int r,c,m,n;
    printf("Enter the size of the matrix nof of rows,columns\n");
    scanf("%d%d",&m,&n);
    printf("Enter the elements of matrix A row by row\n");
    for(r=0;r<m;r++)
    for(c=0;c<n;c++)
    scanf("%d",&A[r][c]);
    //computing transpose
    for(r=0;r<m;r++)
    {rsum=0;
    for(c=0;c<n;c++)
    rsum=rsum+A[r][c];

    printf("Sum of elements in row %d=%d\n",r,rsum);
    }

    Transpose of a matrix A^T=B ( university question)
    #include <stdio.h>
    main()
    {
      int A[50][50],B[50][50];
      int r,c,m,n;
      printf("Enter the size of the matrix nof of rows,columns\n");
      scanf("%d%d",&m,&n);
      printf("Enter the elements of matrix A row by row\n");
      for(r=0;r<m;r++)
       for(c=0;c<n;c++)
        scanf("%d",&A[r][c]);
     //computing transpose
      for(r=0;r<m;r++)
       for(c=0;c<n;c++)
          B[c][r]=A[r][c];
        
      printf("The transpose of A is \n");
      for(r=0;r<n;r++)
       {
       for(c=0;c<m;c++)
         printf("%3d",B[r][c]);
        printf("\n");
        }
    }

    Adding two matrix sum=a+b ( university question)
    #include <stdlib.h>
    #include <stdio.h>
    int main( void )
    {
    int a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } };
    int b[ 2 ][ 3 ] = { { 1, 2, 3 }, { 3, 2, 1 } };
    int sum[ 2 ][ 3 ], row, column;
    /* First the addition */
    for( row = 0; row < 2; row++ )
    for( column = 0; column < 3; column++ )
    sum[ row ][ column ] =a[ row ][ column ] + b[ row ][ column ];
    /* Then print the results */
    printf( "The sum is: \n\n" );
    for( row = 0; row < 2; row++ ) {
        for( column = 0; column < 3; column++ )
             printf( "\t%d", sum[ row ][ column ] );
    printf( '\n' ); /* at end of each row */
    }
    return 0;
    }
    Multiply two matrix C=A*B ( university question)
    #include<stdio.h>
    int main(void)
    {
      int i,j,k,m,n,p,q,tot;
      int A[30][30], B[30][30], C[30][30];
      printf(" Please insert the number of rows and columns for first matrix \n ");
      scanf("%d%d", &m, &n);
      printf(" Insert your matrix elements : \n ");
      for (i= 0; i < m; i++)
        for (j = 0; j < n; j++)
          scanf("%d", &A[i][j]);
       printf("Please insert the number of rows and columns for second matrix\n");
      scanf("%d%d", &p, &q);
      if (n != p)
        printf(" Your given matrices cannot be multiplied with each other. \n ");
      else
      {
        printf(" Insert your elements for second matrix \n ");
         for (i= 0; i< p; i++)
          for (j= 0; j< q; j++)
            scanf("%d", &B[i][j] );
        for (i = 0; i < m; i++) {
          for (j = 0; j < q; j++) {
        tot=0;
            for (k = 0; k < p; k++) {
              tot = tot + A[i][k] * B[k][j];
            }
            C[i][j] = tot;
                 }
        }
         printf(" The result of matrix multiplication or product of the matrices is: \n ");
        for (i = 0; i < m; i++) {
          for (j = 0;j < q; j++)
            printf("%5d", C[i][j] );
          printf(" \n ");
        }
      }
      return 0;
    }

    Check whether the given matrix is diagonal ( university question)
    #include <stdio.h>
    int main(void)
    {
      int i,j,m,n,flag=1;
      int A[30][30];
      printf(" Please insert the number of rows and columns max 30 \n ");
      scanf("%d%d", &m, &n);
      printf(" Insert your matrix elements : \n ");
      for (i= 0; i < m; i++)
        for (j = 0; j < n; j++)
          scanf("%d", &A[i][j]);
     //checking for non diagonal ..all elements must be 0 
     
     for (i= 0; i < m; i++)
      {
        for (j = 0; j < n; j++)
          if(i!=j && A[i][j]!=0) {flag=0; break;}
         
        if(flag==0)  break;
      }       
      if(flag)
        printf("Diagonal Matrix \n");
      else
        printf("Non Diagonal Matrix\n");
    }

    Matrix A is said to be symmetric if A=A^T and Skew Symmetric matrix if A= - A^T.
    Write a C program to check whether a matrix is symmetric or skew symmetric
    #include <stdio.h>
    #define MAX_SIZE 10

    int main() {
    int A[MAX_SIZE][MAX_SIZE];
    int i, j, rows, cols;
    int symmetric = 1, skewsymmetric = 1;

    printf("Enter the number of rows and columns of the square matrix: ");
    scanf("%d", &rows);
    cols = rows;

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

    // Check for symmetric matrix
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            if (A[i][j] != A[j][i]) {
                symmetric = 0;
                break;
            }
            }
        if (symmetric == 0) {
            break;
        }
        }

    // Check for skew-symmetric matrix
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            if (A[i][j] != -A[j][i]) {
                skewsymmetric = 0;
                break;
                }
            }
        if (skewsymmetric == 0) {
            break;
        }
    }

    if (symmetric == 1) {
        printf("The matrix is symmetric.\n");
    } else if (skewsymmetric == 1) {
        printf("The matrix is skew-symmetric.\n");
    } else {
        printf("The matrix is neither symmetric nor skew-symmetric.\n");
    }

    return 0;
    }
     
    Note: Matrix programs can be written using functions and hence optimize the code.Look at the blog post on functions.

    Programs to try using 1-D arrays

    1.Read an array and rotate elements right( read n-number of times to rotate)
    2.Find the average of list of numbers.
    3.Find the maximum and minimum values from an array of integers.
    4.Swap the k th and k+1 th element in an array. Read k.
    5.Find the binary equivalent of a number using array.
    6.Find similar elements in an array and compute the number of times they occur.
    7. Separate odd and even integers in separate arrays from a given array.
    8.Find the intersection of two set of numbers.
    9.Rearrange n numbers in an array in reverse order.(selection sort)
    10.Sort the numbers stored in array in ascending order.(bubble sort)
    11.Arrange numbers in an array in such a way that the array will have odd numbers followed by the even numbers.
    12.Find the frequency of digits in a set of numbers.
    13.Remove duplicate elements from an array.( Hint: sort the array)
    14.Merge two sorted arrays into another array in sorted order.
    15.Find the mean,variance,median and standard deviation of set of integer data.
    16.Read list of numbers and print prime numbers from the list.
    17.List of internal marks of a subject is stored in an array ( marks out of 50).
    Find
    a.number of passed students ( need 50 percentage or more)
    b.number of failed students
    c.number of students having 60 percentage or more
    d.maximum , minimum and average mark in the subject.
    ( do it as a menu driven program..)
    18.Search a key element in a given array ( linear search)
    19.Search a key element in the give sorted array ( binary search)
    20.Generate Fibonacci numbers up to n and store it in an array.Read and print prime numbers from it.
    21.Given two vectors V1 and V2 in R3 . Find their sum (V1+V2)and dot product V1.V2.
    22.Find the length of a given vector in Rn.
    23.Find the second largest element in an unsorted array.
    24.Find the kth largest element in a list.
    25.Convert a decimal number into hexadecimal.
    26.Write a C program to find the occurrence of each element in an array.(uq)
    27.Write a C program to check if a number is present in a given list of numbers. If present, give location of the number otherwise insert the number in the list at the end.(uq)
    28.Find the second largest element in the array ( uq)
    29.Find the element which occurs largest number of times in an array. 
    30.Reverse an array.

    Programs to try using two dimensional arrays
    1.Read a 2D array and print it in row major and column major order.
    2.Write programs for matrix arithmetic.
            a)addition b)subtraction c)multiplication
    3.Find transpose of a given matrix.(uq)
    4.Find the trace of a matrix.( sum of the diagonal element)
    5.Find sum of each rows and columns of a matrix.
    6.Find the norm of a matrix.(1-norm .Find sum of absolute value of element column wise.Find the max).
    7.Given two square matrices A and B of same order.
    Check whether AB equal BA.
    8.Check whether the given matrix is symmetric.(university question)
    9.Check whether a given matrix is an identity matrix.
    10. Calculate determinant of a 3 x 3 matrix.
    11.Find the saddle points in a matrix.
    12.Check for upper triangular/lower triangular matrix.
    13. marks(out of 150) of 5 students in 3 subjects are stored in matrix form.Find
        a)top marks in each subject
        b)Number of failed students in each subject
        c)average mark in each subject.
        d)Number of supply subjects each students have.
    14.Print all prime numbers from a matrix.(university question)
    15.Write a C program to accept a two dimensional matrix and display the row sum, column sum and diagonal sum of elements.(university question)
    16.Check whether the given matrix is diagonal.

    Comments

    Popular posts from this blog

    Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

    Structure of a C Program