fire simulation program dont know how to initialize it - c++

The program is supposed to output a matrix of 12x24 which is bordered by 0s, has 1s in the middle, and a 2 at the location of (1,1) i do not know in which part to initialize M[row][col]=2; because anywhere i put it, it does not output the 2 to the first spot, any suggestions?
int main()
{
int M[N/2][N];
int ROWS, COLS, row, col;
int r, c;
ROWS = sizeof(M) / sizeof(M[0]);
COLS = sizeof(M[0]) / sizeof(M[0][0]);
fill(M, ROWS, COLS, 1, 1);
row=1;
col=1;
for(r=0; r< ROWS; r++)
{
for(c=0; c < COLS; c++)
{
if (r==0||r ==ROWS-1)
{
M[ROWS][COLS]=0;
}
else if(c==0||c==COLS-1)
{
M[ROWS][COLS]=0;
}
else {
M[ROWS][COLS]=1;
}
cout<< M[ROWS][COLS];
}
cout << endl;
}
print(M, ROWS, COLS);
return 0;
}

I notice you're using ROWS and COLS as array indices inside the for loops...you
probably meant to use the loop variables r and c.
Also, it's considered bad form to use upper case names for regular variables...the
convention in C is to use upper case identifiers only for macros.

I bet if you write M[1][1]=2; just before the line cout<<M[ROWS][COLS] then you will see the output you want. It is silly to do it that way, because then you will assign that single location (M[1][1]) to the same value repeatedly--to be exact, 288 times--but you cannot print the wrong value for M[1][1] if you set it to the correct value each time you print anything. There are better ways to do it, of course.
You would be much better off to cleanly separate the actions the program performs. There are really two things it must do:
Initialize the array.
Print the contents of the array.
Each of these actions should be performed by a different function. That is, call one function one time to initialize the entire array, and then call another function one time to print the entire array. This way every cell in the array is set to the correct value before any cell is printed.
If you do this, you should very easily be able to find a good place in your code to set M[1][1]=2 so that you see the correct printout.
I am assuming this is an exercise that will later be extended to do something more with the array, so that it makes sense to use an array in the first place. If so, there is a very good chance you'll have to print the array again at some point, and then you'll be very glad that you wrote a function that prints the array and does nothing else.

Related

How would I overwrite a printed 2D array to simulate 'updates'

So given a 2D array called 'world' and the code below to output the array to the console. I want to constantly update the outputted array using a while loop to simulate movement and other actions via changes in the array values without it messily reprinting the entire thing for every update.
I would imagine the best way to do this would be to try and reset the output stream to the first line and overwrite the previous printed array each update but I am unsure on how to do this.
char world[20][20];
for (unsigned int row = 0; row < std::size(world); row++)
{
for (unsigned int col = 0; col < std::size(world); col++)
{
std::cout << world[row][col];
}
std::cout << std::endl;
}
There is a simple way to do this on one line, using \r with printf, as discussed here. However, I'm not certain this is easy if one wishes to reprint multiple lines, as you do.
A better suggestion would be to make use of something like ncurses, which seems to be designed for your purposes, and was probably used to make other programs you've seen operate this way.

Different output rather than expected one

Hello I am a high school student. Recently I started to do some programming in c++. But I'm stuck with the example below. I would appreciate it if you people could help me.
#include<iostream>
using namespace std;
int main()
{
int j;
for(int i=0;i<10;i++)
{
i=j;
}
cout<<j;
}
Why is the output: 2686864?
Instead I think it should be 0123456789, as the loop starts from 0. Thank you for any suggestions. .
what you want to do is pobably this:
int main()
{
int j;
for(int i=0;i<10;i++)
{
j=i;
cout<<j;
}
}
of course, you don't need the variable j here at all; you can simply output i
You haven't assigned a value to j in your declaration. In your loop the assignment is always to i, because of the order of the equals sign, and in fact you're always assigning to i the uninitialized value of j from outside your loop. So j remains at the seemingly crazy value it was initially set to be.
You want to assign the value of i to j inside the loop, i.e. reverse the equality, if you want to see it change. Also if you want to see more than one output, you need to move your print statement inside the for loop.
What you're seeing as output is not the output of multiple print statements - it's the single number automatically assigned to the initial value of j, because you didn't give it a value when you declared it. Best wishes.
First, variable "j" is not initialized. Then you are setting your loop variable to the value of j.
It looks like you're trying to build a string "0123456789", in which case, you need make j a string, and concatenate the character for each number to the end of the string in your loop.
In the loop you are looping while i < 10 and i starts at 0. If you want to set j = i then you need to switch the order of the variables because if not it could mess up the loop, but not necessarily in this situation.
Also you should initialize j to some value because if not you will get garbage values.
Also it won't output it the way you are wanting it. You should move the cout statement inside the for loop to get the out put you desire.

