I am learning c++ since 6months, so I am an extreme beginner. So please bear with me if I am making a stupid and obvious question here.
Also I would like to say that I have studied loops but not arrays and pointers etc. So if the answer is out of my bounds, please convey that to me.
Thank you.
So, now to my question.
I have written this program here which calculates the lowest(other than 1) and highest(other than the number itself) factors of a given number.The program asks for a number larger than 1. What I want the program to do is if the user inputs a number smaller than 1 then it will run again saying that what the user has entered is wrong value. I have used the following method
[code]
//Calculating the highest and lowest factors of a given number in this program
//Also repeating the program from starting point if value input does not satisfy condition
//that is specified
#include<iostream.h>
int calculate()
{
int num, factors, factorl;
char response;
do{
cout<<"Enter a number larger than 1"<<endl;
cin>>num;
if (num>1)
{
factors=2;
factorl=num-1;
while(num%factors>0)factors++;
while(num%factorl>0)factorl--;
cout<<"The smallest factor of "<<num<<" is equal to "<<factors<<endl;
cout<<"The largest factor of "<<num<<" is equal to "<<factorl<<endl<<endl<<endl;
}
else
{
cout<<"Invalid input"<<endl;
calculate();}
cout<<"Do you want to calculate the smallest and largest factors again (y/n)"<<endl;
cin>>response;
}while(response=='y'||response=='Y');
return 0;
}
int main()
{
{
calculate();
}
return 0;
}
[code]
Is there any better way to do this.
Also is there a way to prevent the user from entering any character and asking him to enter again, in the same way as above?
Please help
Thank you
First, please edit your post and put [code] tags around your code. That will make it easier for others to read.
mishrashubham wrote:
is there a way to prevent the user from entering any character and asking him to enter again, in the same way as above?
The first recommendation I have here is to split the calculate() function into two functions: one that does user input and one that calculates the factors.