why is the error in this program c++? - c++

I don't understand this program, I don't get why number is initialized to 1 when the program takes user input.
This is how I understand the program which is obviously wrong:
You enter the factorial number, lets says I enter 6, it goes to the while loop because 6 is greater than 1.
Now factorial is 1, and number is 6, 6 * 1 = 6. Then 6 - 1 = 5, so factorial is 5 but i get 720 as output.
i don't think I understand the while loop
#include <iostream>
using namespace std;
int main()
{
// declaration of the variables
int factorial, number;
// initialization of the variables
factorial = 1;
number = 1;
// Prompt the user to enter the upper limit of integers
cout << "Please enter the number of the factorial";
cin >> number;
// using the while loop find out the factorial
while (number > 1)
{
factorial = factorial * number;
number = number - 1;
}
cout << "The factorial is " << factorial;
}

You are missing a "<" in last line of the program. It should be
cout<<"The factorial is "<<factorial;
After making this change when I compile and run the program it works for me correctly i.e computes the correct factorial. For example factorial of 5 i.e 5!=5*4*3*2*1=120

Your program works correctly.
6! = 6 * 5 * 4 * 3 * 2 = 720.
Btw, use recursion for such recursive problems.
#include <iostream>
using namespace std;
int main()
{
//declaration of the variabe
unsigned int number;
//prompt the user to enter the upper limit of integers
cout << "Please enter the number of the factorial";
cin >> number;
cout << factorial(number);
return 0;
}
unsigned int factorial(unsigned int n)
{
if (n <= 1)
{
return 1;
}
else
{
return n * factorial(n-1);
}
}

The initial assignment of number is indeed unnecessary. However, you should check the input operation for errors:
int factorial = 1;
int number;
if (!(std::cin >> number))
{
/* error! */
return 1; // i.e. abort the program
}
while (number > 1) { /* ... */ }

First of all, it is initialised to 1 because of the following condition:
Factorial(0) = 1
Factorial(1) = 1
So if a user inputs a number less than 2, you do not need some calculations, you just output 1

The first thing I noticed was that there is an error in your code:
cout<<"The factorial is " < factorial;
should be:
cout<<"The factorial is " << factorial;
Correcting this should fix a compile error.
The essence of this code is:
Get a number (int number) from user
Print print the factorial of number

Related

Multiplyuser input by odd numbers C++

I need to write a program that takes input from the user and multiplies it by numbers: 3, 5, 7, and 9. Here is my code:
#include <iostream>
int main()
{
int N;
std::cout << "Input a number: ";
std::cin >> N;
int limit = 9;
for(int i = 3; i <= limit; ++i)
{
if(i % 2 != 0) // if odd
{
N = N * i;
std::cout << N << std::endl;
}
}
return 0;
}
When I output this code, it displays:
Input a number: 1
3
15
105
945
However, what I am aiming for is this:
Input a number: 1
3
5
7
9
Any help would be greatly appreciated.
You over write your variable N at N = N * i. You should add a second variable to output your result and not overwrite your input.
Tip: You increment your loop by just one with ++i. If you replace that with i+=2 you only loop over the desired multiplication numbers. At this point you can also leave out the if statement.

How do I get the individual numbers from my fibonacci sequence to be listed?

