Monday, 24 March 2014

0

C Program 2: To Reverse A Number Using An Array

  • Monday, 24 March 2014
  • IndianBooktuber
  • Share
  • Aim: To reverse a number(digits entered) using an array
    Theory: At first, we would need to ask the user about how many digits he is going to enter or what is the length of the number which he wants to reverse. Then we would ask him to enter the digits of the number one by one and then we reverse the digit and print the reverse number.
    Following would be the code:
    //to reverse the digits in an array
    #include<stdio.h>
    #include<conio.h>
    int main()
    {
        int i,j,n,k, a[10];
        a[10]=0;
        printf("enter the number of digits of number you want to reverse: ");
        scanf("%d", &n);
        n=n-1;
        printf("enter the digits one by one: \n");
        for (i=0; i<=n; i++)
        {
            scanf("%d",&a[i]);
        }
     
        for (j=n; j>=0; j--)
        {
            printf("%d", a[j]);
    }

        getch();
        return 0;
    }



    We would use two for loops in the program to accomplish our objective. Before that, we would ask the user to enter the digits he is going to enter. Then, using a for loop, we would get the input one by one. The loop for(i=0; i<=n; i++) serves this purpose.
    The next loop with 'j' is used to reverse the number. We use decrement operator in the loop so as to get the number reversed.
    What actually happens is, we now print the array from backwards, for eg. when you entered a number 12, the numbers were stored like this in array:
    a[0]=1;
    a[1]=2;
    When you used the decrement counter, you also changed the initialization and condition in the second for loop. The for loop begins with its execution from n, i.e. it first prints a[n] or a[1] in this case.
    It works like:
    a[1]=2;
    a[0]=1;
    Thus, the result becomes 21.

    0 Responses to “C Program 2: To Reverse A Number Using An Array”

    Post a Comment

    Subscribe