C/C++ Program to print alphabets in reverse order

Write a program to print alphabets in reverse order in C/C++.

The logic to print alphabets in reverse order is the same as printing alphabets in serial order. We print alphabets based on the fact that the ASCII value of all English alphabets is contiguous. The only difference is instead of iterating from ‘A’ to ‘Z’, we will iterate from ‘Z’ to ‘A’.

#include<stdio.h>

int main() {

	char c;
	for (c = 'Z'; c >= 'A'; --c) {
		printf("%c ", c);
	}
	printf("\n");

}

Output

Z Y X W V U T S R Q P O N M L K J I H G F E D C B A

Instead of using char, we can also use int.

#include<stdio.h>

int main() {

	int c;
	for (c = 'Z'; c >= 'A'; --c) {
		printf("%c ", c);
	}
	printf("\n");

}

Output

Z Y X W V U T S R Q P O N M L K J I H G F E D C B A

The output of both programs is the same. This shows that char does not actually store the character. It stores an integer ASCII value corresponding to that character. “%c” takes the numeric value and prints the corresponding character.

Program to print alphabets in reverse order using pointer

We can also use pointer to print alphabets in reverse order. Also, we can use both int or char pointer. The output will be same.

#include<stdio.h>
#include<stdlib.h>

int main() {

	int *c = (int *)malloc(sizeof(int));
	for (*c = 'Z'; *c >= 'A'; --(*c)) {
		printf("%c ", *c);
	}
	printf("\n");

}

Output

Z Y X W V U T S R Q P O N M L K J I H G F E D C B A

Read

Leave a Comment

Your email address will not be published. Required fields are marked *