While Loops II

Sentinel

Diamond Member
Jun 23, 2000
3,714
1
71
Im not a CS major ;)

need help with
// Output: 1 2 6 24 120 ... (n - 1)!
// First n factorials

heres my bad code

{
int i = 1;
while (i < n){
std::cout << i << ' ';
// take the output and multiply that by the next number
// 1 * 2 = 2, 2 * 3 = 6, 6 * 4 = 24, 24 * 5 = 120
i = ? }
std::cout << i << ' ';
}

and second

// Output: 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10
// Goes up by 2 and then down by 1 alternatively

{
int i = 0;
while (i < n){
std::cout << i << ' ';
i = ?
 

MrChad

Lifer
Aug 22, 2001
13,507
3
81
Wow, wouldn't it be nice if there were a forum just for Programming questions?
 

Kelemvor

Lifer
May 23, 2002
16,928
8
81
Getting some error message or what do you need help with? Doesn't look like N is defined anywhere on first glance.
 

Sentinel

Diamond Member
Jun 23, 2000
3,714
1
71
it is defined but the code is about 3 pages long wher it is, i just need the loop to work lol
 

purbeast0

No Lifer
Sep 13, 2001
53,654
6,532
126
lol dude first of all .. n^2 does not equal n! . i know you arent' a comp sci major, but that is just plain math that i have known since highschool ...

do nested while loops for the first one.

------------------------
int counter = 1;
int answer = 1;

while (counter != n) {

int timer = counter;

while (timer != 0) {

answer = answer * timer;
timer--;
}

cout << answer << endl;
answer = 1;
counter++;
}
--------------

you can figure out the 2nd one yourself
 

Gibson486

Lifer
Aug 9, 2000
18,378
2
0
There is a special formula for factorials. It is very handy for programming, but i do not know teh formula off teh top of my head.

for the second,

i=0

do {

cout << i;

i=i+2;

cout << i;

i=i-1;

}while (i<=...whatever)

syntax might be wrong, but that is the idea.
 
Aug 25, 2004
11,151
1
81
this would be so much easier with recursion.... in any case, one approach to hard code 0! = 1 and 1! = 1 and enter your loop from n = 2