C Program to mask password text with asterisk(*)

This C program shows how to mask password input with asterisks (*) — exactly what you see on a login screen, where each character you type is hidden behind a *. The trick is to read the keyboard without echoing the typed character to the screen, print a * in its place, and store the real character in a buffer. Because turning off echo is operating-system specific, this tutorial gives you a single portable program that works on Windows, Linux and macOS.

Why You Can’t Just Use scanf

A normal scanf("%s", password) or getchar() echoes every character straight to the terminal, so anyone looking over your shoulder sees the password. To hide it we must read each key in “raw” mode with echo disabled:

  • On Windows, _getch() from <conio.h> reads a key without echoing it.
  • On Linux / macOS, we temporarily turn off the ECHO and ICANON terminal flags using <termios.h>, read the key, then restore the old settings.

The Program (Portable)

#include <stdio.h>
#include <string.h>

#ifdef _WIN32
#include <conio.h>
static int get_ch(void) { return _getch(); }
#else
#include <termios.h>
#include <unistd.h>
static int get_ch(void)
{
    struct termios old, raw;
    int ch;
    tcgetattr(STDIN_FILENO, &old);     /* save current settings */
    raw = old;
    raw.c_lflag &= ~(ICANON | ECHO);   /* turn off line buffering + echo */
    tcsetattr(STDIN_FILENO, TCSANOW, &raw);
    ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &old);  /* restore settings */
    return ch;
}
#endif

int main(void)
{
    char password[32];
    int i = 0, ch;

    printf("Enter your password: ");
    fflush(stdout);

    while (i < (int)sizeof(password) - 1) {
        ch = get_ch();

        if (ch == '\n' || ch == '\r')      /* Enter ends input */
            break;

        if (ch == 127 || ch == 8) {        /* Backspace / Delete */
            if (i > 0) {
                i--;
                printf("\b \b");           /* erase the last * on screen */
                fflush(stdout);
            }
            continue;
        }

        password[i++] = (char)ch;
        printf("*");
        fflush(stdout);
    }
    password[i] = '\0';                     /* null-terminate the string */

    printf("\nYour password is: %s\n", password);
    return 0;
}

How the Program Works

  • get_ch() hides the OS difference: one definition for Windows (_getch), one for Linux/macOS (termios). The rest of the program is identical on every platform.
  • Each keypress is read without echo. We store the real character in password[] and print a * so the screen never shows the actual text.
  • Backspace (codes 8 or 127) deletes the last character and erases its * using "\b \b" — backspace, space, backspace.
  • Enter (\n or \r) ends input. We then write '\0' to terminate the string properly — the original textbook code used '', which is an invalid empty character constant.
  • The loop is bounded by sizeof(password) - 1, so it can never overflow the buffer — unlike the old gets() version.

This is a complete modernisation of the classic example: gone are void main(), clrscr(), gets() and the Windows-only conio.h dependency.

Sample Output

Enter your password: ********
Your password is: secret12

(As you type secret12 you only ever see eight asterisks on screen.)

A Note on Real Security

Masking only hides the password from shoulder-surfers. In real software you should never store or print a plaintext password — you would hash it (e.g. with bcrypt) and compare hashes. This program is for learning terminal input, not production authentication. For the C fundamentals behind it, The C Programming Language by Kernighan and Ritchie is the classic reference — find it on Amazon.

This post contains affiliate links. If you buy through them, we may earn a small commission at no extra cost to you.

Related C Programs

This program reads the terminal directly, so it needs a real local terminal — browser-based online compilers can’t emulate raw key input. Set up a proper toolchain with our guide to a complete C development environment.

C Program: Insert into an array

Arrays in C
Write a C program to insert a particular element in a specified position in a given array.Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

*/

#include <stdio.h>
#include <conio.h>

