Hi! I am working on an assignment in class and received most of this code. I just have to add in some loops to complete it. I have a general idea of loops and finished the first 2 to-do's. Im having trouble finishing it though.
// Factors30 - Find perfect numbers between 2 and 30.
//
// Learning objectives:
// - Understanding the problem statement (i.e. business requirements)
// - Use of global variables (e.g. factors array) and global constants (e.g. MAXFACTOR)
// - Understand loops and nested loops
// - Understand importance of for loop expressions (initializer, test condition, incrementer)
#include <cstdio>
#include <cstdlib>
usingnamespace std;
constint MAXFACTOR = 30;
// Factors array is to store the proper factors of the number under consideration.
// It is defined for 30 elements because, at most, the largest number 30 can have at most 30 factors
int factors [MAXFACTOR];
// This is the count of the actual number of proper factors.
int count;
// This is the sum of the proper factors
int sum;
int main() {
// Below is the loop that generates the candidate numbers
for (int number=2; number <= MAXFACTOR; number++) {
// print out the number under consideration
printf("Number: %d\n", number);
}
// since we have a new candidate zero out the factors of the previous number
// TODO: write a loop to zero out the factors array
for (int i=0; i<MAXFACTOR; i++) {
factors[i] = 0;
}
// now determine the factors of number. Start by setting the sum to zero.
count = 0;
// TODO: write another loop that tests possible factors using the modulus % operator
for (int i+1; i<number; i++) {
if (number % i == 0) {
factors[count] = i;
count++;
}
}
// if you find a proper factor store it in the factors array so it can be printed later
// at this point have found the factors of number
printf("Factors: ");
// TODO: print the factors of the number. Requires another loop.
printf("\n");
// if there is just one proper factor then the number is prime.
// TODO: print if the number is prime.
// compute the sum of the factors. Initialize the sum of factors to zero.
sum = 0;
// TODO: compute the sum of the PROPER factors
// if the sum==number the number is perfect
// TODO: test if the number is perfect. If it is print it.
}
system("pause");
return 0;
}
On line 38 (and later too) you do refer to 'number'. The currently studied number. One selected from [2..MAXFACTOR]. But you don't have a number. You had a number inside the first loop, on lines 27-28.
Resolution: everything on lines 30-56 should be within lines 27-28.
I really don't mean to post again, but i am still having trouble with finding loops that would properly fit into the todo: portions of this code. Could someone guide me?