Write a program that asks a user to enter an integer, and then print out a list of all the factors of such number, which means a list of all the number that can evenly divide into such number. For Example, if user enters 9, then your program should print out a list of fallowing numbers: 1,-1, 3, -3, 9, -9. Answer
I should use while looping statement There is mistake but I don’t know where
#include<iostream> using namespace std; int main(void) { int input=0, i=1; cout<< "This program displays a list of all the factors of a user–given number.\nplease enter a number for a list of factors: "; cin>>input; cout<< "\nThe factors for"<<input<<"are:\n"; while((input%i>0) && (i<=input)){ cout<<i<<endl; cout<<"-"<<i<<endl; i++; } return 0; }
(input%i>0) Will evaluate to false if the number you're testing isn't perfectly divisible by whatever i is. At first, it'll work with 1 since anything mod 1 is 0. But when you get to two, your program will stop because that part of the while is no longer true (unless the number is even). Instead of a while loop, use a for loop. This way it only ends when it tests all numbers.
If you MUST use a while loop, remove the first part of it and put it in and if placed INSIDE of the while loop. That way coming across a number that isn't a perfect divisor won't exit the loop.
Join our real-time social learning platform and learn together with your friends!