Write a program to input a number and display if it's first and last digits are same or not.
Example: If N= 23782, then it's first and last digits are same.
(Iteration and loops.)
Answers
Required Answer:-
Question:
- Write a program to input a number and display if the first digit and last digit are same or not.
Solution:
Here comes the program.
1. In Java.
import java.util.*;
public class Number {
public static void main(String[] args) {
int n, x, y;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number: ");
n=sc.nextInt();
x=n%10;
while(n>=9)
n/=10;
y=n;
if(x==y)
System.out.println("First and last digit are same.");
else
System.out.println("First and last digit are different.");
sc.close();
}
}
2. In Python.
n=int(input("Enter a number: "))
x=n%10
while n>=9:
n//=10
y=n
if x==y:
print("First and last digit are same.")
else:
print("First and last digit are different.")
3. In C
#include <stdio.h>
int main() {
int n, x, y;
printf("Enter a number: ");
scanf("%d", &n);
x=n%10;
while (n >= 9)
n/=10;
y=n;
if(x==y)
printf("First and last digits are same.");
else
printf("First and last digits are different.");
return 0;
}
4. In C++
#include <iostream>
using namespace std;
int main() {
int n,x,y;
cout << "Enter a number: ";
cin >> n;
while(n >= 9)
n /= 10;
y=n;
if (x==y)
cout << "First and last digits are same.";
else
cout << "First and last digits are different.";
return 0;
}
Algorithm:
- START.
- Accept the number.
- Find the first and last digit.
- Check if they are equal or not.
- Display the result.
- STOP.
Refer to the attachment for output ☑.
Explanation:
This is my answer and if you are satisfied with the answer the please mark me as brainlist