Program to print Factorial of a number in c++ - c++

Q) Write a program that defines and tests a factorial function. The factorial of a number is the product of all whole numbers from 1 to N.
For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120
Problem: I am able to print the result,but not able to print like this :
let n = 5
Output : 1 * 2 * 3 * 4 * 5 = 120;
My Code:
# include <bits/stdc++.h>
using namespace std;
int Factorial (int N)
{
int i = 0;int fact = 1;
while (i < N && N > 0) // Time Complexity O(N)
{
fact *= ++i;
}
return fact;
}
int main()
{
int n;cin >> n;
cout << Factorial(n) << endl;
return 0;
}

I am able to print the result,but not able to print like this : let n
= 5 Output : 1 * 2 * 3 * 4 * 5 = 120;
That's indeed what your code is doing. You only print the result.
If you want to print every integer from 1 to N before you print the result you need more cout calls or another way to manipulate the output.
This should only be an idea this is far away from being a good example but it should do the job.
int main()
{
int n;cin >> n;
std::cout << "Factorial of " << n << "!\n";
for (int i =1; i<=n; i++)
{
if(i != n)
std::cout << i << " * ";
else
std::cout << n << " = ";
}
cout << Factorial(n) << endl;
return 0;
}
Better approach using std::string and std::stringstream
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cin >> n;
stringstream sStr;
sStr << "Factorial of " << n << " = ";
for (int i = 1; i <= n; i++)
{
if (i != n)
sStr << i << " * ";
else
sStr << i << " = ";
}
sStr << Factorial(n) << endl;
cout << sStr.str();
return 0;
}

Related

(C++) Problem with if statement ,simple == condition

I have something which outputs all the factors for an integer using a fixed loop.
in this case, int_end_int_ = 4
and middle_x_coefficient = 4
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0) // This gets the factors
{
//here
}
}
i have that inside the if loop that if i * 2 == 4, print a string. So i thought that when i = 2, it will output the string.
//inside if loop
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i; //ignore
cout << "prerooted";
preroot2 = i; //ignore
}
It does not output "prerooted", and i have no clue why.
Full Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Quadratic Equation Solver ( to roots )" << endl;
cout << "Enter quadratic equation, e.x (x^2 + 4x + 4) must be in this form" << endl;
string equation;
cout << ">> ";
getline(cin, equation);
if (equation.length() < 12)
{
cout << "Please enter valid string." << endl;
while (equation.length() < 12)
{
cout << ">> ";
getline(cin, equation);
}
}
char middle_x_coefficient = equation[6]; // getting x^2 + 4(this<-)x + 4
char end_int_ = equation[11]; // getting x^2 + 4x + 4 <-- this
int preroot1 = 0;
int preroot2 = 0;
int int_end_int_ = static_cast<int>(end_int_); //convert char to int using static cast for like no reason
//nvm <- https://stackoverflow.com/questions/103512/why-use-static-castintx-instead-of-intx this says it is better bc compiler bad or smthn
int_end_int_ -= 48; //This converts the ascii value (52 for 4) to 4 (-48)
int pasti = 0;
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0)
{
cout << i << "this<- i" << endl;
cout << middle_x_coefficient << "this<- x" << endl;
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i;
cout << "prerooted";
preroot2 = i;
}
else if (i + pasti == middle_x_coefficient) {
preroot1 = i;
preroot2 = pasti;
}
pasti = i;
}
}
cout << preroot1 << " " << preroot2 << endl;
return 0;
}
You converted the character end_int_ to the integer int_end_int_, but you didn't convert the character middle_x_coefficient to an integer. Convert and use converted integer just as you did for end_int_.
Instead of using magic number 48, using character literal '0' is better.

Separate the digits of an integer (C++)

