Initializing 2D int array in run-time - c++

I got the code below from a C++ book, and I cannot figure out how the initialization works.
From what I can see, there is an outer for loop cycling trough the rows, and the inner loop
cycling trough the column. But its is the assignment of the values into the array that I do not understand.
#include <iostream>
using namespace std;
int main()
{
int t,i, nums[3][4];
for(t=0; t < 3; ++t) {
for(i=0; i < 4; ++i) {
nums[t][i] = (t*4)+i+1; //I don't understand this part/line
cout << nums[t][i] << ' ';
}
cout << '\n';
}
return 0;
}
so here are some questions.
I cannot understand the initialization of the 2D int array nums[3][4]. What separates the (t*4)+i+1, so that the compiler knows what to assign where?
How do I know what values will be stored in the rows and columns, based on what values have been assigned?
Why is there an asterisk?
What are the parentheses around t*4 for?
I understand that initialization two-dimensional arrays look like the following example.
#include <iostream>
using namespace std;
int main() {
char str[3][20] = {{"white" "rabbit"}, {"force"}, {"toad"}}; //initialize 2D character array
cout << str[0][0] << endl; //first letter of white
cout << str[0][5] << endl; //first letter of rabbit
cout << str[1][0] << endl; //first letter of force
cout << str[2][0] << endl; //first letter of toad
return 0;
}
And from what I know, like this in memory.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 w h i t e r a b b i t 0
1 f o r c e 0
2 t o a d 0
Thank you.

(t*4)+i+1
Is an arithmetic expression. t and i are ints, the * means multiply. So for row 1, column 2, t = 1, i = 2, and nums[1][2] = 1x4+2+1 = 7.
Oh, forgot a couple things. First, the () is to specify the order of operations. So the t*4 is done first. Note that in this case the () is unnecessary, since the multiply operator takes precedence over the plus operator anyway.
Also, I couldn't tell from your question if you knew this already or not, but the meaning of rows[t][i] is array notation for accessing rows at row t and column i.

For the first part, isn't it just assigning the a value equal to the row number * 4 plus the column number? I.E. the end result of the assignment should be:
1 2 3 4
5 6 7 8
9 10 11 12
So the expression (t*4)+i+1 means "4 multiplied by the row number plus the column number plus 1". Note that the row number and column numbers in this case start from 0.

nums[t][i] is the one spot in the array it is assigning the value of (t*4)+i+1.
So if t = 1 and i = 1 then the spot num[1][1] will equal (1*4)+1+1 which is 6.
See above.
Asterisk is for multiplying.
You do what's in the ( ) first just like in any mathematical equation.

Lets see, you have
int t,i, nums[3][4];
where we reserve space for the 2d array. The values inside the array will have random values since you only reserved space.
The line :
nums[t][i] = (t*4)+i+1; //I don't understand this part/line
Assigns the values to the array. You have t and i which are loop counters, and the line (t*4)+i+1 means, take value of t, multiply with 4, plus i and plus 1.
So for t=0, i =0, you get that nums[0][0] has value (0*4) + 0 + 1 which is 1.. etc for everything else.
And ofcourse the () are just basic math parentheses.

Related

