Trouble in looping while printing a series - c++

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);
}

Related

Subtract each elements of an array consecutively

I have an array and I want to subtract each of the elements consecutively, ex: {1,2,3,4,5}, and it will result to -13 which is by 1-2-3-4-5.
But I don't declare or make those numbers fixed as they're taken from the input (user). I only make it like, int array[100] to declare the size.
Then, to get the inputs, I use the for loop and insert them to the array. Let's say first input is 10, then array[0] must be 10 and so on.
The problem is, how do I subtract them? I have two options:
The first element of the array (array[0]) will subtract the next element (array[1]) right after the user input the second element, and the result (let's say it's int x) will subtract the next element (array[2]) after the user input it and so on.
I'll have the user input all the numbers first, then subtract them one by one automatically using a loop (or any idea?) *These elements thing refer to the numbers the user input.
Question: How do you solve this problem?
(This program will let the user input for as much as they want until they type count. Frankly speaking, yeah I know it's quite absurd to see one typing words in the middle of inputting numbers, but in this case, just how can you do it?)
Thanks.
Let's see my code below of how I insert the user input into the array.
string input[100];
int arrayInput[100];
int x = 0;
for (int i = 0; i >= 0; i++) //which this will run until the user input 'count'
{
cout << "Number " << i+1 << ": ";
cin >> input[i];
arrayInput[i] = atoi(input[i].c_str());
...
//code to subtract them, and final answer will be in int x
...
if (input[i] == "count")
{
cout << "Result: " << x << endl;
}
}
You can/should use a dynamic sized container like std::vector as shown below:
#include <iostream>
#include <vector>
int main()
{
int n = 0;
//ask user how many input he/she wants to give
std::cout << "How many elements do you want to enter: ";
std::cin >> n;
std::vector<int> vec(n); //create a vector of size n
int resultOfSubtraction = 0;
//take input from user
for(int i = 0 ; i < n ; ++i)
{
std::cin >> vec.at(i);
if(i != 0)
{
resultOfSubtraction-= vec.at(i);
}
else
{
resultOfSubtraction = vec.at(i);
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}
Execute the program here.
If you want a string to end the loop then you can use:
#include <iostream>
#include <vector>
#include <sstream>
int main()
{
std::vector<int> vec;
int resultOfSubtraction = 0, i = 0;
std::string endLoopString = "count";
std::string inputString;
int number = 0;
//take input from user
while((std::getline(std::cin, inputString)) && (inputString!=endLoopString))
{
std::istringstream ss(inputString);
if(ss >> number)
{
vec.push_back(number);
if(i == 0)
{
resultOfSubtraction = number;
}
else
{
resultOfSubtraction-= number;
}
++i;
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}

How to receive input with whitespaces that are then stored into a vector?

I am new to C++, but this picture here is the goal of my program.
This is what I need my input/output to look like:
--- INPUT ---
The first line of standard input contains an integer 1 ≤ C ≤ 50, the number of test cases.
C data sets follow. Each data set begins with an integer, N, the number of people in the class (1 ≤ N ≤ 1000).
N integers follow, separated by spaces or newlines, each giving the final grade (an integer between 0 and 100) of a student in the class.
--- OUTPUT ---
For each case you are to output a line giving the percentage of students whose grade is above average, rounded to exactly 3 decimal places.
This is the code that I currently have:
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using std::vector;
void aboveAverage(int testCases) {
// initialize number of students for vector size
int numOfStudents;
// initialize a vector to hold grades
vector<int> grades;
// for # of testCases, recieve # of students per test case
for(int i = 0; i < testCases; i++) {
std::cout << "Num of Students: ";
std::cin >> numOfStudents;
// per test case, recieve grade per student and push into vector
for(int j = 0; j < numOfStudents; j++) {
int grade1;
std::string grade;
// debug statement
std::cout << "Enter grades: ";
std::getline(std::cin, grade);
grade = int(grade1);
grades.push_back(grade1);
}
}
// sum the vector array and intitialize above average threshold
int sum = std::accumulate(grades.begin(), grades.end(), 0);
// debug statement
std::cout << "Sum = " << sum << std::endl;
int threshold = sum / numOfStudents;
// initialize a counter and based on threshold get the # of elements that
// meet that criteria
int counter = 0;
for(int j = 0; j < numOfStudents; j++) {
// if the grade is larger than the threshold, add to counter
if(grades[j] > threshold) {
counter += 1;
}
}
// get the percentage of those above average and print it out
float percentage = (counter / numOfStudents) * 10;
std::cout << std::setprecision(3) << std::fixed << percentage << std::endl;
}
int main() {
int testCases;
// debug statement
std::cout << "# of Test Cases: ";
std::cin >> testCases;
aboveAverage(testCases);
return 0;
}
The code as a whole runs "fine", I guess you could say. Just no errors in the compiler that yell at me at least. I just cannot, for the life of me, figure out how to set it up exactly like it should for the input. I think I complicated my life with the vector, although it seems easier to me this way. I think I'm close. Hopefully I am!

Number Guessing game does not output right

Im trying to create a number guessing game where the user enters number integers they want to guess and the range of those integers 1 to (m). Then the computer randomly generates numbers in that range for the user to guess. The user guesses until they get all the numbers correct For example:
Enter number integers: 4
Enter the range of those integers from 1 to (m): 6
Enter guess: 2 3 1 4
3 of your guesses are correct. Guess Again
Enter guess: 2 3 1 6
Correct. Would you like to play again.
The Output I get right now is:
Enter number integers: 4
Enter the range of those integers from 1 to (m): 6
Enter your guesses for the 4 in the range from 1 to 6 that you have selected: 2 3 1 4
There are three files for this game.cpp, game.h, and driver.cpp. Please let me know if you find anything else wrong with my code. This is my 1st program I have written in C++.
//game.cpp
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "Game.h"
#include <iostream>
#include <iomanip>
#include <vector>
//---------------------------------------------------------------------------------------------
// generateNumbers: Fucntion to generate numbers between 1 to (m) and
// generate as many has user wanted.
// n: the amount of integers
// m: the max number the user wants
// numbers: returns the numbers generated by the computer
//---------------------------------------------------------------------------------------------
std:: vector<int> Game::generateNumbers(int n, int m) {
// Declare array size to generate random numbers based on what is between 1 to (m)
std::vector<int> random_numbers;
int numbers;
// Randomly generate n intgers between 1 to (m)
for (int i = 0; i < n; i++) {
numbers = (rand() % m) + 1;
random_numbers.push_back(numbers);
}
return random_numbers;
}
//-----------------------------------------------------------------------------------------------
// guessingGame: See's how many numbers the user got to correct until they win the game.
// n: the amount of integers
// m: the max number the user wants
//-----------------------------------------------------------------------------------------------
void Game::guessingGame(int n, int m) {
// Declare variables
std::vector<int> pointer;
int correct_answers = 0;
// Set inputGuess equal to a vector which is teh size of n
std::vector<int> inputGuess;
inputGuess.resize(n);
pointer = generateNumbers(n, m);
// Get user guesses integers
for (int i = 0; i < n; i++) {
std::cin >> inputGuess[i];
}
// See if the user guesses and computers answers match up
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (pointer[i] == inputGuess[j]) {
correct_answers++; //counts how many numbers the user got correct
}
}
}
}
// driver.cpp
#include <iostream>
#include "Game.h"
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <iomanip>
#include <vector>
int main()
{
//Declare variables
Game guess;
int n; // number of integers
int m; // max value for integers
int guesses;
std::vector<int> userNumbers;
std::srand(static_cast<unsigned int>(time(nullptr))); // Intialize random number
// Prompt the user to enter integers and range
// Have user enter number of integers they want
std::cout << "Enter the Number of the Integers (n): ";
std::cin >> n;
// Have user enter the range if integers between 1 to m
std::cout << "Enter the Number of Each Integers from 1 to (m): ";
std::cin >> m;
// guesses from user are not correct then user needs to keep guessing
while (userNumbers.size() != n) {
std::cout << "Enter your guesses for the " << n << " " << "in the range from 1 to " << m << " " << "that you have been selected: ";
for (int i = 0; i < n; i++) {
userNumbers.push_back(n);
guess.guessingGame(n,m);
}
}
// If the user has guessed the correct numbers and would like to play again
if (userNumbers.size() == n) {
std::cout << "You are correct! Play Again?";
}
// If numbers guessed not correct then display how many are correct
else {
std::cout << sizeof(userNumbers) << "of your guesses are correct." << std::endl;
}
};
// game.h
#include <vector>
class Game {
public:
// Get what numbers the users have guessed are correct
std::vector<int> getNumbers() {
return correct_number;
}
// Generate random numbers between the range set by user
std:: vector<int> generateNumbers(int n, int m);
// Begin the guessing game
void guessingGame(int n, int m);
private:
std::vector<int> correct_number; // numbers that are correct
std::vector<int> input_guess;
};
The line
inputGuess.push_back(n);
adds only one element, but you are using n elements here:
// Get user guesses integers
for (int i = 0; i < n; i++) {
std::cin >> inputGuess[i];
}
Therefore an out-of-range access happens when n is larger than 1.
To set the number of elements to n, you should use resize() instead like this:
inputGuess.resize(n);

C++ Can't retrieve private variable from class [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am writing a program that generates integers and sets the range of the user's choosing.
For example:
Enter the number of integers: 4
Range: 10
4 9 2 1 are generated
Now the user chooses 4 digits at a time until they're correct.
Program will also tell user if they are partially correct.
For example:
User input: 4 9 0 7
Console << 2 of your answers are correct.
I have three files:
Driver.cpp
#include <iostream>
#include "Game.h"
using namespace std;
int main()
{
// Declare variables.
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) {
cout << "Enter the Number of Integers (n): " << endl;
cin >> numberOfIntegers;
cout << "Number of Each Integers from 1 to (m): " << endl;
cin >> rangeOfIntegers;
cout << "Enter your guesses for the " << numberOfIntegers << " integers in the range from 1 to " << rangeOfIntegers << " that have been selected:" << endl;
guess.beginGuessingGame(rangeOfIntegers, numberOfIntegers);
}
if (count == numberOfIntegers) {
cout << "You are correct! Play again? (y/n)";
}
else {
cout << count << " of your guesses are correct." << endl;
}
};
Game.h
// identifiers
#ifndef guessing_game
#define guessing_game
class Guess
{
private :
int * generatedSequence;
int * inputGuess;
int sum;
public :
void generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers);
void beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers);
int getSum() {
return sum;
}
};
#endif
and Game.cpp
#include <iostream>
#include <iomanip>
#include "Game.h"
using namespace std;
void Guess::generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Initialize random number generator.
srand(time(0));
/// Declare array size for the generated sequence to be based on user input.
generatedSequence = new int[inputRangeOfIntegers];
/// Input randomly generated numbers from from 0 to input range into generatedSequence.
for (int i = 0; i < inputNumberOfIntegers; i++) {
generatedSequence[i] = rand() % inputRangeOfIntegers + 1;
cout << generatedSequence[i] << " " << endl;
}
}
void Guess::beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Call our generateSequence function.
generateSequence(inputRangeOfIntegers, inputNumberOfIntegers);
/// Declare guess size based on user input.
inputGuess = new int[inputNumberOfIntegers];
/// Begin endless loop for user to guess integers.
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
break;
}
}
}
}
}
My issue is: I cant retrieve that sum variable in the main class to check it against the number of integers. Because if they are equal, then the program knows the user has guessed correctly. I cant use cout after calling the beginGuessingGame function either..
Any suggestions?
Thanks.
At least this part of the program
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) { //...
does not make sense. The program has undefined behavior.
Data members of the class object guess are not initialized So the member function getSum returns an indeterminate value of the data member sum of the object. And this indeterminate value is compared with another indeterminate value of the uninitialized variable numberOfIntegers in the while loop.
In the function generateSequence it seems there is a typo in this statement
generatedSequence = new int[inputRangeOfIntegers];
There should be
generatedSequence = new int[inputNumberOfIntegers];
Within the function beginGuessingGame there is an infinite loop
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
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";