Multiplyuser input by odd numbers C++ - 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.

Related

Trouble in looping while printing a series

I have to write a program in C++ that will print a sequence of 10 numbers based on user supplied variable input.
Expected output:
Input a number: 10
Series: 11 13 16 20 25 31 38 46 55 65
Here is my code so far:
#include <stdio.h>
int main()
{
int j, sum = 0, b=1;
for (j = 10; j <= 65; j=j+b++)
{
sum = sum + j;
printf("%d\n",j);
}
}
I've hardcoded it with respect to the given sample. How can I make it work for variable inputs?
Here is a solution that is almost complete, your part of job is to update one line where comment says /* ??? */
See code comments for more info:
#include <iostream>
int main()
{
// Starting value, ex. 10, chosen by user
int input = 0;
// Length of the sequence, also chosen by user
int length = 0;
// Sequence is incremented according to the pattern you already know
// for more info see:
// https://www.mathsisfun.com/algebra/sequences-sums-arithmetic.html
int adder = 0;
// Ask user to input starting number
std::cout << "Please enter the starting number: ";
std::cin >> input;
// TODO: verify user input is number
// Ask user for desired length of a sequence
std::cout << "Please enter the desired length of sequence: ";
std::cin >> length;
std::cout << "Generating sequence..." << std::endl;
// Generate sequence
// TODO: your part of job is to replace the ???
for (int counter = 0; counter < length; ++counter, input += /* ??? */)
{
// Show the current number in the sequence
std::cout << input << std::endl;
}
return 0;
}
I think this is the solution:
#include <iostream>
using namespace std;
int main() {
int n;
cin >>n;
int lastNumber=n;
for (int i=1; i<=n; i++) {
lastNumber+=i;
cout <<lastNumber <<' ';
}
endl(cout);
}

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.

How to count the frequency of the number x

I want to print the first number that first counts to 4, for example, I have this random function, I want to see the first number that reaches 4 times. so it's the first number that prints himself 4 times. For example:
int n;
int count1 = 0;
int count2 = 0;
int count3 = 0;
while (true) {
cout << "Enter a number btween 1-3" << endl;
cin >> n;
if (n == 1) {
count1++;
}
if (n == 2) {
count2++;
}
if (n == 3) {
count3++;
}
if (count1 == 4) {
cout << "You printed the number 1 4 times!";
break;
}
if (count2 == 4) {
cout << "You printed the number 2 4 times!";
break;
}
if (count3 == 4) {
cout << "You printed the number 3 4 times!";
break;
}
But what would I do if it was 1-1000 numbers not just 1-3 what would I do then?
I want to do that but on a random function - the first number that the count of that number is 4 times print the number -
int fun() {
srand(time(NULL));
return rand() % 3;
}
Then I want to do in main that first number that reaches for example 4 times print this number.
I tried doing something like this:
for (int i = 0; i < 31; i++) {
arr[fun()]++;
cout << arr[fun()];
if (arr[fun()] == 4) {
cout << arr[fun()];
}
}
You would use an collection (such as a vector) for that, rather than a thousand separate variables :-)
For a start, if you want random numbers in the range 1..3, you would use (rand() % 3) + 1. However, you can use the range 0..n-1 rather than 1..n and just adjust the value after the loop.
First step is to create and initialise the counts of each number to zero:
const int SZ = 1000;
std::vector<int> count(SZ, 0);
Then your loop just generates random numbers and adjusts the relevant count, until one of them reaches the target value:
int num;
for (;;) { // infinite loop
num = rand() % SZ;
++count[num];
if (count[num] == 4)
break; // exit infinite loop when one of them reaches four.
}
Then you just simply output the one that reached four first. Note that, since we're doing 0..999, we map that to 1.1000:
std::cout << ++num << " reached a count of four first\n";
A complete program showing this can be seen below:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(nullptr));
const int SZ = 1000;
std::vector<int> count(SZ, 0);
int num;
for (;;) { // infinite loop
num = rand() % SZ;
++count[num];
if (count[num] == 4)
break; // exit loop when one of them reaches four.
}
std::cout << ++num << " reached a count of four first\n";
}
A sample run of that (ensuring a delay so random number generator gets different seed):
>> for i in {1..10} ; do sleep 1 ; ./testprog ; done )
296 reached a count of four first
520 reached a count of four first
205 reached a count of four first
239 reached a count of four first
822 reached a count of four first
260 reached a count of four first
421 reached a count of four first
444 reached a count of four first
21 reached a count of four first
92 reached a count of four first
The last answer was out of range. My answer is using only an array
while(1) {
int f = rand() % 3;
count[f]++;
cout << f << endl;
if (count[f] == 4) {
cout <<"4 times" <<f;
break;
}
}

How to take numerous inputs without assigning variable to each of them in C++?

I'm beginning with C++. The question is: to write a program to input 20 natural numbers and output the total number of odd numbers inputted using while loop.
Although the logic behind this is quite simple, i.e. to check whether the number is divisible by 2 or not. If no, then it is an odd number.
But, what bothers me is, do I have to specifically assign 20 variables for the user to input 20 numbers?
So, instead of writing cin>>a>>b>>c>>d>>.. 20 variables, can something be done to reduce all this calling of 20 variables, and in cases like accepting 50 numbers?
Q. Count total no of odd integer.
A.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,odd=0;
cout<<"Number of input's\n";
cin>>n;
while(n-->0)
{
int y;
cin>>y;
if(y &1)
{
odd+=1;
}
}
cout<<"Odd numbers are "<<odd;
return 0;
}
You can process the input number one by one.
int i = 0; // variable for loop control
int num_of_odds = 0; // variable for output
while (i < 20) {
int a;
cin >> a;
if (a % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
If you do really want to save all the input numbers, you can use an array.
int i = 0; // variable for loop control
int a[20]; // array to store all the numbers
int num_of_odds = 0; // variable for output
while (i < 20) {
cin >> a[i];
i++;
}
i = 0;
while (i < 20) {
if (a[i] % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
Actually, you can also combine the two while-loop just like the first example.
Take one input and then process it and then after take another intput and so on.
int n= 20; // number of input
int oddnum= 0; //number of odd number
int input;
for (int i = 0; i < n; i ++){
cin >> input;
if (input % 2 == 1) oddnum++;
}
cout << "Number of odd numbers :"<<oddnum << "\n";

why is the error in this program 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