Write a program to receive a five-digit number and display it as like 2,4,6,8,9
Example:
Input: num = 24689 Output: 2 4 6 8 9
Approach: Simple
C
#include <stdio.h>int main(){int num;printf("Enter a five digit number : ");scanf("%d", &num);int arr[6];int i = 4;while (num > 0){arr[i] = num % 10;num = num / 10;i--;}for (i = 0; i < 5; i++)printf("%d\n", arr[i]);return 0;}
Java
import java.util.Scanner;public class Main{public static void main(String[] args) {System.out.println("enter the five digit number");Scanner sc = new Scanner(System.in);int numarr[] = new int[5];int i=4;int num = sc.nextInt();while(num>0){numarr[i] = num%10;num=num/10;i--;}for(int j=0;j<5;j++){System.out.println(numarr[j]);}}}
Approach: Using recursion
C
#include <stdio.h>void printRec(int n){if (n < 10){printf("%d\n", n);return;}else{printRec(n / 10);printf("%d\n", n % 10);}}int main(){int num;printf("Enter a five digit number : ");scanf("%d", &num);printRec(num);return 0;}
Java
import java.util.Scanner;public class Main{public static void main(String[] args) {System.out.println("enter the five digit number");Scanner sc = new Scanner(System.in);int num = sc.nextInt();printNum(num);}public static void printNum(int num){if(num<10){System.out.println(num);}else{printNum(num/10);System.out.println(num%10);}}}
No comments:
Post a Comment