C - Read an Integer Number until Valid Number not Found using C Program.


IncludeHelp 04 August 2016

In this code snippet, we will learn how to take an input within a range in c program, in this program input will be taken again and again until valid (number within range) not found.

It is easy to check range on an input number, in this program we are checking range in while loop condition block and if it is not matched program will read number again.

In this example, we will read age and the age range between 18 to 65 years, program will read age until input value does not match this criteria i.e. age is not between 18 to 65 years. If valid age found program will print the age.

C Code Snippet - Read an Integer Number until Valid Number not Found using C Program

/*C - Read an Integer Number until Valid Number 
not Found using C Program.*/

#include <stdio.h>

int main(){
	int age;
	
	printf("Enter age between 18-65: ");
	scanf("%d",&age);	
	
	while(!(age>=18 && age<=65)){
		printf("Invalid age!!!\n");
		printf("Enter valid age: ");
		scanf("%d",&age);
	}
	
	printf("Your age is: %d\n",age);
	
	return 0;	
}

    Enter age between 18-65: 10
    Invalid age!!!
    Enter valid age: 77
    Invalid age!!!
    Enter valid age: 25
    Your age is: 25



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.