Nested for() in c++ [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
No matter how I see this problem, I keep getting the answer to be 10. When I run the program, the answer gives me 20. I am lost as to how this should be solved. Could anyone help me with much detail? Thanks! ps. first programming class in c++.
int n = 0;
for (int i = 1; i <= 5; i++)
for (int j = 0; j < i; j++)
n = n + j;

Let's see n after each iteration of i.
n = prev value of n + sum of 0 to i-1;
i=1 , n= 0
i=2 , n= 0+0+1=1
i=3, n= 1+0+1+2 =4
i=4, n= 4+0+1+2+3=10
i=5, n= 10+0+1+2+3+4 =20

When i == 1 you add 0 to n, so n == 0.
When i == 2 you add 0 and 1 to n, so n == 0 + 0 + 1 == 1.
When i == 3 you add 0, 1, 2 to n, so n == 1 + 0 + 1 + 2 == 4.
When i == 4 you add 0, 1, 2, 3 to n, so n == 4 + 0 + 1 + 2 + 3 == 10.
When i == 5 you add 0, 1, 2, 3, 4 to n, so n = 10 + 0 + 1 + 2 + 3 + 4 == 20
If you only got 10, you either missed the last iteration of the outer loop (because 10 is the result after 4 iterations), or you forgot that you're adding on to what you accumulated in the previous iterations (since the last iteration adds 10 to the total).

Related

Need Explanation for C++ output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
#include <iostream>
int main()
{
int i = 100,sum=0;
for(int i =0; i!=10;++i)
sum+=i;
std::cout<<i<<" "<<sum<<std::endl;
return 0 ;
}
I'm a beginner in C++ , the output of the code is 100 45 . I understand 100 as its block scope but why 45?
As sum is declared in the outer scope and not redefined inside your loop, the loop is operating on the outer sum which means it's value ends up equivalent to the cumulative value of the loop scoped i which would be:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
The i variable is instead redefined in the loop scope (int i=0;), therefore while in the loop block it goes from 0 to 9, but once out of the loop the i variable is taken into account is the one with 100 assigned.
Next time, if you have the tools, I'd recommend stepping through the loop with a debugger and having a look at what the variables and values are doing.
You display i and sum right after it.
At the start of your loop i=100 and as you declare another i in the scope of your loop, when the code goes out of the scope of your loop, it display the value of the first i, that is 100 and sum = 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45.

acending repetitious function without array 1 22 333 4444 55555 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
F is a function that number x has been repeated in an ascending order f(x).
x : 1 2 3 4 5 6 7 8 9 10
f(x): 1 2 2 3 3 3 4 4 4 4
my function gets 'x' and gives 'f(x)' and it has to do it without array but it goes wrong in high numbers.
int main()
{
int n;
cin>>n;
int i=1,a=1;
if(n==1)
cout<<'1';
else{
while(true){
a++;
i=i+a;
if(i>=n)
break;
}
}
cout<<a;
return 0;
}
TL;DR
f(x) = floor(0.5 + sqrt(1 + 8 * (x - 1)) / 2)
Explanation
Well, since this is a mathematical problem, just solve it with math ;)
One thing to notice is the correlation between the table and the triangular numbers:
h(x) = sum(range(1, x)) = x*(x + 1)/2 //triangular number
x 1 2 3 4 5 6 7 8 9 10
f(x) 1 2 2 3 3 3 4 4 4 4
h(f(x)) 1 3 3 6 6 6 10 10 10 10
So how does that help us? Well, we can write a new equation:
h(f(x)) = x | x = max({n | f(n) = f(x)})
And logically for the inverse the following should apply:
h^-1(x) = f(x)
No we've got two options:
Call it a day and just solve the rest via brute-force:
i = 1
sum = 0
while sum < x:
sum += i
i++
return i - 1
Or build our function h^-1(x):
h(x) = y = (x+1)x/2
h^-1(y) = x with h(x) = y
x ^ 2 + x - 2y = 0
solve for x using the quadratic formula:
x = 0.5 +/- sqrt(1 + 8y) / 2
Now this formula still lacks a few things:
we get two results, one of which is negative. We can just throw the negative result away, so +/- turns into +
this formula is 0-based. To be honest, I'm still trying to figure out why. Solution: simply decrement y by 1 to get the proper result
while this formula returns the correct result for the matching numbers, i.e. y = 3 -> x = 3, it returns floating-point numbers for other input, so we'll have to round down appropriately
Putting it together:
f(x) = floor(0.5 + sqrt(1 + 8 * (x - 1)) / 2)
int f(int x) {
return (x * (x + 1)) / 2;
}
int main() {
int n;
cin >> n;
int left = 1, right = n;
while(left < right) {
int mid = left + (right - left) / 2;
int val = f(mid);
if(val >= n) {
right = mid;
}
else {
left = mid + 1;
}
}
cout << left;
return 0;
}
Use binary search. Right now I am in mobile. I will add the explanation later if needed. Let me know if you don't understand anything.