Print statement changing output of function?

I have a bit of c++ code that's supposed to look at the derivative of a function and collect the points that have a slope greater than some threshold. It's been giving me troubles, so I've been putting print statements everywhere to figure out what is going wrong. I stumbled upon a baffling issue where when I used std::cout<< to print the size of an array, it changed the output of the function! Here's the code snippet:
int* Tools::findPoi(float* y, int size, float threshold, int width, float step, int* outsize){
int poi[size];
float* derive = derivative(smooth(y,size,width),size, step);
int n = 0;
std::cout<<size<<" data size\n";
for(int i = 0; i<size; i++) {
if(derive[i] > threshold) {
poi[n] = i;
n++;
}
}
*outsize = n-1;
return poi;
}
without the commented out line "std::count..." I get 82 poi. But if I comment it out or remove it I get 84 poi. Nothing else changes, only this print statement. I am so confused as to why or even how it could possibly change the output. Any help would be greatly appreciated.
EDIT: ok, so actually, it's just random. The variable n is different everytime I run it, which leads me to believe that something weird is going on in memory.
There is a significant problem with the line:
return poi;
This returns the address of a local object. The array no longer exists when it goes out of scope at the end of the function. For a wonderful explanation see: Can a local variable's memory be accessed outside its scope?.
Since this is C++ and you want a dynamic array I suggest you use std::vector. It solves many problems such as this.

C++ program to compute lcm of numbers between 1 to 20 (project euler )