void main()
{
int x[10];
int i, j, n, m, temp, key, pos;

clrscr();

printf("Enter how many elementsn");
scanf("%d", &n);

printf("Enter the elementsn");
for(i=0; i<n; i++)
{
scanf("%d", &x[i]);
}

printf("Input array elements aren");
for(i=0; i<n; i++)
{
printf("%dn", x[i]);
}

for(i=0; i< n; i++)
{
for(j=i+1; j<n; j++)
{
if (x[i] > x[j])
{
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}

printf("Sorted list isn");
for(i=0; i<n; i++)
{
printf("%dn", x[i]);
}

printf("Enter the element to be insertedn");
scanf("%d",&key);

for(i=0; i<n; i++)
{
if ( key < x[i] )
{
pos = i;
break;
}
}

m = n - pos + 1 ;

for(i=0; i<= m ; i++)
{
x[n-i+2] = x[n-i+1] ;
}

x[pos] = key;

printf("Final list isn");
for(i=0; i<n+1; i++)
{
printf("%dn", x[i]);
}
} /* End of main() */
Read more Similar C Programs
Array In C

Simple C Programs

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program: Array Summation Using Pointers

Arrays in C.
Write a C program to read N integers and store them in an array A, and so find the sum of all these elements using pointer. Output the given array and and the computed sum with suitable heading. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/



#include <stdio.h>
#include <conio.h>
#include <malloc.h>

void main()
{
int i,n,sum=0;
int *a;

clrscr();

printf("Enter the size of array An");
scanf("%d", &n);

a=(int *) malloc(n*sizeof(int)); /*Dynamix Memory Allocation */

printf("Enter Elements of First Listn");
for(i=0;i<n;i++)
{
scanf("%d",a+i);
}

/*Compute the sum of all elements in the given array*/
for(i=0;i<n;i++)
{
sum = sum + *(a+i);
}

printf("Sum of all elements in array = %dn", sum);

} /* End of main() */
Read more Similar C Programs
Array In C

Simple C Programs

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed! and the computed sum with suitable heading. Read more about C Programming Language .

(c) www.c-program-example.com

C program: Sum Of Elements In A Matrix

Write a C program to read a matrix A (MxN) and to find the following using functions
a) Sum of the elements of each row
b) Sum of the elements of each column
c) Find the sum of all the elements of the matrix
Output the computed results with suitable headings.
Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/


#include <stdio.h>
#include <conio.h>

void main()
{
int arr[10][10];
int i, j, row, col, rowsum, colsum,sumall=0;

/* Function declaration */
int Addrow(int A[10][10], int k, int c);
int Addcol(int A[10][10], int k, int c);

clrscr();

printf("Enter the order of the matrixn");
scanf("%d %d", &row, &col);

printf("Enter the elements of the matrixn");
for(i=0; i<row; i++)
{
for(j=0; j< col; j++)
{
scanf("%d", &arr[i][j]);
}
}

printf("Input matrix isn");
for(i=0; i<row; i++)
{
for(j=0;j<col;j++)
{
printf("%3d", arr[i][j]);
}
printf("n");
}

/* computing row sum */
for(i=0; i<row; i++)
{
rowsum = Addrow(arr,i,col);
printf("Sum of row %d = %dn", i+1, rowsum);
}

for(j=0; j<col; j++)
{
colsum = Addcol(arr,j,row);
printf("Sum of column %d = %dn", j+1, colsum);
}

/* computation of all elements */
for(j=0; j< row; j++)
{
sumall = sumall + Addrow(arr,j,col);
}

printf("Sum of all elements of matrix = %dn", sumall);

}

/* Function to add each row */
int Addrow(int A[10][10], int k, int c)
{
int rsum=0, i;
for(i=0; i< c; i++)
{
rsum = rsum + A[k][i];
}
return(rsum);
}

/* Function to add each column */
int Addcol(int A[10][10], int k, int r)
{
int csum=0, j;
for(j=0; j< r; j++)
{
csum = csum + A[j][k];
}
return(csum);
}
Read more Similar C Programs
Matrix Programs
Learn C Programming

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to find the Multiplication of two matrices

C Program to find the Multiplication of two matrices. C Program Develop functions
a) To read a given matrix
b) To output a matrix
c) To compute the product of two matrices
Use the above functions to read in two matrices A (MxN) B (NxM), to compute the product of the two matrices, to output the given matrices and the computed matrix in a main function
Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdio.h>
#include <conio.h>
#define MAXROWS 10
#define MAXCOLS 10