Unexpected result C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am creating a Minesweeper game. However, while testing the generating function, It malfunctions almost always (if not always), and I do not understand why.
Here is my code:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
struct board {
int width=9, mines=10;
char board[9][9];
/* char board[][]
* -1 = Mine
* 0 = No mines near
* 0+ = x amount of mines are near
*/
};
struct point {
int x,y;
};
board newBoard(){
board board1;
point randPoint;
for(int i=0;i<board1.width;i++){
for(int j=0;j<board1.width;j++) board1.board[i][j]=0; // Initialize array
}
for(int i=0;i<board1.mines;i++){
randPoint.x=rand()%board1.width, randPoint.y=rand()%board1.width; // Where will the mine go?
if(board1.board[randPoint.x][randPoint.y]!=-1){ // If not already a mine
board1.board[randPoint.x][randPoint.y]=-1; //make a mine
} else i--; //else don't count this
}
for(int i=0;i<board1.width;i++){
for(int j=0;j<board1.width;j++){
if(board1.board[i][j]==-1) { // If mine exists
// The if checks preceding the ++'s are to prevent out of bounds erors
if (j-1>=0) board1.board[i][j-1]++;
if (j+1<board1.width) board1.board[i][j+1]++;
if (i-1>=0) board1.board[i-1][j]++;
if (i+1<board1.width) board1.board[i+1][j]++;
if ((i-1>=0) && (j-1>=0)) board1.board[i-1][j-1]++;
if ((i-1>=0) && (j+1<board1.width))board1.board[i-1][j+1]++;
if ((i+1<board1.width) && (j-1>=0))board1.board[i+1][j-1]++;
if ((i+1<board1.width) && (j+1<board1.width))board1.board[i+1][j+1]++;
}
}
}
return board1;
}
int main() {
board boardGame=newBoard();
printf("- ");
for(int i=0;i<boardGame.width;i++) printf("%i ",i+1);
printf("\n\n");
for(int i=0;i<boardGame.width;i++){
printf("%i. ",i+1);
for(int j=0;j<boardGame.width;j++) if (boardGame.board[i][j]==-1) {
printf(" X");
} else {
printf(" %i", boardGame.board[i][j]);
}
printf("\n");
}
return 0;
}
This produces:
- 1 2 3 4 5 6 7 8 9
1. 0 0 0 0 1 X 1 0 0
2. 1 1 0 0 2 2 2 1 1
3. X 2 1 1 1 X 1 1 X
4. 1 2 X 0 1 1 0 1 1
5. 0 1 1 1 0 0 0 0 0
6. 0 0 0 0 1 1 1 0 0
7. 0 0 1 1 2 X 1 0 0
8. 1 1 2 X 2 1 1 0 0
9. 1 X 2 1 1 0 0 0 0
As you most likely already know, in the game of minesweeper, there is mines (in this case will they will be marked as X), and all nearby grid points are the number of mines near it (if you are still unfamiliar with it this page may of use). As you can see, the numbers at 4,7 and 4,4 are incorrect.
I do not know why this is this way. Could someone aid my understanding in this, and tell my how to to fix this?
Also, I just noticed that this produces the same output every time it is run. Why?
Ioums is correct, you are not checking to see if a cell is a mine before incrementing it. However, with the way that your code is currently set up, this will mean adding a check that the cell does not equal -1 in every single if statement. You should consider creating a function to safely increment a cell if it is within bounds and not a mine, like so:
void safeIncrement(int x, int y, board& b)
{
if(x >= 0 && y >= 0 && x < b.width && y < b.width && b.board[x][y] != -1)
{
b.board[x][y]++;
}
}
This means that you can replace your if statements with:
safeIncrement(i-1,j,board1);
safeIncrement(i-1,j-1,board1);
safeIncrement(i-1,j+1,board1);
safeIncrement(i,j-1,board1);
safeIncrement(i,j+1,board1);
safeIncrement(i+1,j,board1);
safeIncrement(i+1,j-1,board1);
safeIncrement(i+1,j+1,board1);
Which is much more readable in my opinion. Additionally, since the function doesn't increment the cell if it is a mine, you could also replace the if statements with the following code!
for(int a=-1; a<=1; a++)
{
for(int b=-1; b<=1; b++)
{
safeIncrement(i+a,j+b, board1);
}
}
The problem happens when 2 mines are close together: when you're adding to the mine count, you don't check if that square has a mine.
Suppose you get a mine on (0, 0) and another on (0, 1). When you're adding to the mine count around (0, 0), you accidentally also add to the mine in (0, 1), changing it from -1 to 0. It also makes the second mine being processed disappear.
I suggest using another number to signal a mine, like -999, and check if the number is negative when looking for them. It's easier than adding another condition for all if clauses you already have.