I need to write a program that takes an integer as input and outputs it with its digits spaced. The algorithm works fine but prints the digits in reverse order. To get the original order, I used a for loop. The problem is that it prints nothing.
#include <iostream>
using namespace std;
int countDigit(int n)
{
int count = 0;
while (n != 0) {
n = n / 10;
++count;
}
return count;
}
int main()
{
int Num ;
int sum = 0;
int arr[100];
cout <<"Enter an integer: " ;
cin >> Num ;
int c = countDigit(Num) ;
for (int i = c; i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
cout << " Your digits:";
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
return 0;
}
My issue is here
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
It prints nothing. What could be the problem ?
The input used is 1234
The expected output is 1 2 3 4
For starters the function countDigit is wrong.
int countDigit(int n)
{
int count = 0;
while (n != 0) {
n = n / 10;
++count;
}
return count;
}
It returns 0 for the valid number 0 that has one digit.
The function can look the following way
size_t countDigit( int n, int base = 10 )
{
size_t count = 0;
do
{
++count;
} while ( n /= base );
return count;
}
In this loop
for (int i = countDigit(Num); i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
the variable Num was changed. So in the next loop
for (int x = 1 ; x <= countDigit(Num) ; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
it will not have the original value You need to use an intermediate variable to make the calculation.
Also take into account that the use can enter a negative number.
EDIT: After you updated your code then you also need to move the output of the sum from the loop
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
}
cout << sum ;
And instead of the large integer array it is better to use an object of the type std::string.
Here is a demonstrative program
#include <iostream>
#include <string>
size_t countDigit( int n, int base = 10 )
{
size_t count = 0;
do
{
++count;
} while ( n /= base );
return count;
}
int main()
{
const int Base = 10;
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
size_t count = countDigit( num );
std::string s( count, ' ' );
int sum = 0;
for ( ; count-- != 0; num /= Base )
{
int digit = num % Base;
if ( digit < 0 ) digit = -digit;
s[count] = digit + '0';
sum += digit;
}
std:: cout << "Your digits: ";
for ( const auto &c : s ) std::cout << c << ' ';
std::cout << '\n';
std::cout << "The sum of digits is " << sum << '\n';
return 0;
}
Its output might look like
Enter an integer: -123456789
Your digits: 1 2 3 4 5 6 7 8 9
The sum of digits is 45
Another approach is to write a recursive function that outputs digits and returns the sum of digits.
#include <iostream>
unsigned int recursive_sum( long long int n, long long int base = 10, std::ostream &os = std::cout )
{
long long int digit = n % base;
if ( digit < 0 ) digit = -digit;
unsigned int sum = digit + ( ( n /= base ) == 0 ? 0 : recursive_sum( n ) );
os << digit << ' ';
return sum;
}
int main()
{
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
unsigned int sum = recursive_sum( num );
std::cout << '\n';
std::cout << "The sum of digits is " << sum << '\n';
return 0;
}
Again the program output might look like
Enter an integer: -123456789
1 2 3 4 5 6 7 8 9
The sum of digits is 45
This gives the expected output. I assigned countDigit(Num) to c and wrote the sum to outside the loop.
int main()
{
int Num ;
int sum = 0;
int arr[100];
cout <<"Enter an integer: " ;
cin >> Num ;
int c = countDigit(Num); //edit 1
// extracts the digits
for (int i = c; i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
cout << "Your digits with spaces: ";
// reverses the order
for (int x = 1 ; x <= c ; x++)
{
cout << arr[x] << " " ;
}
cout << endl << "The sum of the digits is: " << sum ; // edit 2
return 0;
}
Here's a shorter version:
#include <concepts>
#include <cstdio>
#include <string>
template <std::integral T>
void printDigits(T const i) {
for (auto const ch : std::to_string(i)) {
std::printf("%c ", ch);
}
std::fflush(stdout);
}
LIVE
Here's a take that uses strings.
#include <iostream>
#include <string>
int main()
{
std::string input;
std::size_t location;
std::cout << "Enter an integer: ";
std::getline(std::cin, input);
std::stoi(input, &location); // Don't care about the integer, just location
if (location != input.length()) {
std::cout << "Invalid Entry: Non-integer entered\n";
return 1;
}
for (auto i : input) {
std::cout << i << ' ';
}
// Here's a one liner that requires <algorithm>
// std::for_each(input.begin(), input.end(), [](auto i) { std::cout << i << ' '; });
std::cout << '\n';
}
I don't care about an integer at all. I can validate that only digits were entered and quit early if not. The only loop I need is for printing.
stoi() can return the integer, but I don't care about the integer. I just want to know how many characters were converted, and I learn that by feeding it the output argument location. Checking that location is the same as the string length ensures that only digits were entered. No decimal points, no extra letters, just numbers.
The caveats are that this might not fit into your requirements if this is an assignment. It also requires C++11, which is surprisingly not a given yet (for assignments, I get the industry arguments).

Run-Time Check Failure #2 - Stack around the variable 'numberchoices' was corrupted

I am having this terminal error every time I finish the debug program.
What I am doing:
[this program is a simple Lottery Numbers Comparison between user input numbers with the non-repeated random lottery numbers. e.g. using what if it got 4 right of 6]
but it turns out that the program is not working or at least, be stable.
Here's my code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <time.h>
#include <ctime>
#include <algorithm>
using namespace std;
int main()
{
cout << "[La Loteria Electronica]\n";
cout << "Escoge 6 n" << char(163) << "meros del (1 al 49): \n";
int numberchoices[] = { 0 };
for (int w = 1; w < 7; w++)
{
cout << "N" << char(163) << "mero #" << w << ": ";
cin >> numberchoices[w];
} // user numbers
//lottery numbers
int i, j, k, nums[51];
srand((int)time(0));
for (i = 1; i < 50; i++) nums[i] = i;
for (i = 1; i < 50; i++)
{
j = (rand() % 49) + 1;
k = nums[i]; nums[i] = nums[j]; nums[j] = k;
}
cout << "The lottery numbers are: ";
for (i = 1; i < 7; i++) cout << nums[i] << " ";
if (numberchoices[i] = nums[i])
{
cout << "gud\n";
}
if (numberchoices == nums)
{
cout << "gud 2";
}
/**/
cout << "\n\n";
system("pause");
Please ?
int numberchoices[] = { 0 };
for (int w = 1; w < 7; w++)
{
cout << "N" << char(163) << "mero #" << w << ": ";
cin >> numberchoices[w];
} // user numbers
You're declaring an array of size 1 and then you use it up to position 6 ?
I am having this terminal error every time I finish the debug program.
I'm surprised that you're not having a terminal error every time you start debug.
The access of numberchoises at positions from 1 to 6 are UB (Undefined Behavior). That is: all can happens.
Solution: try with
int numberchoices[7] = { }; // initialize all elements to zero!
Another point
if (numberchoices == nums)
not sure that you get what do you expect.
Do you want compare the integer pointer corresponding to numberchoices (a int[1], suggested int[7]) with the one corresponding to nums (a int[51]) ?

C++ : Count even / odd numbers in a range

My program has to count how many numbers in a range are even and how many of them are odd but I can't seem to figure it out.It kinda works
but when I put numbers in it spouts out nonsense. I'm an extreme nooob when it comes to programing, I think that the problem has to be at line 21 for (i=n; i<=m; i++) { ?
But I'm not sure. I have a programing book but it does not help much,maybe someone can help?
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i;
}
else {
b=b+i;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
Assuming you mean even and odd numbers your problem lies in this code:
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i; // increase number of even numbers by i
}
else {
b=b+i; // increase number of odd numbers by i
}
}
What you might want do to do is add 1 (instead of whatever i is):
for (i = n; i <= m; ++i) {
if (i % 2 == 0)
++a; // increase number of even numbers by one
else
++b; // increase number of odd numbers by one
}
Also I'd suggest using better variable names, for example even and odd instead of a and b and so on. It makes code easier to understand for everybody, even for you.
Just a little more tips. Assigning variables as soon as you declare them is good practice:
int m = 0;
You can declare variable inside of for loop, and in your case there is no need to declare it out of it:
for (int i = n; i <= m; ++i) { ... }
Example how it can change look and clarity of your code:
#include <iostream>
using namespace std;
int main() {
int from = 0,
to = 0,
even = 0,
odd = 0;
cout << "Enter a number that begins interval: ";
cin >> from;
cout << "Enter a number that ends interval: ";
cin >> to;
for (int i = from; i <= to; ++i) {
if (i % 2 == 0)
++even;
else
++odd;
}
cout << " even numbers: " << even << endl;
cout << " odd numbers: " << odd << endl;
return 0; // don't forget this! main is function returning int so it should return something
}
Ok, so as per the new clarification the following should work
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a++;
}else {
b++;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}
So the following changes were done:
The for loop was closed
a = a + i or b = b + i was wrong as you are adding the counter value to the count which should be a++ or b++. Changed that also
The last two lines where you are showing your result was out of the main method, brought them inside the main method
Hope you find this useful.
You don't need to use loop to count even and odd numbers in a range.
#include <iostream>
int main ()
{
int n,m,even,count;
std::cin >> n >> m;
count=m-n+1;
even=(count>>1)+(count&1 && !(n&1));
std::cout << "Even numbers: " << even << std::endl;
std::cout << "Odd numbers: " << count-even << std::endl;
}
#include <iostream>
using namespace std;
int main()
{
int n, i;
cin >> n;
cout << " even : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 == 0)
cout << i << " ";
}
cout << " odd : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 != 0)
cout << i << " ";
}
return 0;
}
//input n = 5
// output is even : 2 4 6 8 10
// odd : 1 3 5 7 9
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a = 0;
b = 0;
for (i = n; i < = m; i++) {
if (i%2 == 0){
a = a + 1;
} else {
b = b + 1;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}
Not sure why you are looping through all the elements (half of them are going to be even and the other half odd). The only case where you have to consider when the interval length is not divisible by two.
using namespace std;
int main()
{
int n;
int m;
int x;
int odds;
int evens;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
cout << n << " " << m << endl;
x = m - n + 1;
odds = x / 2;
evens = odds;
if (x % 2 != 0) {
if (n % 2 == 0) {
evens++;
} else {
odds++;
}
}
cout << " even numbers: " << evens << endl;
cout << " odd numbers: " << odds << endl;
}
This is a more readable version of #Lassie's answer

Recursively print Factorial values in decreasing order?

Using C++ to figure out the factorial is straightforward enough. To print the values coming up (if factorial is 5) ... 1 * 2, * 3, * 4 * 5 also no problem - as I think I've done below.
But what I'm having a hard time doing is saying show me 5 * 4 then value * 3 then value * 2 etc. I want to be able to print the data going down and I can't seem to figure it out.
#include <iostream>
using namespace std;
int factorial(int n);
int main()
{
int number;
cout << "Enter an integer value ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number) << endl;
}
int factorial(int n)
{
if (n == 0)
return 1; // Base case
else
{
n = n * factorial(n - 1); // Recursive case
cout << " going up" << n << " ";
return n;
}
}
There are a couple of other posts but I didn't find one asking the same thing.
The desired results are: 20 60 120
The current results are 1 2 6 24 120
Please advise.
Thank you.
Just change where you are printing the value
else
{
n = n * factorial(n - 1); // Recursive case
cout << " going up" << n << " ";
return n;
}
to
else
{
cout << " going down" << n << " ";
n = n * factorial(n - 1); // Recursive case
return n;
}
The above would print 5 4 3 2 1 but if you want something like
5 20 60 ...
Than you have to change the recursive definition a bit.
#include<iostream>
using namespace std;
int factorial(int n,int temp);
int main()
{
int number;
cout << "Enter an integer value ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number,1) << endl;
}
int factorial(int n,int temp)
{
if (n == 0)
return temp; // Base case
else
{
cout << " going down" << n * temp << " ";
factorial(n - 1,n*temp); // Recursive case
//return n;
}
}