void main()
{
int A[MAXROWS][MAXCOLS], B[MAXROWS][MAXCOLS], C[MAXROWS][MAXCOLS];
int M, N;

/*Function declarations*/

void readMatrix(int arr[][MAXCOLS], int M, int N);
void printMatrix(int arr[][MAXCOLS], int M, int N);
void productMatrix(int A[][MAXCOLS], int B[][MAXCOLS], int C[][MAXCOLS],
int M, int N);

clrscr();

printf("Enter the value of M and Nn");
scanf("%d %d",&M, &N);
printf ("Enter matrix An");
readMatrix(A,M,N);
printf("Matrix An");
printMatrix(A,M,N);

printf ("Enter matrix Bn");
readMatrix(B,M,N);
printf("Matrix Bn");
printMatrix(B,M,N);

productMatrix(A,B,C, M,N);

printf ("The product matrix isn");
printMatrix(C,M,N);
}

/*Input matrix A*/
void readMatrix(int arr[][MAXCOLS], int M, int N)
{
int i, j;
for(i=0; i< M ; i++)
{
for ( j=0; j < N; j++)
{
scanf("%d",&arr[i][j]);
}
}
}
void printMatrix(int arr[][MAXCOLS], int M, int N)
{
int i, j;
for(i=0; i< M ; i++)
{
for ( j=0; j < N; j++)
{
printf("%3d",arr[i][j]);
}
printf("n");
}
}

/* Multiplication of matrices */
void productMatrix(int A[][MAXCOLS], int B[][MAXCOLS], int C[][MAXCOLS],
int M, int N)
{
int i, j, k;
for(i=0; i< M ; i++)
{
for ( j=0; j < N; j++)
{
C[i][j] = 0 ;
for (k=0; k < N; k++)
{
C[i][j] = C[i][j] + A[i][k] * B[k][j];
}
}
}
}
Read more Similar C Programs
Matrix Programs
Learn C Programming

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to Sort N Elements Using Selection Sort — With Step-by-Step Example

Selection Sort works by repeatedly finding the minimum element from the unsorted portion of the array and placing it at the beginning. After each pass, the sorted portion grows by one element from the left.

It always performs exactly O(n²) comparisons regardless of input order — unlike Bubble or Insertion Sort, there is no early exit. Its one real advantage: it makes at most O(n) swaps, which matters when write operations are expensive (e.g. flash memory or EEPROM).

Algorithm

  1. For position i from 0 to n-2:
  2. Find the index of the minimum element in arr[i..n-1]
  3. Swap it with arr[i]
  4. After this pass, arr[0..i] is sorted

Step-by-Step Example

Sort [64, 25, 12, 22, 11]:

Pass 0:  find min in [64,25,12,22,11] → 11 at index 4 → swap with index 0
         [11, 25, 12, 22, 64]    11 in final position ✓

Pass 1:  find min in [25,12,22,64] → 12 at index 2 → swap with index 1
         [11, 12, 25, 22, 64]    12 in final position ✓

Pass 2:  find min in [25,22,64] → 22 at index 3 → swap with index 2
         [11, 12, 22, 25, 64]    22 in final position ✓

Pass 3:  find min in [25,64] → 25 at index 3 (already in place, no swap)
         [11, 12, 22, 25, 64]    25 in final position ✓

Final:   [11, 12, 22, 25, 64] ✓

C Program — Selection Sort

#include <stdio.h>

void selection_sort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int min_idx = i;

        /* Find index of minimum in arr[i+1..n-1] */
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[min_idx])
                min_idx = j;
        }

        /* Swap only if minimum is not already in place */
        if (min_idx != i) {
            int temp       = arr[min_idx];
            arr[min_idx]   = arr[i];
            arr[i]         = temp;
        }
    }
}

void print_array(int arr[], int n) {
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

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

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

    printf("Before sorting: ");
    print_array(arr, n);

    selection_sort(arr, n);

    printf("After sorting:  ");
    print_array(arr, n);

    return 0;
}

Code Explanation

  • Outer loop (i) — marks the boundary between the sorted (left) and unsorted (right) portions. Each iteration places one more element into its final position.
  • Inner loop (j) — scans the unsorted portion to find the index of the smallest element. Tracks only the index, not the value, so the swap can be done directly.
  • if (min_idx != i) — skips the swap when the minimum is already at position i. This avoids a redundant write and keeps the swap count minimal.

Sample Output