Passing an array to a function in C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am trying to recreate the game 2048 in C++.
I'm working on a spawn function right now. It takes in an array of the current values of the 16 spots, randomly scans for an empty one, and puts either a 2 or a 4 in that spot.
I am starting out with a test array, b. I want to pass this array to a function that will alter one of its values, which I know I need to do by passing a pointer, but none of the changes are staying after I leave the function.
Can anyone see what is wrong here? How do I properly pass the array in so the changes will stay after the spawn function?
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void showBoard(int board[]);
void spawn(int* board);
int main() {
srand(time(NULL));
int b[16] = {2, 2, 2, 2};
int* bp = b;
showBoard(b);
spawn(bp);
showBoard(b);
}
// print out the 16 current tiles to the console
void showBoard(int board[]) {
for(int i=0; i<=15; ++i){
if(i%4==0)
cout<<'\n';
cout<<board[i]<<" ";
}
cout<<'\n';
}
void spawn(int* board) {
int x; // index
// randomly choose an index to spawn a 2 or 4:
do x=rand()%16; while(board[x]!=0);
// when found empty place (with value 0), spawn a new tile.
/* there should be a 90% chance of spawning a 2
* and a 10% chance of spawning a 4. Generate a
* random number between 0 and 9, and if it is
* 9, make the new spawn tile a 4.
*/
if (rand()%10 == 9) {
board[x] == 4;
cout << "added 4 \n";
}
else {
board[x] == 2;
cout << "added 2 \n";
}
}
The output:
2 2 2 2
0 0 0 0
0 0 0 0
0 0 0 0
added 2
2 2 2 2
0 0 0 0
0 0 0 0
0 0 0 0
So my cout confirms that I got to the if block where I would set board[x] to 2, but when I do showBoard afterwards, there is no update to the array. Any help?
board[x] == 2;
board[x] == 4;
Need to be:
board[x] = 2;
board[x] = 4;
Also, it may make the code simpler if you make this a 2D 4x4 array. Picking a random square would then become:
int x = rand() % 16;
int board_spot = board[x%4][x/4];

combinations for numbers 0 to 40 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I would like to know all possible combinations from 0-40 in sets of 2. So for example:
1 / 1 -
1 / 2 -
1 / 3 -
1 / 4 -
1 / 5 -
1 / 6 -
1 / 7 -
1 / 8 -
1 / 9 -
1 / 10
All the way to 40 and all possible combinations.
Cheers.
In haskell:
[(x, y) | x <- [1..40], y <- [1..40]]
In other languages you should probably look at for-loops: (this is C#)
Tuple<int, int>[,] things = new Tuple<int, int>[40,40];
for (int i = 0; i < 40; i++)
{
for (int j = 0; j < 40; j++)
{
things[i,j] = Tuple.Create(i+1,j+1);
}
}