Storing new values from a while loop?? C++ [duplicate] - c++

This question already has answers here:
Using unique dynamic variable names (not variable values!)
(4 answers)
Closed 8 years ago.
im not sure if someone asked this question before i couldn't find it in the search,
im using a normal while loop that generates a series of numbers and i want to store all these numbers as an int variable for each, here is my code so far
int numvalue = 30;
while (numvalue<100){
numvalue= numvalue + 10;
cout << numvalue<< endl;
}
Output:
40
50
60
70
80
90
100
so i need to store each output as an int variable and assign the names automatically , how should i go about this?

Variables are statically defined so you cannot create names for them from the code in the for loop.
But you can make lists of values. In your case using the std::vector is probably the best choice:
#include <vector>
int value = 30;
std::vector<int> values;
while (numvalue<100){
numvalue= numvalue + 10;
values.push_back(numvalue);
cout << numvalue<< endl;
}
So after the loop values will contain 7 values. values[0] will be 40, values[1] will be 50, etc.

Related

How is the following character array accessed [duplicate]

This question already has answers here:
C++ array[index] vs index[array] [duplicate]
(4 answers)
With arrays, why is it the case that a[5] == 5[a]?
(20 answers)
Accessing arrays by index[array] in C and C++
(2 answers)
Closed 4 days ago.
#include <iostream>
using namespace std;
int main()
{
char str[]="ABCD";
for(int i=0;str[i]!='\0';i++)
{
cout<<i[str]<<" ";
}
return 0;
}
The output of the following code is A B C D but i am not able to understand how we are accessing the array
Let's consider str has address 100 (Very simplified example).
It has 5 chars in it, so the addressed are 100, 101, 102, 103, 104, where in the 104 is '\0'
When you try to access str[i], it actually calculates the address str + i, and gets the value: *(str + i). And when you try to write the reversed way i[str], it also calculates the address i + str. So you get correct result.
Note that here is working pointer arithmetic (so for every type T you get the address pointer + sizeof(T))
And your
for(int i=0;str[i]!='\0';i++)
{
cout<<i[str]<<" ";
}
Will access addresses 100, 101, 102, 103, 104. And print the right values.

Having trouble with decimal float in struct array [duplicate]

This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Closed 1 year ago.
I am having some trouble and I cant really even figure out what is wrong, so I needed some help.
I need to take a percentage of a number that one of the structs in my array has, for each one.
my struct looks like
struct person{
int number;
string name;
float share;
}
So I use a for loop to get the total of number, no problem, all comes out good. But when I try to get what percent of the total I always get a zero.
for (int i=0; i<numberOfPersons;i++){
people[i].share = 100 * ((people[i].number)/totalNumber);
}
I don't understand what is going wrong here but people[i].share always comes out as 0.00 when I cout it.
literally all I do after this is cout it and I get the correct values from number and totalNumber. So I'm like really confused.
If I flip the division problem around I get answers(not the right ones obviously), so I know that there is data in the fields when the for loop runs. But where is it going when I run the equation the way I need to run it?
I tried initializing it and leaving uninitialized, swapping the pointers for ints made inside the loop, and more and I always get the same result.
Please help me understand.
I presume your type of totalnumber is int and person.number is int as well.
For operation between ints, the return value is still int
Expanding people[i].share = 100 * ((people[i].number)/totalNumber);
It would be something like people[i].share = 100 * ( 1/10 );
=> people[i].share = 100 * ( 0 );
=> people[i].share = 0;
So you will get 0 as a result;
To prevent it, cast one of int to float.
people[i].share = 100 * ((static_cast<float>(people[i].number))/totalNumber);

Need to generate a unique 5 digit number from 00001 to 99999 in C++ [duplicate]

This question already has answers here:
Generate random numbers uniformly over an entire range
(20 answers)
rand() returns same values when called within a single function
(5 answers)
Closed 4 years ago.
We will modify part of the existing menu logic to generate an ID for the user. This user ID will be of the type int, and will be 5 digits in length. The values are 00001 – 99999, and should appear with all 5 digits (leading zeroes) on the display upon generating them. Do not change the data type from that of an int. Check out the setfill manipulator as a possible helper for this. Setfill allows you to set a fill character to a value using an input parameter, such as ‘0’ for leading zeroes. Researching it, you’ll see that you will need to reset the fill character after use too, or you will be printing a lot of zeroes on the display! Your program also should guarantee an absolutely unique user ID has been generated for each new activity that is added. Think about how this works...
Currently I've been trying to get the following code to work
srand(time(0));
cout << setfill('0') << setw(5) << rand() %99999 << endl;
Problem is that this doesn't seem random at all (it's just slowly counting up based on the computers internal clock right?) and the first digit is always zero. Like the instructions say it should be between 00001 and 99999.
EDIT: I appreciate the different solutions, but most of them are more advanced than what I'm supposed to be using for this assignment. I'm fairly sure srand() and rand() is what I should be using.
Okay, so it seems you must use the rand() function to generate a value between 1-99999. So with that in mind, the following code should generate random values in the required range:
#include <iomanip>
#include <iostream>
const int randID()
{
return 1 + (std::rand() % (99999));
}
int main()
{
for(int i = 0; i < 1000; ++i)
std::cout << std::setfill('0') << std::setw(5) << randID() << '\n';
return 0;
}
For me it prints, for example:
01886
21975
01072
11334
22868
26154
14296
32169
20826
09677
15630
28651
Which should satisfy your requirement of 0-padded values between 1-99999. Also, as mentioned in the comments. Do look into the <random> for your random number needs outside this assignment as it generates far superior random numbers, and offers way more generators, distributions and better seeding.