Enter number of elements: 6
Enter 6 elements: 64 25 12 22 11 90
Before sorting: 64 25 12 22 11 90
After sorting:  11 12 22 25 64 90

Time and Space Complexity

Case Time Note
Best O(n²) No early exit — always scans the full unsorted portion
Average O(n²) n(n-1)/2 comparisons always
Worst O(n²) Same as best — input order makes no difference
Space O(1) In-place, one temp variable
Swaps O(n) At most n-1 swaps — key advantage

Selection Sort is not stable — the swap can move an element past another equal element, changing their relative order.

Selection Sort vs Other O(n²) Algorithms

Algorithm Comparisons Swaps Best case Stable
Selection Sort O(n²) always O(n) O(n²) No
Bubble Sort O(n²) O(n²) O(n) ✓ Yes
Insertion Sort O(n²) O(n²) shifts O(n) ✓ Yes

When to choose Selection Sort: when the cost of writing/swapping is high relative to the cost of reading/comparing. For most in-memory sorting, Insertion Sort is a better choice because it adapts to partially sorted data.

Related Sorting Programs in C


As an Amazon Associate we earn from qualifying purchases.

Further Reading

The definitive reference for C — The C Programming Language by Brian Kernighan and Dennis Ritchie. Covers every concept on this site: pointers, arrays, structs, file I/O, and the standard library. Worth having on your desk.

C Program To Sort Names

Write a C program to read N names, store them in the form of an array and sort them in alphabetical order.Output the given names and the sorted names in two columns side by side with suitable heading.Program will sort the name strings using Bubble Sort technique. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/


#include <stdio.h>
#include <conio.h>
#include <string.h>

void main()
{
char name[10][8], Tname[10][8], temp[8];
int i, j, N;

clrscr();

printf("Enter the value of Nn");
scanf("%d", &N);

printf("Enter %d namesn", N);
for(i=0; i< N ; i++)
{
scanf("%s",name[i]);
strcpy (Tname[i], name[i]);
}

for(i=0; i < N-1 ; i++)
{
for(j=i+1; j< N; j++)
{
if(strcmpi(name[i],name[j]) > 0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}

printf("n----------------------------------------n");
printf("Input NamestSorted namesn");
printf("------------------------------------------n");
for(i=0; i< N ; i++)
{
printf("%stt%sn",Tname[i], name[i]);
}
printf("------------------------------------------n");

} /* End of main() */
Read more Similar C Programs

Data Structures


C Sorting

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to read an English sentence and replace lowercase characters by uppercase and vice-versa.

Write a C program to read an English sentence and replace lowercase characters by uppercase and vice-verso. Output the given sentence as well as the case converted sentence on two different lines. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/


#include <stdio.h>
#include <ctype.h>
#include <conio.h>

void main()
{
char sentence[100];
int count, ch, i;

clrscr();

printf("Enter a sentencen");
for(i=0; (sentence[i] = getchar())!='n'; i++)
{
;
}

sentence[i]='';

count = i; /*shows the number of chars accepted in a sentence*/

printf("The given sentence is : %s",sentence);

printf("nCase changed sentence is: ");
for(i=0; i < count; i++)
{
ch = islower(sentence[i]) ? toupper(sentence[i]) : tolower(sentence[i]);
putchar(ch);
}

} /*End of main()*/
Read more Similar C Programs

C Strings


Data Structures


C Sorting

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C program to check whether a given string is palindrome or not

Write a C program to read a string and check whether it is a palindrome or not (without using library functions). Output the given string along with suitable message.Palindrome is a word, sentence, group of characters, or number, that remains same, when reversed.
For example: GADAG, 9009… Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                                  Happy Coding
***********************************************************/

#include <stdio.h>
#include <conio.h>
#include <string.h>

void main()
{
 char string[25], revString[25]={''};
 int  i,length = 0, flag = 0;

 clrscr();

 fflush(stdin);

 printf("Enter a stringn");
 gets(string);

 for (i=0; string[i] != ''; i++) /*keep going through each */
 {                                 /*character of the string */
  length++;                     /*till its end */
 }

 for (i=length-1; i >= 0 ; i--)
 {
  revString[length-i-1] = string[i];
 }

 /*Compare the input string and its reverse. If both are equal
   then the input string is palindrome. Otherwise it is
   not a palindrome */

 for (i=0; i < length ; i++)
 {
  if (revString[i] == string[i])
   flag = 1;
  else
   flag = 0;
 }

 if (flag == 1)
  printf ("%s is a palindromen", string);
 else
  printf("%s is not a palindromen", string);

}   /*End of main()*/
Read more Similar C Programs
Searching in C

C Strings

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

C Program to Find the Transpose of a Matrix — Rectangular and In-Place Square

The transpose of a matrix is formed by flipping it over its main diagonal — rows become columns and columns become rows. If the original matrix is of order M×N, its transpose is of order N×M, where element A[i][j] becomes B[j][i].

Matrix A (3×2):        Transpose B (2×3):
  1  2                   1  3  5
  3  4        →          2  4  6
  5  6

Transpose is fundamental in linear algebra: it appears in matrix multiplication, solving linear systems, neural networks (weight matrices), and signal processing.

Algorithm

For an M×N matrix A, the transpose B is an N×M matrix where:

B[j][i] = A[i][j]   for all i in 0..M-1, j in 0..N-1

C Program — Transpose of a Rectangular Matrix (M×N)

#include <stdio.h>

#define MAX 10

void read_matrix(int mat[][MAX], int rows, int cols) {
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            scanf("%d", &mat[i][j]);
}

void print_matrix(int mat[][MAX], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++)
            printf("%4d", mat[i][j]);
        printf("\n");
    }
}