as the title explains this is a program to find lcm of numbers between 1 to 20. i found an algorithm to do this, here's the link
http://www.cut-the-knot.org/Curriculum/Arithmetic/LCM.shtml
there is a java applet on the webpage that might explain the algorithm better
Problem: i wrote the code compiler shows no error but when i run the code the program goes berserk, i guess may be some infinite loopig but i can't figure it out for the life of me. i use turbo c++ 4.5 so basically if anyone can look at the code and help me out it would be great . thanks in advance
Algorithm:
say we need to find lcm of 2,6,8
first we find the least of the series and add to it the number above it, i.e the series become
4,6,8
now we find the least value again and add to it the intitial value in the column i.e 2
6,6,8
so the next iteration becomes
8,6,8
8,12,8
10,12,8
10,12,16
12,12,16
14,12,16
14,18,16
16,18,16
18,18,16
18,18,24
20,18,24
20,24,24
22,24,24
24,24,24
as you can see at one point all numbers become equal which is our lcm
#include<iostream.h>
/*function to check if all the elements of an array are equal*/
int equl(int a[20], int n)
{
int i=0;
while(n==1&&i<20)
{
if (a[i]==a[i+1])
n=1;
else
n=0;
i++;
}
return n;
}
/*function to calculate lcm and return that value to main function*/
int lcm()
{
int i,k,j,check=1,a[20],b[20];
/*loading both arrays with numbers from 1 to 20*/
for(i=0;i<20;i++)
{
a[i]=i+1;
b[i]=i+1;
}
check= equl(a,1);
/*actual implementation of the algorith*/
while(check==0)
{
k=a[0]; /*looks for the least value in the array*/
for(i=0;i<20;i++)
{
if(a[i+1]<k)
{
k=a[i+1]; /*find the least value*/
j=i+1; /*mark the position in array */
}
else
continue;
}
a[j]=k+b[j]; /*adding the least value with its corresponding number*/
check= equl(a,1);
}
return (a[0]);
/*at this point all numbers in the array must be same thus any value gives us the lcm*/
}
void main()
{
int l;
l=lcm();
cout<<l;
}
In this line:
a[j]=k+b[j];
You use j but it is unitialized so it's some huge value and you are outside of the array bounds and thus you get a segmentation fault.
You also have some weird things going on in your code. void main() and you use cout without either saying std::cout or using namespace std; or something similar. An odd practice.
Also don't you think you should pass the arrays as arguments if you're going to make lcm() a function? That is int lcm(int a[], int b[]);.
You might look into using a debugger also and improving your coding practices. I found this error within 30 seconds of pasting your code into the compiler with the help of the debugger.
Your loop condition is:
while(n==1&&i<20)
So your equl function will never return 1 because if n happens to be 1 then the loop will just keep going and never return a 1.
However, your program still does not appear to return the correct result. You can split the piece of your code that finds the minimum element and replace it with this for cleanliness:
int least(int a[], int size){
int minPos = 0;
for(int i=0; i<size ;i++){
if (a[i] < a[minPos] ){
minPos = i;
}
}
return minPos;
}
Then you can call it by saying j = least(a, 20);. I will leave further work on your program to you. Consider calling your variables something meaningful instead of i,j,k,a,b.
Your equl function is using array indices from 0-20, but the arrays only have 1-19
j in lcm() is uninitialized if the first element is the smallest. It should be set to 0 at the top of the while loop
In the following code, when i=19, you are accessing a[20], which is out of the bounds of the array. Should be for(i=0;i<19;i++)
for(i=0;i<20;i++) {
if(a[i+1]<k)
You are not actually using the std namespace for the cout. this should be std::cout<<l
Your are including iostream.h. The standard is iostream without the .h, this may not work on such an old compiler tho
instead of hard-coding 20 everywhere, you should use a #define. This is not an error, just a style thing.
The following code does nothing. This is the default behavior
else
continue;

Insert into a desired element of an array and push all other elements one spot over in c++

Having some issues with one small function I'm working on for a homework assignment.
I have a static array size of 20 (shelfSize), however, I only need to use a max of 10 elements. So I don't have to worry about out of bounds etc (the entire array of 20 is initialized to 0).
What I am looking to do is insert an integer, booknum, into an element of an array it receives as input.
This my current logic:
void insert_at(int booknum, int element){
for(int i=element+1; i < shelfSize; i++)
bookshelf[i+1]=bookshelf[i]
bookshelf[element]=booknum;
}
so let's say I have the this array:
[5,4,3,1,7]
I want to insert an 8 at element 1 and have the array turn to:
[5,8,4,3,1,7]
Technically, everything after the final element 7 is a 0, however, I have a separate print function that only prints up to a certain element.
No matter how many times I take some pencil and paper and manually write out my logic, I can't get this to work.
Any help would be appreciated, thanks.
You should start from the end of the array, this should word for you:
void insert_at(int booknum, int element)
{
for (int i = shelfsize-1;i>element;i--)
bookshelf[i] = bookshelf[i-1];
bookshelf[element] = booknum;
}
Also I recommend that you get used to handling illegal values, for example, what if a user entered 21?
The optimized code would be:
bool insert_at(int booknum, int element)
{
if (element>=shelfsize-1)
return false;
for (int i = shelfsize-2;i>element;i--)
bookshelf[i] = bookshelf[i-1];
bookshelf[element] = booknum;
return true;
}
If your example is correct, then you're assuming 1-based indices instead of 0-based. Use the following instead:
void insert_at(int booknum, int element){
for(int i=element; i < shelfSize; i++)
bookshelf[i]=bookshelf[i-1];
bookshelf[element-1]=booknum;
}
However, I would prefer you just use the same code, and change "at element 2" in your example to "at element 1". Always remember C++ arrays are 0-based.
That being said, please tell your professor that this is why vectors (and other standard containers) were made, and that C++ arrays are evil.
http://www.parashift.com/c++-faq-lite/containers.html#faq-34.1
Just noticed, you are copying up, this means your function does this:
[5,4,3,1,7]
--^
[5,4,4,1,7]
--^
[5,4,4,4,7]
--^
[5,4,4,4,4]
--^
[5,4,4,4,4,4]
For moving values in an array, you always want to copy in the opposite direction to which you are moving, so to move up, you want to copy each item up from the top down:
[5,4,3,1,7]
--^
[5,4,3,1,7,7]
--^
[5,4,3,1,1,7]
--^
[5,4,3,3,1,7]
--^
[5,4,4,3,1,7]
And then you can overwrite the index you freed up.