C++ for loop and do-while loop of a single dimensional array gives questionable output [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am taking a course on edx.org Introduction to C++ by Microsoft. I get unwanted output when looping through a single dimensional array. The code is below.
<#include <iostream>
int main() {
int arrayName[10] = { 1,2,3,4,5,6,7,8,9,10 };
for (int i = 1; arrayName[i] <= 20; i++) {
std::cout << i << std::endl;
}
The output of this is:
1
2
3
4
5
6
7
8
9
10
11
Where does the 11 come from? And, if I make i=0, it also prints a 0. How does it print more than 10? And, when I try to change arrayName[10] to arrayName[9], I get a compiler error that there are too many initialized values:
int arrayName[10] = { 1,2,3,4,5,6,7,8,9,10 };
do {
std::cout << i << std::endl;
i++;
} while (arrayName[i] < 5);
The output is:
12
13
14
15
16
17
18
That do-while loop outputs 7 integers that I did not specify to be included in the arrayName[] array.
I don't know what I am doing wrong or what I am not understanding.
Please help. Thank you!
First, note that arrays in c++ start at index 0. So in int arrayName[3] = {10, 42, 88}; then arrayName[1] is 42, not 10. That means the last element in this array is int arrayName[2]. There is no element at index 3.
Your array only contains 10 elements (indices 0 to 9). The standard does not specify what happens when you access an element past the end of an array, anything can happen. In your case, arrayName[10] and arrayName[11] happens to give you something less than or equal to 20, and then arrayName[12] gave you something greater than 20, ending the loop. If you try it on another computer, or even at a different time, the results will vary. It might also crash (this is the best case scenario).
See this answer for more information on undefined behavior.
I finally found this: Correct way of loop through the C++ arrays, answer by https://stackoverflow.com/users/1619294/mark-garcia.
Changed my code to:
std::cout << "Looping through arrayName3 with std::array and letting the compiler determine how many objects to print:" << std::endl;
// Need to #include <array>
std::array<int, 10> arrayName3 = { 1,2,3,4,5,6,7,8,9,10 };
for (const auto& i : arrayName3) // Range-for
{
std::cout << i << std::endl;
}
The output was what I wanted:
1
2
3
4
5
6
7
8
9
10
This let's the compiler know it is deciding what to output. It would be great to know how to change this to control how many indices to loop through.

Finding the square of a number without multiplication [duplicate]

This question already has answers here:
Making a square() function without x*x in C++
(7 answers)
Closed 4 years ago.
I'm a beginner in programming and trying to learn C++ by the book Programming principles and practice using C++. In some parts of the book there are little exercises that you can try to do, one of this exercises is about calculating the square of a number, here is what my book says :
Implement square() without using the multiply operator, that is, do the x * x by repetead addition (start a variable result to 0 and add x to it x times).
I've already found a solution for this program but my first tentative was something like this :
#include <iostream>
int main()
{
int a = 0;
std::cout << "Enter an integer value : ";
std::cin >> a;
while (a < a * a)
{
a += a;
std::cout << a << "\n";
}
}
I know this code is wrong but I can't understand the output of the progam, if I enter 5 the program prints 10 20 30 40 50 until 8000, why the for loop doesn't stop when a is greater than its square ? I'm just curious to undersant why
Using multiplication when trying to avoid multiplication seems broken. What about this:
int r = 0;
for (int n = 0; n < a; ++n) {
r += a;
}
why the for loop doesn't stop when a is greater than its square ?
Because it never is. If you compare the graph of y=x^2 against the graph of y=x, you will see that the only time y=x is above, is when 0 < x < 1. That's never the case for integers1. Now, since we're talking about computers with limited storage here, there is a thing called overflow, which will cause a very large number to become a very small number. However, signed integer overflow is undefined behavior in C++. So once your loop gets to the point where overflow would happen, you cannot rely on the results.
1. Note that your loop is not set to stop just when a is greater than its square, but when it is greater than or equal to its square. So, your loop will actually stop if a is 0 or 1.