void transpose(int A[][MAX], int B[][MAX], int rows, int cols) {
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            B[j][i] = A[i][j];   /* B is cols×rows */
}

int main(void) {
    int A[MAX][MAX], B[MAX][MAX];
    int M, N;

    printf("Enter number of rows and columns: ");
    scanf("%d %d", &M, &N);

    printf("Enter elements of %d×%d matrix:\n", M, N);
    read_matrix(A, M, N);

    printf("\nMatrix A (%d×%d):\n", M, N);
    print_matrix(A, M, N);

    transpose(A, B, M, N);

    printf("\nTranspose B (%d×%d):\n", N, M);
    print_matrix(B, N, M);   /* note: N rows, M cols */

    return 0;
}

Bonus — In-Place Transpose of a Square Matrix

For an N×N square matrix, the transpose can be done in-place with no extra array — just swap elements above and below the main diagonal:

#include <stdio.h>

#define MAX 10

void transpose_inplace(int mat[][MAX], int n) {
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++) {
            int temp    = mat[i][j];
            mat[i][j]   = mat[j][i];
            mat[j][i]   = temp;
        }
}

void print_matrix(int mat[][MAX], int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            printf("%4d", mat[i][j]);
        printf("\n");
    }
}

int main(void) {
    int mat[MAX][MAX];
    int n;

    printf("Enter matrix size N (for N×N): ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n * n);
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            scanf("%d", &mat[i][j]);

    printf("\nOriginal matrix:\n");
    print_matrix(mat, n);

    transpose_inplace(mat, n);

    printf("\nTransposed matrix:\n");
    print_matrix(mat, n);

    return 0;
}

The inner loop starts at j = i + 1 — this skips the main diagonal (which stays in place) and avoids double-swapping elements below the diagonal.

Code Explanation

  • Rectangular transpose: the output matrix B has dimensions N×M (rows and columns swapped). The assignment B[j][i] = A[i][j] places each element in its transposed position. When printing B, pass N as rows and M as columns — not the original M and N.
  • In-place square transpose: only iterate the upper triangle (j starts at i+1). Each pair (i, j) and (j, i) is swapped exactly once. O(1) extra space.

Sample Output

Enter number of rows and columns: 3 2
Enter elements of 3×2 matrix:
1 2
3 4
5 6

Matrix A (3×2):
   1   2
   3   4
   5   6

Transpose B (2×3):
   1   3   5
   2   4   6

Complexity

Version Time Space
Rectangular (M×N) O(M × N) O(N × M) for output matrix
Square in-place (N×N) O(N²) O(1)

Related Matrix Programs in C


As an Amazon Associate we earn from qualifying purchases.

Further Reading

The definitive reference for C — The C Programming Language by Brian Kernighan and Dennis Ritchie. Covers every concept on this site: pointers, arrays, structs, file I/O, and the standard library. Worth having on your desk.