Different output rather than expected one - c++

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.

Related

C++ character variable value of '\x1'

I'm failing to understand why would the loop exit at the value of character variable i = '\x1'
#include <iostream>
using namespace std;
int main()
{
char i;
for (i = 1; i < 10, i++;)
{
cout << i << endl;
}
return 0;
}
Can somebody please explain this behavior ?
This is wrong
for (i = 1; i < 10, i++;)
/* ^ should be ; */
You only declared 3 regions for the loop, but put your increment statement in the middle area, and left your increment area empty. I have no idea which statement in the middle area your compiler will choose to execute. Best not to try to be cute and deceive your compiler. Let alone some colleague who will read your code years from now and go WTF???
A for loop has 3 distinct areas delimited by semi-colons:
The initialization area. You can declare as many variables in here as you want. These can be delimited by commas.
The test area. This is where an expression goes to test if the loop should continue.
The post loop area. This region of code gets executed after every loop.
Try to keep it simple. If it is going to be more complicated then use a while loop.
The reason that i ends up being 1 is that when i++ is zero, which terminates the loop, then i will become 1 (That is what the form of the ++ operator you used does). As the other answered have pointed out, once you fix your code by moving i++ out of the condition by replacing the comma with a semicolon, then i will make it all the way to 10 as desired.
for (i = 1; i < 10; i++)
You wrote for statement wrong.

fire simulation program dont know how to initialize it

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.

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;

in visual c++, warning comes but program doesnt runs furthers, is there any way to igonre it?

I have written some code, here is a snippet of it is:
int num[8],n=0;
for (n = 0; n<8; n++)
{
char temp = binnum[n];
num[n] = atoi(&temp);
cout << num[n];
}
It doesn't gives any error, but I do get a warning. When I run it on C++, it gives Run Time Check Failure - The variable n is being used without being initialized.
After that, it doesn't run any further and the program closes. Is there any way to ignore this error? Because if I initialize n, it gives the wrong answer. For example, if answer is 101011, it will give 10101100, which is wrong.
Initialize n as #anthares pointed out and increment it at the end of the loop so your loop actually works.
int number[8];
int n = 0;
do
{
char temp = binnum[n];
number[n] = atoi(&temp);
cout << number[n];
n++;
} while (n<8);
Your main problem (after all the edits) is that atoi takes a null-terminated char array (C-style string). The address of a single char variable does not make a C-style string.
To convert a single character in range ['0'...'9'] to a corresponding number use:
number[i] = temp - '0';
possibly having checked that temp contains a digit character.
Give a value to your vairable n before using it int number [8], n=0 for example. Otherwise, it is "not defined behavior" what is the value of n and how many iterations you will do in your cycle.
Also, As it is written your loop will go forever since you never change the value of n ...
You are using n before it is assigned a value. You need to ensure that n is initialized (to 0, maybe) before you begin to reference it in your code. You do not want to ignore this error.
Try something like this:
const int count = 8;
int number[count];
for (int i=0; i < count; i++)
{
char temp = binnum[i];
number[i] = atoi(&temp);
cout << number[i];
}
what? you never assign any value to n.
and even if you will for example do int number[8],n=0; you never change n's value you you will end up with an infinite loop.
You should really initialize n (and also increment it, for that matter).
You are probably running a debug build of your application. In this case, the variable is probably always initialized with the same value. This is why you see the result you expect. It seems to behave correct purely by accident.
As soon as your application is built in release mode, n may have a different value each time the program is run and thus the output will be unpredictable.
This is what happens when you have undefined behavior in your program.

trying to sort a simple string in c++

#include "stdio.h"
#include "conio.h"
#include <iostream>
using namespace std;
int main (void)
{
char my_char[] = "happy birthday";
int i;
bool j=false;
char my_char_temp[1];
do
{
for (i=0;i<sizeof(my_char)-2;i++)
{
j=false;
if (my_char[i+1] < my_char[i])
{
my_char_temp[0]=my_char[i+1];
my_char[i+1] = my_char[i];
my_char[i] = my_char_temp[0];
j=true;
}
}
}while (j);
cout << my_char;
}
What am I doing wrong?
I'm just trying to sort the letters within the char.
The output I get is completely wrong.
You want to use strlen() rather than sizeof.
You are resetting j to false each and every time you compare two characters.
This means that, if you swap two characters, and you are NOT at the end of your array, you will forget that you have swapped them.
Move the j=false; from inside the for-loop to just inside the do-loop.
And you owe me a bottle of Jack for saving your ass on a homework assignment on Sunday afternoon.
I don't know what are you trying to implement with your sizeof(...) - 2 and etc, but what you probably want to get can be done this way:
#include <iostream>
#include <algorithm>
int main() {
std::string s("happy birthday");
std::sort(s.begin(), s.end());
}
Consider what happens inside this loop:
for (i=0;i<sizeof(my_char)-2;i++)
If you find a pair of values to swap, setting j to true, you'll continue iterating through that loop, and set j back to false on the next iteration. As a result, the program is going to exit as soon as the last two characters in the string are in sorted order, regardless of whether the rest of the string is sorted.
Instead, as soon as you find a pair of characters to swap, you want to start over again at i=0. The simplest way to do that is add a break; statement after your j = true line. With that fix, this works correctly.
Alternately, you could move the initial j = false line outside the loop, which would solve the problem in a slightly different way.
You are actually very close. The only problem is that
j=false;
needs to be in the outer loop. As is, j is cleared every time the inner loop executes.
With this fix, your program works fine for me.
Stylistic errors, however, are another story.
I could be mistaken but it looks like you're trying to do a bubble sort?
And it's i < sizeof(my_char)-2 because he's using a 0-based, null terminated string, and he doesn't want to sort the null terminator.
Try just repeating the condition of the inner loop, using j instead of i, and see if that works? Note that this has a run time of O(n^2) and you can get sorts down much much faster than that if you need to. Alternately you can move the boolean out of the for and into the do loop.
for (i=0;i < sizeof(my_char)-2;i++)
for (i=0;i<sizeof(my_char)-2;i++)
{
if (my_char[i+1] < my_char[i])
{
my_char_temp[0]=my_char[i+1];
my_char[i+1] = my_char[i];
my_char[i] = my_char_temp[0];
}
}