Tuesday, 3 July 2012

Reverse a digit using array in C ( 5 Digit number )



Code - 

//___Program to reverse a 5 digit number___

/* There are 2 ways for reversing a number....1 is implemented below and for other

   check Reversing a number Version 2

   Logic - The first way is to extract the digits one by one and store them in an array and print the array

   Disadvantage of using this type of method is that it is space consuming i.e. requires memory

   of 5 variable */

//_________Including Header Files____________

#include<stdio.h>

#include<conio.h>

//________Included mainly for the getch() function____________

int main()
{
int number, number_digits[5], counter = 0, remainder = 0, temp_number = 0, i = 0;

//_________Variable declaration_________

printf("\n\n\t\t   _______ Reverse the 5 digit number _________\n\n\n");

printf("  Enter a 5 digit number - ");

//___Prompting the user to enter a 5 digit number____

scanf("%d", &number);

//____Reading the user inputr and storing it in variable number of type integer___

temp_number = number;

while(number != 0)

/*__Looping Construct which will keep on executing till number does not become 0 when divided by

10__ */
{
remainder = number % 10;

/*_Extracting the digit using modulus operator by gettning the remainder after dividing the

number by 10__ */

number = number / 10;

/*_Changing the value of number by assigning it the quotient obtain after dividing it by 10__ */

number_digits[counter] = remainder;

//___Assigning the digits one by one to the array elements____

counter++;
/*__Counter variable is used to count the number of digits in the original number inputted ___ */

}

if (counter != 5)

//_________Checking whether the total number of digits were 5 or not____________
{
printf("\n\n\t  ___ 5 Digit number was required ___");
}

printf("\n\n\t\t  Reverse of %d number %d entered is  - ", counter, temp_number);

for (i = 0; i <= counter - 1; i++)

//__________Looping construct to display the elements of the array___________

{
printf("%d", number_digits[i]);

}

getch();

return 0;

/*_return 0 tells the compiler that program has executed successfully without any error__ */

}

Follow Us on Facebook -  Assignment Hub

No comments:

Post a Comment