This is what I was tasked to do:
The Fibonacci series (0,1,1,2,3,5,8,13,21, …) begins with 0 and 1 and has the property that each subsequent Fibonacci number is the sum of the previous two Fibonacci numbers.
Your task is to translate the series into a program, using recursion, that will calculate the Fibonacci value up to the input integer.
How do I get the individual digits and list it in the way shown in picture 2
#include <iostream>
using namespace std;
int fibonacci(int target, int num1, int num2);
int main()
{
int n;
cout << "Know the Fibonacci Sequence up to the nth
term." ;
cout << '\n';
cout << "Input n: ";
cin >> n;
cout << "The sequence up to fibonacci(" << n <<"):";
cout << '\n';
cout << fibonacci(n-1,0,1);
cout << '\n';
return 0;
}
int fibonacci(int target, int num1, int num2)
{
cout << num1 << " ";
if(target == 0)
{
return num1 + num2;
}
else {
fibonacci(target-1, num2, num1 + num2);
}
}
This is how my program runs for now
This is my goal
When you arrive to n = 0, you return the next Fibonacci number, because of your addition :
if(target == 0)
{
// here you have:
// num1 = 34
// num2 = 55
return num1 + num2;
}
To fix it, juste return num2.
If you have closely observed your output, the last Fibonacci number printed by your program is 89 which is the 12th number of Fibonacci series and not the 11th. In fact your program is printing 1 extra Fibonacci number then the what user is requested to print. As you can see, you have entered 10 as input and your program is printing 11 Fibonacci numbers starting from 0 (in which the last one is not in sequence).
Since, you just want to print the series, you don't need to return any thing from your fibonacci() function because you are printing the Fibonacci series numbers in the recursive calls as you are calculating them.
If you want to print the Fibonacci series numbers with sequence numbers (as you have shown in picture 2), modify fibonacci() function signature and add one more parameter which will be the sequence number of the current Fibonacci series number to be printed. Check this:
#include <iostream>
void fibonacci(int seqNum, int target, int num1, int num2);
int main() {
int n;
std::cout << "Know the Fibonacci Sequence up to the nth term." << std::endl;
std::cout << "Input n: ";
std::cin >> n;
std::cout << "The sequence up to fibonacci(" << n <<"):" << std::endl;
fibonacci(0, n, 0, 1);
std::cout << std::endl;
return 0;
}
void fibonacci(int seqNum, int target, int num1, int num2) {
if (target <= 0) {
return;
}
std::cout << seqNum << ".\t" << num1 << std::endl;
fibonacci(seqNum + 1, target - 1, num2, num1 + num2);
}
Output:
# ./a.out
Know the Fibonacci Sequence up to the nth term.
Input n: 11
The sequence up to fibonacci(11):
0. 0
1. 1
2. 1
3. 2
4. 3
5. 5
6. 8
7. 13
8. 21
9. 34
10. 55
The above program is just to show you a way to get output in the format you want. Note that, you need to take care invalid user input because if user give input greater than or equal to 48, it will result in overflow on a platform where the integer size is 4 bytes (as you have declared num1 and num2 as signed int type). I am leaving it up to you to take care of validity of user input. Also, if you want to print only positive Fibonacci numbers, it make sense to declared num1 and num2 as unsigned type rather than a signed type.

How to reverse my input including the negative

This is my code that I have currently but it always outputs 0 I'm trying to get it to output the reverse of the input including the negative for example -123425 will be 524321-:
#include<iostream>
using namespace std;
int main() {
int number;
bool negative;
cout << "Enter an integer: ";
cin >> number;
while (number != 0) {
number % 10;
number /= 10;
}
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
cout << number << endl;
return EXIT_SUCCESS;
}
You could convert the input to a std::string, then reverse its content with std::reverse.
#include <algorithm> // reverse
#include <cstdlib> // EXIT_SUCCESS
#include <iostream> // cin, cout, endl
#include <string> // string, to_string
using namespace std;
int main()
{
cout << "Enter an integer: ";
int number;
cin >> number;
auto str = to_string(number);
reverse(str.begin(), str.end());
cout << str << endl;
return EXIT_SUCCESS;
}
Reading to an int first - and not to a std::string - makes sure that we parse a valid integer from the input. Converting it to a std::string allow us to reverse it. This let us feed inputs like -042 and -0 to the program, and get 24- and 0 as a result, not 240- and 0-.
After the first loop
while (number != 0) {
number % 10;
number /= 10;
}
the variable number is equal to 0.
So the following if statement
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
does not make sense.
Pay attention to that it can happen such a way that a reversed number can not fit in an object of the type int. So for the result number you should select a larger integer type.
Here is a demonstrative program that shows how the assignment can be done.
#include <iostream>
int main()
{
std::cout << "Enter an integer: ";
int n = 0;
std::cin >> n;
bool negative = n < 0;
const int Base = 10;
long long int result = 0;
do
{
int digit = n % Base;
if ( digit < 0 ) digit = -digit;
result = Base * result + digit;
} while ( n /= Base );
std::cout << result;
if ( negative ) std::cout << '-';
std::cout << '\n';
return 0;
}
Its output might look like
Enter an integer: 123456789
987654321-
I think trying to visualize the process of your program is a great way to see if your solution is doing what you expect it to. To this end, let's assume that our number is going to be 12345. The code says that while this is not equal to 0, we will do number % 10 and then number /= 10. So if we have 12345, then:
number % 10 --> 12345 % 10 --> 5 is not assigned to any value, so no change is made. This will be true during each iteration of the while loop, except for different values of number along the way.
number /= 10 --> 12345 /= 10 --> 1234
number /= 10 --> 1234 /= 10 --> 123
number /= 10 --> 123 /= 10 --> 12
number /= 10 --> 12 /= 10 --> 1
number /= 10 --> 1 /= 10 --> 0 (because of integer division)
Now that number == 0 is true, we proceed to the if/else block, and since number < 0 is false we will always proceed to the else block and then finish with the cout statement. Note that the while loop will require number == 0 be true to exit, so this program will always output 0.
To work around this, you will likely either need to create a separate number where you can store the final digits as you loop through, giving them the correct weight by multiplying them by powers of 10 (similar to what you are hoping to do), or cast your number to a string and print each index of the string in reverse using a loop.
Quite simple:
int reverse(int n){
int k = abs(n); //removes the negative signal
while(k > 0){
cout<<k % 10; //prints the last character of the number
k /= 10; //cuts off the last character of the number
}
if(n < 0) cout<<"-"; //prints the - in the end if the number is initially negative
cout<<endl;
}
int main(){
int n = -1030; //number you want to reverse
reverse(n);
}
If you don't want to use String or have to use int, here is the solution.
You want to check the negativity before you make changes to the number, otherwise the number would be 0 when it exit the while loop. Also, the modulus would be negative if your number is negative.
number % 10 only takes the modulus of the number, so you want to cout this instead of just leaving it there.
The last line you have cout << number << endl; will cout 0 since number has to be 0 to exit the while loop.
if(number < 0) {
number = -number;
negative = true;
}
while (number != 0) {
cout << number % 10;
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}
EDIT: With a broader assumption of the input taking all int type values instead of the reversed integer being a valid int type. Here is a modified solution.
if(number < 0) {
negative = true;
}
while (number != 0) {
cout << abs(number % 10);
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}
using namespace std;
int main()
{
int number,flag=1;
long long int revnum=0;
bool negative;
cout << "Enter an integer: ";
cin >> number;
if(number<0)
{ negative=true;
}
while (number > 0) {
revnum=revnum*10+number %10;
number /= 10;
}
if (negative)
{ revnum=(-revnum);
cout << revnum << '-'<<endl;
}
else
{ cout<<revnum<<endl;
}
return 0;
}
A few changes I did -
checking the number whether it's negative or positive
if negative converting it to positive
3.reversing the number with the help of a new variable revnum
4.and the printing it according to the requirement
To reverse the num-
revnum=revnum*10 + number%10
then num=num/10
like let's try to visualize
1.take a number for example like 342
2.for 1st step revnum=0 so revnum*10=0 and num%10=2 , so revnum will be 2
and the number now is num/10 so 34
4.next now rev = 2 the rev*10=20 and num%10=4 then rev*10 + num/10 =24
5.finally we get 243
Hope it helps :)
edit:-
just a small edit to solve the problem of the overflow of int , made revnum as long long int.

