C program to find the size of a union.

A union in C is similar to a structure, but all its members share the same memory location. While a struct allocates separate space for each member, a union allocates space equal to its largest member, and every member overlaps that same block of memory. Only one member holds a valid value at any point …

C Program to Sort Matrix Rows Ascending and Columns Descending

Given an M×N matrix, this program produces two independently sorted versions: Rows sorted ascending — within each row, elements are rearranged smallest to largest. Rows are independent of each other. Columns sorted descending — within each column, elements are rearranged largest to smallest (operating on the original matrix, not the row-sorted one). Columns are independent …

Sum of Digits of a Number in C – Loop and Recursion

Finding the sum of digits of a number in C is a classic programming exercise that teaches digit extraction using the modulo operator. You extract each digit by taking n % 10, add it to a running total, then divide n by 10 to drop the last digit. Repeat until no digits remain. This technique …

C Program to interchange the main diagonal elements of the matrix

Every square matrix has two diagonals: the main diagonal (top-left to bottom-right, elements a[i][i]) and the anti-diagonal (top-right to bottom-left, elements a[i][n-1-i]). This program reads a square matrix, swaps each main-diagonal element with the anti-diagonal element in the same row, and prints the result. The original post used void main(), a broken scanf format string …

C Program to Find Second Largest and Second Smallest Element in an Array

Finding the second largest and second smallest elements in an array can be done in a single pass through the data — O(n) time, O(1) space — without sorting. The key is maintaining four running extremes: largest, second_largest, smallest, second_smallest. The original program sorted the array first (O(n²) with bubble sort), then accessed fixed indices …

C Program to Sort N Numbers in Descending Order

Sorting in descending order means arranging elements from largest to smallest. The only difference from ascending bubble sort is the direction of the comparison: ascending uses arr[j] > arr[j+1] (swap when left is larger), while descending uses arr[j] < arr[j+1] (swap when left is smaller). This program fixes the original which used void main, a …