How to do the following c++ programs? please help me?
Henry
2010-09-25 22:21:42 UTC
1)To print factorial of a number.
2)To accept two values and swap them using a third value
Three answers:
Maru
2010-09-25 22:42:52 UTC
// function recursive factorial
int factorial(int n){
if (n == 0)
return 1;
else
return n*factorial(n-1); //recursive so it just goes down the list from 9*8*7*6*5...ect
}
//function swap
void swap(int& a, int& b)
{
int temp = a; //stores a
a = b; //makes a to b
b = temp; //uses the previously stored a to make b have the value a.
}
Edit: what Chavon C said was right, I forgot about doing a reference to directly access the values... fixing it now..
now all you have to do is put these code on top of your main function and call it inside your main.
Chavon C
2010-09-26 06:12:52 UTC
Both answers above are only partially correct when it comes to second question. To truly swap the values you need to pass references to the "swap(int a, int b)" function. Calling such a function without references will leave the values you call it with the same as they were before. Simply change the function to: void swap(int& a, int& b);
Now when you call the function, the actually values of the passed variables get swapped, so if you were to output or use them again in the main function, the values would be switched.
The regular "void swap(int a, int b)" creates a copy when it is called, so the values don't get affected directly
lilac9109
2010-09-26 05:47:43 UTC
1)To make a factorial use a for loop:
int total = num;
for(int i = num-1; i>0; i --) This will go down from the number - 1 to 1
{ in here you multiply i with total and assign that to total
}
2) to accept two values and swap them using a third value:
You have value1 and value2 = to some numbers.
Now in order to swap them, you need the third variable (temp) to equal one of them to save the value.
temp = value2;
value2 = value1;
value1 = temp;
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.