c++, ask the user to input a set of numbers to sum (unknown number of input), however numbers wouldn't add up

I want to write a simple program where I ask the user to input a set of numbers to sum. The user can input an unknown number of numbers.
Here's my code:
#include <iostream>
using namespace std;
//ask the user to input a set of numbers to sum (unknown number of input)
int main (){
int sum = 0, value = 0;
while (cin >> value){
sum += value;
cout << "sum is " << sum << endl;
return 0;
}
}
However, when I input several numbers, the result always equal to the first number, not the sum of all numbers entered. As in:
5 6 7 8
sum is 5
What I am doing wrong?
The problem is return 0. Put it outside of the while block.
You are doing it wrong. You must have to put the print method outside of the loop and the return too.If you want user to terminate at any time he wants then you need to take input at an specific keyword or any other keyword other than the data type(like char at place of integer) , so that it will terminate the loop.
#include <iostream>
using namespace std;
int main (){
int sum = 0, value = 0;
/*press any key other than number to terminnate*/
while (cin >> value){
sum += value;
}
cout << "sum is " << sum << endl;
return 0;
}

loop in c++ that keeps track when the count is divisible by 4

Hello I am having trouble with a c++ program. Basically its a loop that iterates the amount of times the user wants it to. Now when it reaches a number divisible by 4 it keeps track of that number and finally then outputs how many times the number entered was divisible by 4.
#include<iostream>
using namespace std;
int num;
int count;
int test = 0;
int main()
{
cin>> num;
for (int count = 0; count < num; count++)
if (count % 4 == 0)
(test++);
else
cout<<"";
return 0;
}
Well - if you use return in main, your program will just exit, because that's what return does - ends the function and returns some value. If you want to actually print the value of test, do it before you return:
cout << test;
getch(); // use this so the console won't close automatically
return 0;
Also, the whole program could be written much better:
int main()
{
cin>> num;
cout << num/4;
getch(); // use this so the console won't close automatically
return 0;
}
Do you need to use a loop? If you just need "How many times is a given number divisible by 4" and are not required to loop
#include<iostream>
using namespace std;
int main()
{
int num;
cin>> num;
cout<< num<<" is divisible by 4 "<< (num>>2) <<" time"<<(num>>2>1?"s":"") <<endl;
return 0;
}
num>>2 is bit shifting to teh right twice, which is the same as doing an integer divide by 4. It could be replaced by num/4 if you wanted. Integer division always truncates, so for all positive numbers, it's like rounding down: the same behavior your loop gives you.