Summarize the problem:
My goal is to generate odd numbers up to a limit, store them in a vector then output the square of them.
Describe what you've tried:
So far, I used the #include < cmath > at the start before int main(), then I used a couple of if statements to check whether the limit is zero, if so I output an error message. If the limit is >0 then I squared the odd numbers using pow(num,2) however, this does not work and gives wrong answer. For example, it gives the square of 13 as 600ish, that is obviously wrong. Please give advice. My full code is here, it is very simple so I did not put much comments in there:
#include<iostream>
#include<format>
#include<cmath>
#include<vector>
using namespace std;
int main()
{
int limit{};
cout << "Enter a limit of odd integers: \n";
cin >> limit;
vector<int>oddnumb(limit);
if (limit == 0)
{
cout << "You MUST enter a number>0, then restart the program. \n";
return 0;
}
if (limit > 0)
{
cout << "Odd numbers are as follows: \n";
for (size_t i{}; i < limit-1; ++i)
{
oddnumb[i] += ++i;
cout << oddnumb[i] << endl;
}
cout << "Squared odd numbers follow: \n";
for (size_t i{}; i < limit - 1; ++i)
{
oddnumb[i] += ++i;
cout << pow(oddnumb[i],2) << endl;
}
}
I've written up a working version of what you want to do. I urge you to figure it out yourself first, that's the best way to learn, and then check your version against what I've got here. Note that this is certainly not the best way to do it. But I wrote it in a way that should be easy to understand. In programming there are lots of ways to tackle any problem, the best way is arguably... the way that works! Good luck in your journey with C++!
#include <cmath>
#include <iostream>
#include <vector>
int main()
{
double input{};
while (input < 1)//validate that input is greater than 0 here by looping if it isn't
{
std::cout << "Enter a limit of odd integers: ";
std::cin >> input;
if (input < 1)//if a valid range is entered this is never shown
{
std::cout << "Enter a valid range. Greater than 0. \n\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
std::vector<double> oddNumbers{};
std::cout << "Odd numbers:\n";
//notice we're starting this loop at 1, since 0 is even we just avoid it
for (double i = 1.0; i <= input; i += 2.0) //you can add more than just 1 to i
{
oddNumbers.push_back(i);// here we're putting the value of i at the back of the vector
std::cout << i << " squared is " << pow(i, 2.0) << '\n';
//we could avoid using a vector by printing the squared value of i within this loop
}
std::cout << "Squared Odd Numbers:\n";
//we do need to start this loop at 0 to access the first element of the vector
for (unsigned int i = 0; i < oddNumbers.size(); i++)
//we also increase i by just one each time to access each element we stored
{
std::cout << pow(oddNumbers[i], 2.0) << '\n';
}
return 0;
}
Related
Consider the following code:
#include <iostream>
using namespace std;
int main(){
int a,b;
cout << "Enter two positive numbers:" <<endl;
cin >> a >> b;
if (a<b) cout <<a<<" is less than "<< b<<endl;
else if (a>b) cout <<a<<" is greater than " <<b<<endl;
}
How can I make the program endlessly repeat asking for a new set of numbers as input?
Here's the simplest way of doing what you want (there are other ways). Basically, you just need to 'wrap' the code that you want to repeat in a loop, where the 'test' condition for the loop will always evaluate to true.
Note the comments with "///" I've given:
#include <iostream>
//using namespace std; /// Search this site for "Why using namespace std is bad"
using std::cout;/// Just declare usage of those feature you ACTUALLY use...
using std::cin;
using std::endl;
int main() {
int a, b;
while (true) { /// The test condition will always be "TRUE" so the loop will never end!
cout << "Enter two positive numbers:" << endl;
cin >> a >> b;
if (a < b) cout << a << " is less than " << b << endl;
else if (a > b) cout << a << " is greater than " << b << endl;
// cout /// This line is wrong!
}
}
Feel free to ask for further clarification and/or explanation.
Depends on what exactly do you want your program to do. If you want it to "deny access". For example lets say you have want a number K > 3 always for the program to continue. The all you have to do is use a do- while loop:
do
{
cout << "Enter the value for the sequence: ";
cin >> K;
if ( K <= 3)
{
cout << "Write a bigger number!" << endl;
}
} while(K <= 3);
Otherwise just use a normal loop with the condition suitable for the task.
Suppose your program is to find the Factorial of number and you want it to loop such that it ask for new value from the user
int main()
{
int n;
while (true) {
int factorial = 1;
cin >> n;
if (n==0) {
cout << 0;
}
else {
for (int i=n;i>0;i--) {
factorial = factorial*i;
}
cout << factorial;
}
}
return 0;
}
please, why this pointer array won't accept more than 5 values?
Doing excercises from Prata's C++ book, but got stuck on this.
//ex2_numrow -- showing entered numbers til zero is entered
#include <iostream>
using namespace std;
int main()
{
int n = 0;
int num = 0;
int* entered = new int[1];
do
{
cout << "Enter number: ";
cin >> num;
entered[n] = num;
cout << "Your numbers: ";
for (int i = 0; i <= n; i++)
{
cout << entered[i] << " ";
}
cout << endl << endl;
n++;
} while (num);
delete[] entered;
return 0;
}
The code int* entered = new int[1]; gives you a pointer to an array of size one!
It is very unwise (i.e., undefined behaviour) to then try to write values outside of that array. The best case is that your code will crash before it causes any serious issues.
As an aside, the set of use cases for raw pointers is fast dwindling in C++, you should generally be looking at smart pointers instead.
I say "generally" because, if your intent is to have a resizable array, even smart pointers won't help that much. What will help is a little thing I like to call std::vector :-) You should probably look into using that for your immediate purpose.
For example, this program accepts positive numbers, adding them to a vector, then printing them out:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers;
int num;
do {
std::cout << "Enter number: ";
std::cin >> num; // should probably check for errors in real code
if (num >= 0) {
numbers.push_back(num);
}
} while (num >= 0);
std::cout << "You entered:";
for (int num: numbers) {
std::cout << ' ' << num;
}
std::cout << '\n';
}
I always seem to have this problem when I want to display two variables of an array in one iteration of a loop, I'm wondering if there is a nicer way of displaying the array.
The code works if I change ++i to i+1 but I'm wondering why that happens, and I'm wondering if there's a smarter way to do what I want. The error says unsequenced modification and access to 'i' [-Wunsequenced]
#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int players = 0,rounds=0;
bool winnerFound=false;
cout << "Welcome to my tournament match maker\n";
cout << "Enter the number of participants in the tournament: ";
cin >> players;
rounds=players/2;
string *pNames = new string[players]; //dynamically allocate
for (int i = 0;i < players;i++)
{
cout << "Enter the name of player " << i + 1<<":";
cin >> pNames[i];
}
random_shuffle(&pNames[0],&pNames[players]);
for(int i=0;i<rounds;i++)
{
cout<<pNames[i]<<" vs "<<pNames[++i]; //
}
return 0;
}
I'm not sure if that's the best way to do it, any tips would be appreciated.
For the tips, I think it is better to use a STL container instead of a raw array. std::array or std::vector for example. You can change the declaration of pNames as follows:
std::vector <std::string> pNames(players);
Your problem is that you iterate only until rounds. You don't want that, you want to loop over all players, not only half of them.
To make your code work, you need to write:
for(size_t i = 0; !pNames.empty() && i < pNames.size()-1; ++i)
{
std::cout << pNames[i] << " vs " << pNames[++i] << std::endl;
}
But I think it is a bad way to modify i from inside the loop, you better have to directly increment i by two in the loop statement. This will give:
for(size_t i = 0; !pNames.empty() && i < pNames.size()-1; i+=2)
{
std::cout << pNames[i] << " vs " << pNames[i+1] << std::endl;
}
Of course, if you have only one player or any odd number of players, you will miss the last one (because you need two opponents to make a vs).
I hope it can help.
#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
int players = 0,count=0;
cout << "Welcome to my tournament match maker\n";
cout << "Enter the number of participants in the tournament: ";
cin >> players;
string *pArray = new string[players]; //dynamically allocate
cin.ignore();
for (int i = 0;i < players;i++)
{
cout << "Enter the name of player " << i + 1<<":";
getline(cin, pArray[i]);
}
random_shuffle(&pArray[0], &pArray[players]);
for (int i = 0;i < players;i++)
{
cout << ++count << ": " << pArray[i] << " vs " << pArray[i + 1] << endl;
i++;
}
return 0;
}
Any critiques?
Firstly i++ and ++i are different.
i++ increments after returning the value and
++i increments before returning the value of the result.
It would be more readable if you incremented your i in the for loop by two and then not have a side effect when asking for the array value. And of course you need to check if i is valid at this point
for(int i=0; i < players-1; i += 2)
{
// check if valid.
// with odd numbers of players, the last remaining player will be dropped.
cout << pNames[i]<<" vs " << pNames[i+1]; // no side effect.
// In a for loop
// all increments should happen in
// the loop header.
}
#include <iostream>
using namespace std;
int main()
{
double donation[10];
int index = 0;
cout.setf(ios::fixed);
cout << "Enter sum of money for donating: ";
while (index < 10 && cin >> donation[index])
{
cout << "donation #" << 1 + index++ << ": " << donation[index] << endl;
}
return 0;
}
Result
That code couldn't display right value of donation...
I could check the mistake is '1 + index++', but I don't know why did.
Why my code using '1 + index++' has a difference with code when I use 'index++' in the next line.
Keep to the idiomatic way instead of trying to understand stranger constructions and also mixing increments with function/operator parameters should be avoided (see sequence points):
for (int index = 0; index < 10; ++index)
{
if (! std::cin >> donation[index])
break;
std::cout << "donation #" << (1 + index) << ": " << donation[index] << std::endl;
}
This should do what is expected and should be understood with some knowledge of C++. It runs at most 10 times, tries to fill input to the array and displays when the input works or stops when the input fails. The only issue would be better validation of the user input.
This is my first post on here so please don't kill me for my noobishness.
I recently made a program for fun to put in a ton of numbers and have it put out the mean, not very useful but I thought I would see if I could. I would love it if someone could explain to me how I could improve my code using arrays instead of lots of variables, but still achieve the same thing, maybe even more efficiently.
My code looks like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int q1;
int q2;
int q3;
int q4;
int q5;
int q6;
int q7;
int q8;
int q9;
int q10;
int q11;
int q12;
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
cin >> q1;
cin >> q2;
cin >> q3;
cin >> q4;
cin >> q5;
cin >> q6;
cin >> q7;
cin >> q8;
cin >> q9;
cin >> q10;
cin >> q11;
cin >> q12;
f = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12;
cout << f / a << '\n';
system("pause");
}
Any advice is very appreciated! This was made in Visual Studio just in case you needed to know.
Of course arrays can make your life easier!
Here's how you could have accomplished the same task as above, with arrays:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "You can only enter up to 12 numbers;
// Declare an array to hold 12 int's
int nums[12];
// i will count how many numbers have been entered
// sum will hold the total of all numbers
int i, sum = 0;
for(i = 0; i < 12; i++) {
cout << "Enter the next number: ";
cin >> nums[i];
sum += nums[i];
}
cout << "The mean is: " << (sum / totalNums) << '\n';
//Try to avoid using system!
system("pause");
}
But, why use an array?
There's no need to keep any of the numbers after you add them to the total, so why use an array?
You can accomplish the same task without an array and with only one variable for the numbers!
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "Enter the amount of numbers that will be entered: ";
cin >> totalNums;
// i will count how many numbers have been entered
// sum will hold the total of all numbers
// currentNum will hold the last number entered
int i, sum = 0, currentNum = 0;
for(i = 0; i < totalNums; i++) {
cout << "Enter the next number: ";
cin >> currentNum;
sum += currentNum;
}
cout << "The mean is: " << 1.0 * sum / totalNums << '\n';
//Try to avoid using system!
system("pause");
}
Arrays can be considered as series of variables each of which has ids.
integers between 0 and (number of elements) - 1 (both inclusive) are available ids.
Using that with loop, your code can be like this (sorry, I hate stdafx.h):
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int q[12];
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
for (int i = 0; i < 12; i++) {
cin >> q[i];
}
f = 0;
for (int i = 0; i < 12; i++) {
f += q[i];
}
cout << f / a << '\n';
system("pause");
}
You may use the numbers read in the future, but currently the numbers aren't used except for calculating the sum, so you can omit the array and do addition while reading. Also I deleted the variable t, which is unused and stopped using using namespace std;, which is not considered as good.
#include <cstdlib>
#include <iostream>
using std::cin;
using std::cout;
int main() {
int q;
int f;
//Used for the total of all values
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
f = 0;
for (int i = 0; i < 12; i++) {
cin >> q;
f += q;
}
cout << f / a << '\n';
system("pause");
}
You marked this question as C++.
I recommend you do not use "using", and you should prefer vector over array.
Consider the following approach:
#include <iostream>
#include <vector>
int main(int argc, char* argv[])
{
std::cout << "We will be finding a mean." << std::endl
<< "Enter numbers, and press ^d when complete.\n"
<< std::endl;
// Declare a vector to hold user entered int's
std::vector<int> intVec;
// the vector automatically keeps track of element count
do {
std::cout << "number: "; // prompt
int t = 0;
std::cin >> t; // use std::cin,
if(std::cin.eof()) break; // ^d generates eof()
intVec.push_back(t);
}while(1);
// there are several way to sum a vec,
// this works fine:
int sum = 0;
for (auto i : intVec) sum += i;
std::cout << "\n sum : " << sum
<< "\ncount : " << intVec.size()
<< "\n mean : " << (sum / intVec.size()) << std::endl;
return(0);
}
You can enter single item per line (neatness counts).
You can enter multiple integers separated by white space, but the above will give back a prompt for the integers already entered.
^d - generates an end of file input.
... press and hold 'Control' key and letter 'd' at same time
Note - does not handle error input - try entering a 'number' as 'num' string.
The accepted answer is definitely the most efficient way to transform your code using arrays, but one thing I would add is that in C++ dividing an integer by another integer can only ever result in an integer, and because you're trying to get the mean, it seems like you'd want to have the result in decimals, so you need to do one of two things:
Declare sum as a float for the purposes of diving it by totalNums to get the mean.
Cast one of the integers to either a float or a double so that the decimals won't get truncated, so the last cout statement would look like this:
cout << "The mean is: " << (double)sum/totalNums << endl;
In C++ the default for precision is 6, but you can change the number of decimal points that are displayed by adding #include <iomanip> and using the setprecision( ) function in the iomanip, which you can just add in the same output line:
cout << setprecision(x) << "The mean is: " << (double)sum/totalNums << endl;
where x is whatever precision you want.
If you want to try using dynamic memory
This is definitely not necessary for what you're doing, but it's interesting stuff and good practice!
One more thing is that if you want to be able to have the user enter integers indefinitely, you can dymanically allocate memory during runtime by declaring a array of pointers to integers (so it's an array of address locations instead of an array of integers) and some sentinal value so they can decide when to stop. That code would look like:
#include <iostream>
#include <iomanip>
using namespace std;
main( ) {
const int ARRAY_SIZE = 200;
const int SENTINAL = -999;
int totalNums = 0;
int sum = 0;
//declare an array of pointers to integers so
//the user can enter a large number of integers
//without using as much memory, because the memory
//allocated is an array of pointers, and the int
//aren't allocated until they are needed
int *arr[ARRAY_SIZE];
cout << "We will be finding a mean." << endl;
cout << "Enter integers (up to 200) or enter -999 to stop" << endl;
//add a conditional into the for loop so that if the
//user enters the sentinal value they will break out
//of the loop
for (int c = 0; c < ARRAY_SIZE; c++) {
//every time you iterate through the loop, create a new
//integer by using the new keyword using totalNums as
//the index
arr[totalNums] = new int;
cout << "Enter integer: ";
//input into the array of pointers by dereferencing it
//(so it refers to what the pointer is pointer to instead
//of the pointer)
cin >> *arr[totalNums];
if (*arr[totalNums] == SENTINAL)
break;
else {
sum += *arr[totalNums];
totalNums++;
}
}
cout << setprecision(3) << "The mean is: " << (float)sum / totalNums << endl;
}