Reverse a number

 Reverse a number


C Program
1.For Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int n,res;
    printf("Enter a Number:");
    scanf("%d",&n);
    for(res=0;n>0;n=n/10)
    {

        res = res * 10 + n%10;
    }
    printf("%d",res);
}
2.While Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int n,res;
    printf("Enter a Number:");
    scanf("%d",&n);
    while(n>0)
    {
        res = res * 10 + n%10;
        n=n/10;
    }
     printf("%d",res);
}
3.Do While Loop
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int n,res;
    printf("Enter a Number:");
    scanf("%d",&n);
    do
    {
      res = res * 10 + n%10;
       n=n/10;
    }while(n>0);
   printf("%d",res);
}


Java Program
1.For Loop
import java.util.Scanner;

public class ReverseNumber {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.print("Enter A Number:");
		int n = s.nextInt();
		int res;
		for(res=0;n>0;n=n/10)
	    {
	 
	        res = res * 10 + n%10;
	    }
	    System.out.print(res);
	}
}
2.While Loop
import java.util.Scanner;

public class ReverseNumber {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.print("Enter A Number:");
		int n = s.nextInt();
		int res = 0;
		 while(n>0)
		    {
		        res = res * 10 + n%10;
		        n=n/10;
		    }
	    System.out.print(res);
	}
}
3.Do While Loop
import java.util.Scanner;

public class ReverseNumber {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.print("Enter A Number:");
		int n = s.nextInt();
		int res = 0;
		 do
		    {
		      res = res * 10 + n%10;
		       n=n/10;
		    }while(n>0);
	    System.out.print(res);
	}
}

0 Comments:

Post a Comment