How to draw 1 isosceles triangle with vertex facing left side of screen using C++ [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 4 months ago.
Improve this question
I am a student and am looking for a way to solve a problem online with content like the image below
Please solve it for me with C++ code
If you want to solve such a problem, then you need split the big problem in to smaller problems. Then the solution is easier.
So, let's first strip of the '*'. They are always starting a row and ending it. This is not needed in the beginning.
Next. You see some sequences, like
1
121
12321
1234321
123454321
1234321
12321
121
1
You see that the digits will be incremented by one until we hit the maximum value for this row and then decremented again until they are 1.
The decreasing numbers are also not important at the moment, because, it is simple to decrement them from the maximum number.
Stripping of the decremented numbers, we will get:
1
12
123
1234
12345
1234
123
12
1
And this looks like a triangle and can be generated mathematically by a typical triangular function.
We want to calculate the maximum number in a row from the row value istelf. Applying the algorithm from the triangular function, will always result in a formular with the "abs"-function. So taking the absolute value.
We will then get something like the below:
Row 5-abs(Row-5)
0 0
1 1
2 2
3 3
4 4
5 5
6 4
7 3
8 2
9 1
10 0
We see also that the number of output lines is double the input value.
We can then do a simple increment/decrement loop, to show the digits according to the before shown values.
Then we add a little bit the output of the "". Please note, that the "closing" star "" at the end of the line is not needed in the first and last row.
Having explained all the above, we can now start writing the code. There are really many many potential solutions, and I just show you one of them as an example.
Please have a look and implement your own solution.
#include <iostream>
#include <cmath>
int main() {
// Tell user what to do
std::cout << "\nPlease add number for the triangle: ";
// Get the maximum extent from the user. Limit values
int maxN{};
if ((std::cin >> maxN) and (maxN >= 0) and (maxN < 10)) {
// Now we want to print row by row
for (int row=0; row <= (maxN * 2); ++row) {
// Calculate the maximum value that should be shown in this row
int maxValueForRow = maxN - std::abs(row-maxN);
// You may uncomment the following line for getting more info
//std::cout << maxValueForRow << '\t';
// Always print at least on beginning star
std::cout << '*';
// Now we want to print the digits. Start counting with 0
int i = 0;
// Print and increment digits
for (i = 0; i < maxValueForRow; ++i) std::cout << i+1;
// And now decrement the digits and print them
for (i=i-2; i >= 0; --i) std::cout << i+1;
// Show closing star only, if we are not in first or last row
if (maxValueForRow > 0) std::cout << '*';
// Start a new line
std::cout << '\n';
}
}
else std::cerr << "\n\nError: Invalid input\n";
}

Squaring numbers in consecutive order 0-9

I am extremely new to the coding world. I just have a basic question regarding this function that squares integers from 0-9. I understand most of what's going on until I get to
std::cout << i << " " << square << "\n";
i = i + 1;
I'm not too sure how that ends up causing the output to square the results in order from 0-9. Can someone explain the reasoning behind this line of code? Here is the code for this function.
#include <iostream>
int main() {
int i = 0;
int square = 0;
while ( i <= 9) {
square = i*i;
std::cout << i << " " << square << "\n";
i = i + 1;
}
return 0;
}
This code:
std::cout << i << " " << square << "\n";
i = i + 1;
Doesn't square anything. It is merely outputting the current square that has already been calculated, and then increments i for the next loop iteration.
The actual squaring happens here:
square = i*i;
So, the code starts at i=0, calculates square=0*0 and displays it, then sets i=1, calculates square=1*1 and displays it, then sets i=2, calculates square=2*2 and displays it, and so on until i exceeds 9, then the loop stops.
Lets start from beginning and what is happening, I will ignore first several lines and start at:
int i = 0;
int square = 0;
You see when you say int i; your compiler says I need to allocate bucket of memory to hold value for i. When you say i = 0 zero is put into that memory bucket. That is what is happening for square as well.
Now to loop
while ( i <= 9 ) {
square = i*i;
std::cout << i << " " << square << "\n";
i = i + 1;
}
So, lets ignore
square = i*i;
std::cout << i << " " << square << "\n";
for now we will come to it later.
So
while ( i <= 9 ) {
i = i + 1;
}
goes into the loop and gets value from i's bucket, adds 1 and puts new value into the i's bucket. So in first loop it will be i = 0 + 1, put 1 into i bucket. Second, i = 1 + 1 put 2 in, third i = 2 + 1 put 3.
So lets go back to square and its bucket.
square = i*i;
So first time we go into the loop i = 0 and square = 0 * 0 so compiler puts 0 into square's memory bucket. Next time it hits square i has been incremented to 1 so square = 1 * 1, thus compiler puts 1 into the bucket. Third time i is 2 so square = 2 * 2, and compiler puts 4 into the bucket. And so on till it i <= 9. When i hits 10 loop is not executed.
In comments you have stated that you do not know the difference between a math equation and an assignment statement. You are not alone.
I will try to explain, as an addition to existing answers, to provide a different angle.
First, two examples of math equations:
x = 1 +1
y+1 = x*2
To illustrate their meaning, let me point our that you first can determine that x is 2 and in a second step that y is 3.
Now examples of assignment statements.
x = 1 +1;
y = x*2;
The minor difference is the ; at the end, tipping you off that it is a program code line.
Here the first one looks pretty much the same as the first equation example. But for a C compiler this is different. It is a command, requesting that the program, when executing this line, assigns the value 2 to the variable x.
The second assingment statement I made similar to the second equation example, but importantly different, because the left side of = is not an expression, not something to calculate. The equation-turned-statement
y +1 = x*2;
does not work, the compiler will complain that it cannot assign a value (no problem with doing a little calculation on the right side) to an expression. It cannot assign the value 4 to the expression y+1.
This helps with your problem, because you need to understand that both lines
i = i + 1;
square = i*i;
are statements which, when executed (and only then) cause a change to the value of the variable in that line.
Your program starts off with the value 0 in the variable i. At some point it executes the first of the statements above, causing the value of i to change from 0 to 1. Later, when the same line is executed again, the value of i changes from 1 to 2. So the values of i change, loop iteration by loop iteration, to 2,3,4,5,6,7,8,9
The second assignment line causes the value of square to become the value of i, whatever it is during that loop iteration and multiplied by itself. I.e. it gets to be 4,9,16,25,36....
Outputting the value of square each time in the loop gets you the squares.
Since you state that you basically understand loops, I just mention that the loop ends when i is not lower or equal to 9 any more.
Now from the other point of view.
If you try to solve the equation
i = i + 1
for i, you should hear your math teacher groaning.
You can subtract i from both sides and get
0 = 1
The solution is "Don't try.", it is not an equation.
std::cout << i << " " << square << "\n"; prints every
number i next to its square, which is previously computed
(square = i*i;).
i = i + 1; increments i to compute the next square. It stops when i reaches 10.
The output will look like this:
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
So we have a while loop here, which run while i <= 9. The square of any number i is i * i.
while(i <=9){ //check the condition and then enter the body
//body
}
But we need a condition to get out of the loop, otherwise our program will enter into an infinite loop.
To ensure, we will exit from the loop we increase the value of i by 1.
so at first when i = 0 square = 0 * 0 = 0,now we increase the value of i i.e now i becomes one which still satisfies the condition to stay inside the loop , again it will calculate square = 1 * 1 until and unless the value of i remains less than or equal to 9.
Once the condition fails, the execution comes out of the loop.

Cross sum calculation, Can anyone explain the code please?

i'm going to learn C++ at the very beginning and struggling with some challenges from university.
The task was to calculate the cross sum and to use modulo and divided operators only.
I have the solution below, but do not understand the mechanism..
Maybe anyone could provide some advice, or help to understand, whats going on.
I tried to figure out how the modulo operator works, and go through the code step by step, but still dont understand why theres need of the while statement.
#include <iostream>
using namespace std;
int main()
{
int input;
int crossSum = 0;
cout << "Number please: " << endl;
cin >> input;
while (input != 0)
{
crossSum = crossSum + input % 10;
input = input / 10;
}
cout << crossSum << endl;
system ("pause");
return 0;
}
Lets say my input number is 27. cross sum is 9
frist step: crossSum = crossSum + (input'27' % 10 ) // 0 + (modulo10 of 27 = 7) = 7
next step: input = input '27' / 10 // (27 / 10) = 2.7; Integer=2 ?
how to bring them together, and what does the while loop do? Thanks for help.
Just in case you're not sure:
The modulo operator, or %, divides the number to its left by the number to its right (its operands), and gives the remainder. As an example, 49 % 5 = 4.
Anyway,
The while loop takes a conditional statement, and will do the code in the following brackets over and over until that statement becomes false. In your code, while the input is not equal to zero, do some stuff.
To bring all of this together, every loop, you modulo your input by 10 - this will always return the last digit of a given Base-10 number. You add this onto a running sum (crossSum), and then divide the number by 10, basically moving the digits over by one space. The while loop makes sure that you do this until the number is done - for example, if the input is 104323959134, it has to loop 12 times until it's got all of the digits.
It seems that you are adding the digits present in the input number. Let's go through it with the help of an example, let input = 154.
Iteration1
crossSum= 0 + 154%10 = 4
Input = 154/10= 15
Iteration2
crossSum = 4 + 15%10 = 9
Input = 15/10 = 1
Iteration3
crossSum = 9 + 1%10 = 10
Input = 1/10 = 0
Now the while loop will not be executed since input = 0. Keep a habit of dry running through your code.
#include <iostream>
using namespace std;
int main()
{
int input;
int crossSum = 0;
cout << "Number please: " << endl;
cin >> input;
while (input != 0) // while your input is not 0
{
// means that when you have 123 and want to have the crosssum
// you first add 3 then 2 then 1
// mod 10 just gives you the most right digit
// example: 123 % 10 => 3
// 541 % 10 => 1 etc.
// crosssum means: crosssum(123) = 1 + 2 + 3
// so you need a mechanism to extract each digit
crossSum = crossSum + input % 10; // you add the LAST digit to your crosssum
// to make the number smaller (or move all digits one to the right)
// you divide it by 10 at some point the number will be 0 and the iteration
// will stop then.
input = input / 10;
}
cout << crossSum << endl;
system ("pause");
return 0;
}
but still dont understand why theres need of the while statement
Actually, there isn't need (in literal sense) for, number of digits being representable is limited.
Lets consider signed char instead of int: maximum number gets 127 then (8-bit char provided). So you could do:
crossSum = number % 10 + number / 10 % 10 + number / 100;
Same for int, but as that number is larger, you'd need 10 summands (32-bit int provided)... And: You'd always calculate the 10 summands, even for number 1, where actually all nine upper summands are equal to 0 anyway.
The while loop simplifies the matter: As long as there are yet digits left, the number is unequal to 0, so you continue, and as soon as no digits are left (number == 0), you stop iteration:
123 -> 12 -> 1 -> 0 // iteration stops, even if data type is able
^ ^ ^ // to store more digits
Marked digits form the summands for the cross sum.
Be aware that integer division always drops the decimal places, wheras modulo operation delivers the remainder, just as in your very first math lessons in school:
7 / 3 = 2, remainder 1
So % 10 will give you exactly the last (base 10) digit (the least significant one), and / 10 will drop this digit afterwards, to go on with next digit in next iteration.
You even could calculate the cross sum according to different bases (e. g. 16; base 2 would give you the number of 1-bits in binary representation).
Loop is used when we want to repeat some statements until a condition is true.
In your program, the following statements are repeated till the input becomes 0.
Retrieve the last digit of the input. (int digit = input % 10;)
Add the above retrieved digit to crosssum. (crosssum = crosssum + digit;)
Remove the last digit from the input. (input = input / 10;)
The above statements are repeated till the input becomes zero by repeatedly dividing it by 10. And all the digits in input are added to crosssum.
Hence, the variable crosssum is the sum of the digits of the variable input.

Need Help in a Project of C++

So this is the actual Problem
Can anyone tell me that how I read the repective Data from the file, and how would I able to store it in variables (without using array) also the code should be generic, That if the number of series will incresed or decresed.. Code will not be affected... I Just can't understand that how would I store sata in variables and how.. Please Help.. :(
Problem
A file contains information of a batsman. Information is no of series
played by the batsman. No of matches played in each series & score in
each match by the batsman. You have to read the data (without using
any array) and find average score and maximum score in all matches of
a series. In the end find overall average score and max score in all
matches.
Input:
Read data from file "cricket.txt". First line contains no of seasons/
series played by the player. Next pair of lines contains matches
played by the batsman followed in next line scores by batsman in
different matches of a season. See sample "cricket.txt"
5
6
93 75 41 40 90 19
5
45 86 30 60 29
3
47 90 33
4
22 2 92 5
5
88 67 96 91 90
First 5 shows player has played 5 seasons/ series
Next 6 show in first series player has played 6 matches
Next line has scores of player in 6 matches
Next 5 show in second series player has played 5 matches
Next line has scores of player in 5 matches
So on in second last line 5 shows player has played 5 matches in 5th
series
Last line has scores of player in 5 matches of last series
You're looking for an array.
int a[10];
// Loop that assigns all elements in array a to 0
for (int i = 0; i < 10; i++)
{
a[i] = 0;
}
// Array b will have all of it's members initialized to 0
int b[10]{};
// You can also assign different values to different elements of the array
b[0] = 6;
b[8] = 2;
// You can then use the array elements in operations
int c = b[0] * b[8];
If you want array like structure without compile time defined size, then use std::vector.
// An empty vector of ints
std::vector<int> d;
// A simple int
int e = 5;
// Push 2 values to the end of the vector
d.push_back(2);
d.push_back(e);
// Use the members for operations
int f = d.at(0) * d.at(1);
Since you've now described the problem you're trying to solve instead of just the problem with the solution you came up with:
You don't need to invent variable names or use arrays to compute averages and maximums.
Here's an example of how you can compute an average of the numbers a user inputs:
float sum = 0;
int elements = 0;
float input = 0;
while (cin >> input)
{
sum += input;
elements += 1;
}
std::cout << "Average: " << sum / elements << std::endl;
It's easy to expand this to also keep track of the maximum value so far.
To expand to the average and maximum of a number of series, add another loop "around" it.

How does the modulus operator work?

Let's say that I need to format the output of an array to display a fixed number of elements per line. How do I go about doing that using modulus operation?
Using C++, the code below works for displaying 6 elements per line but I have no idea how and why it works?
for ( count = 0 ; count < size ; count++)
{
cout << somearray[count];
if( count % 6 == 5) cout << endl;
}
What if I want to display 5 elements per line? How do i find the exact expression needed?
in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined). For example:
5 % 2 = 1
13 % 5 = 3
With this knowledge we can try to understand your code. Condition count % 6 == 5 means that newline will be written when remainder of division count by 6 is five. How often does that happen? Exactly 6 lines apart (excercise : write numbers 1..30 and underline the ones that satisfy this condition), starting at 6-th line (count = 5).
To get desired behaviour from your code, you should change condition to count % 5 == 4, what will give you newline every 5 lines, starting at 5-th line (count = 4).
Basically modulus Operator gives you remainder
simple Example in maths what's left over/remainder of 11 divided by 3? answer is 2
for same thing C++ has modulus operator ('%')
Basic code for explanation
#include <iostream>
using namespace std;
int main()
{
int num = 11;
cout << "remainder is " << (num % 3) << endl;
return 0;
}
Which will display
remainder is 2
It gives you the remainder of a division.
int c=11, d=5;
cout << (c/d) * d + c % d; // gives you the value of c
This JSFiddle project could help you to understand how modulus work:
http://jsfiddle.net/elazar170/7hhnagrj
The modulus function works something like this:
function modulus(x,y){
var m = Math.floor(x / y);
var r = m * y;
return x - r;
}
You can think of the modulus operator as giving you a remainder. count % 6 divides 6 out of count as many times as it can and gives you a remainder from 0 to 5 (These are all the possible remainders because you already divided out 6 as many times as you can). The elements of the array are all printed in the for loop, but every time the remainder is 5 (every 6th element), it outputs a newline character. This gives you 6 elements per line. For 5 elements per line, use
if (count % 5 == 4)