Home » C programming language

C function to validate integer input with minimum and maximum values

Here, I am writing a User Define Function to take integer input with minimum and maximum values validation.

If there is no validation and we enter an invalid value, program produces incorrect output (because there is no option to go back and enter the value again).

In this function, program will take input until correct value doesn't found.


Function Description/Prototype

int int_input(char *msg,int min,int max)

Here,

  • char *msg - Is the user input message that will appear when we input the value.
  • int min - Minimum input value to validate.
  • int max - Maximum input value to validate.
  • int (return type) - Function will return an integer value that can be stored in the actual variable declared in the parent (calling) function.

Function definition (code)

int int_input(char *msg,int min,int max)
{
	int temp;
	while(1)
	{
		printf("%s",msg);
		scanf("%d",&temp);		
		if(temp>=min && temp<=max)
			return temp;		
		else
		{
			printf("Incorret input!!!\n");
		}
	}
}

Explanation

As you can see, function has a infinite loop (while(1)), and reading an integer value with the message which is being passed in the function (through char *msg parameter), then function is checking value with minimum and maximum value (if(temp>=min && temp<=max)), if the condition is true, function will return the entered value, and if it is false program's control will move to the starting of the loop to take input again with an error message "Incorret input!!!".

Example using this function to take input

#include <stdio.h>

//function to take input with validation
int int_input(char *msg,int min,int max)
{
	int temp;
	while(1)
	{
		printf("%s",msg);
		scanf("%d",&temp);		
		if(temp>=min && temp<=max)
			return temp;		
		else
		{
			printf("Incorret input!!!\n");
		}
	}
}
int main()
{
	int a,b,sum=0;
	
	a=int_input("Enter first number: ",100,200);
	b=int_input("Enter second number: ",100,200);
	
	sum=a+b;
	printf("sum= %d\n",sum);
	return 0;
	
}

Output

Enter first number: 10
Incorret input!!! 
Enter first number: 250 
Incorret input!!! 
Enter first number: 120 
Enter second number: 200
sum= 320

COMMENTS




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