• Here is a diagram to describe the program without using any algorithms.
» C
(*) Take advantage of using while() loop and getchar() != '\n' to clear buffer input and validate positive integer.
#include <stdio.h>
void clearInputBuffer() {
int c;
while ((c = getchar()) != '\n' && c != EOF);
}
int main() {
int N;
printf("Enter a positive integer: ");
scanf("%d", &N);
while (scanf("%d", &N) != 1 || N <= 0) {
printf("Invalid input. Enter a positive integer: ");
clearInputBuffer();
}
printf("Postive Integer: %d", N);
return 0;
}
» Java
(*) Take advantage of using scanner.hasNextInt() method is used to check if the next token in the input stream is a valid integer before comparing positive or negative numbers.
import java.util.Scanner;
class HelloWorld {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N;
System.out.print("Enter a positive integer: ");
while(true) {
if (scanner.hasNextInt()) {
N = scanner.nextInt();
if (N > 0) {
break;
}
}
System.out.print("Invalid input. Enter a positive integer: ");
scanner.nextLine(); // Clear the input buffer
}
System.out.println("Positive Integer: " + N);
scanner.close();
}
}
» PHP
<?php
$N;
echo "Enter a positive integer: ";
while(true) {
$input = trim(fgets(STDIN));
if (filter_var($input, FILTER_VALIDATE_INT) && $input > 0) {
$N = intval($input);
break;
}
echo "Invalid input. Please enter a positive integer: ";
}
echo "Positive Integer: $N\n";
?>
» Javascript
let N = 0;
while (true) {
let input = prompt("Enter a positive integer:");
if (Number.isInteger(Number(input)) && Number(input) > 0) {
N = parseInt(input);
break;
}
alert("Invalid input. Please enter a positive integer.");
}
console.log("Positive Integer: " + N);
» Python
N = 0
while True:
try:
input_value = int(input("Enter a positive integer: "))
if input_value > 0:
N = input_value
break
else:
print("Invalid input. Please enter a positive integer.")
except ValueError:
print("Invalid input. Please enter a positive integer.")
print("Positive Integer:", N)