C++ character variable value of '\x1' - c++

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.

Related

How do I prevent command line closing after pressing Enter

So I wanted to write a program which prints out a pyramid made out of "O", whose height is given by user input.
#include <stdio.h>
int main()
{
int n, i, j, k;
scanf_s("%d", &n);
{
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n - i; j++)
{
printf(" ");
}
for (k = 1; k <= 2 * i - 1; k = k + 1);
{
printf("O");
}
printf("\n");
}
return 0;
}
}
I'm a complete beginner, so if you have any advice, please do offer it. Anyways, I tried running it on a compiler on Android; seemed to work, printed out the pyramid.
Tried it on Microsoft Visual Studio. The command line opens, but after I put in the number and press "enter", the whole window just closes without giving me anything. How do I prevent this? Programs that don't need user input seem to run just fine.
For your described problem: Preventing console window from closing on Visual Studio C/C++ Console application
For your code, there seems to be a mistake, and currently your code will not produce a pyramid, but a slash of O. To solve this problem:
for (k = 1; k <= 2 * i - 1; k = k + 1); remove the ; from this line. Why this solved the problem?
When there is a ; after the loop, it means that the loop does nothing, and then the next three lines are:
{
printf("O");
}
Which means that there are only a single O prints out, instead of printing it in a loop.
Apart from the semicolon after the for (k = 1... loop, you have no bug in this code; if Visual Studio closes, the issue is with that program. (It could well just be closing because the program has finished execution, but I don't know that program).
Since you write that you are a complete beginner and you would appreciate advice, I'll offer some stylistic comments. But these are just comments on how I would do things differently if I were you, I am not saying that what you have is wrong.
Single-letter variable names: these will bite you. It is really easy to mix up i, j, and k since they are all kind of meaningless indexes. When your programs become more complex you will be happy to have meaningful variable names. Also, if you are trying to locate instances of a variable, searching for 'i' is a lot harder than searching for "spaces" or "spc"
Code block under scanf_s(): There is no reason to have this code inside a block--all that does is shift the internal code one tab right. Screenspace is precious.
You will likely find it more useful to iterate from 0 than from 1, as you will be using your iterator variable as an array index a whole lot. Getting into the habit of writing your loops as for (dex = 0 ; dex < max_val ; dex++) will serve you well. Note well that the comparison is "dex < max_val" and not "dex <= max_val"
The "k = k + 1" seems bad to me--people reading your code will need to stop and try to figure out why it's not just "k++" which what people are expecting and what you use in the other two loops. (And even for incrementing-by-more-than-one I'd expect something like "k += 2" not "k = k + 2")
Once console application returns from main method, the associated console window closes automatically. For Windows OS add a system("pause"); before your return 0; statement. For platform independent solution you can just show a prompt to user and wait for a key press before returning from main. Any character remaining in input buffer (enter from scanf in this case) must be cleared.
int main()
{
.........
.........
//clear input buffer
int d;
while ((d = getchar()) != '\n' && d != EOF) { }
printf("Press ENTER key to Continue\n");
getchar();
return 0;
}
You should include conio.h header file in your program and then simply place getch(); after your program's last cout statement.
I think that this would help the window from closing
it worked for me ;)
Put a cin command(C++) or a C equivalent at the very end just before return 0;, so it wont close. :>
Eg:
.
.
.
.
int control; cin>>control;
return 0;
}

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.

Post-increment and pre-increment within a 'for' loop produce same output [duplicate]

This question already has answers here:
Difference between pre-increment and post-increment in a loop?
(22 answers)
Closed 8 years ago.
The following for loops produce identical results even though one uses post increment and the other pre-increment.
Here is the code:
for(i=0; i<5; i++) {
printf("%d", i);
}
for(i=0; i<5; ++i) {
printf("%d", i);
}
I get the same output for both 'for' loops. Am I missing something?
After evaluating i++ or ++i, the new value of i will be the same in both cases. The difference between pre- and post-increment is in the result of evaluating the expression itself.
++i increments i and evaluates to the new value of i.
i++ evaluates to the old value of i, and increments i.
The reason this doesn't matter in a for loop is that the flow of control works roughly like this:
test the condition
if it is false, terminate
if it is true, execute the body
execute the incrementation step
Because (1) and (4) are decoupled, either pre- or post-increment can be used.
Well, this is simple. The above for loops are semantically equivalent to
int i = 0;
while(i < 5) {
printf("%d", i);
i++;
}
and
int i = 0;
while(i < 5) {
printf("%d", i);
++i;
}
Note that the lines i++; and ++i; have the same semantics FROM THE PERSPECTIVE OF THIS BLOCK OF CODE. They both have the same effect on the value of i (increment it by one) and therefore have the same effect on the behavior of these loops.
Note that there would be a difference if the loop was rewritten as
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = ++i;
}
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = i++;
}
This is because in first block of code j sees the value of i after the increment (i is incremented first, or pre-incremented, hence the name) and in the second block of code j sees the value of i before the increment.
The result of your code will be the same. The reason is that the two incrementation operations can be seen as two distinct function calls. Both functions cause an incrementation of the variable, and only their return values are different. In this case, the return value is just thrown away, which means that there's no distinguishable difference in the output.
However, under the hood there's a difference: The post-incrementation i++ needs to create a temporary variable to store the original value of i, then performs the incrementation and returns the temporary variable. The pre-incrementation ++i doesn't create a temporary variable. Sure, any decent optimization setting should be able to optimize this away when the object is something simple like an int, but remember that the ++-operators are overloaded in more complicated classes like iterators. Since the two overloaded methods might have different operations (one might want to output "Hey, I'm pre-incremented!" to stdout for example) the compiler can't tell whether the methods are equivalent when the return value isn't used (basically because such a compiler would solve the unsolvable halting problem), it needs to use the more expensive post-incrementation version if you write myiterator++.
Three reasons why you should pre-increment:
You won't have to think about whether the variable/object might have an overloaded post-incrementation method (for example in a template function) and treat it differently (or forget to treat it differently).
Consistent code looks better.
When someone asks you "Why do you pre-increment?" you'll get the chance to teach them about the halting problem and theoretical limits of compiler optimization. :)
This is one of my favorite interview questions. I'll explain the answer first, and then tell you why I like the question.
Solution:
The answer is that both snippets print the numbers from 0 to 4, inclusive. This is because a for() loop is generally equivalent to a while() loop:
for (INITIALIZER; CONDITION; OPERATION) {
do_stuff();
}
Can be written:
INITIALIZER;
while(CONDITION) {
do_stuff();
OPERATION;
}
You can see that the OPERATION is always done at the bottom of the loop. In this form, it should be clear that i++ and ++i will have the same effect: they'll both increment i and ignore the result. The new value of i is not tested until the next iteration begins, at the top of the loop.
Edit: Thanks to Jason for pointing out that this for() to while() equivalence does not hold if the loop contains control statements (such as continue) that would prevent OPERATION from being executed in a while() loop. OPERATION is always executed just before the next iteration of a for() loop.
Why it's a Good Interview Question
First of all, it takes only a minute or two if a candidate tells the the correct answer immediately, so we can move right on to the next question.
But surprisingly (to me), many candidates tell me the loop with the post-increment will print the numbers from 0 to 4, and the pre-increment loop will print 0 to 5, or 1 to 5. They usually explain the difference between pre- and post-incrementing correctly, but they misunderstand the mechanics of the for() loop.
In that case, I ask them to rewrite the loop using while(), and this really gives me a good idea of their thought processes. And that's why I ask the question in the first place: I want to know how they approach a problem, and how they proceed when I cast doubt on the way their world works.
At this point, most candidates realize their error and find the correct answer. But I had one who insisted his original answer was right, then changed the way he translated the for() to the while(). It made for a fascinating interview, but we didn't make an offer!
Hope that helps!
Because in either case the increment is done after the body of the loop and thus doesn't affect any of the calculations of the loop. If the compiler is stupid, it might be slightly less efficient to use post-increment (because normally it needs to keep a copy of the pre value for later use), but I would expect any differences to be optimized away in this case.
It might be handy to think of how the for loop is implemented, essentially translated into a set of assignments, tests, and branch instructions. In pseudo-code the pre-increment would look like:
set i = 0
test: if i >= 5 goto done
call printf,"%d",i
set i = i + 1
goto test
done: nop
Post-increment would have at least another step, but it would be trivial to optimize away
set i = 0
test: if i >= 5 goto done
call printf,"%d",i
set j = i // store value of i for later increment
set i = j + 1 // oops, we're incrementing right-away
goto test
done: nop
If you wrote it like this then it would matter :
for(i=0; i<5; i=j++) {
printf("%d",i);
}
Would iterate once more than if written like this :
for(i=0; i<5; i=++j) {
printf("%d",i);
}
Both i++ and ++i is executed after printf("%d", i) is executed at each time, so there's no difference.
You could read Google answer for it here:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Preincrement_and_Predecrement
So, main point is, what no difference for simple object, but for iterators and other template objects you should use preincrement.
EDITED:
There are no difference because you use simple type, so no side effects, and post- or preincrements executed after loop body, so no impact on value in loop body.
You could check it with such a loop:
for (int i = 0; i < 5; cout << "we still not incremented here: " << i << endl, i++)
{
cout << "inside loop body: " << i << endl;
}
The third statement in the for construct is only executed, but its evaluated value is discarded and not taken care of.
When the evaluated value is discarded, pre and post increment are equal.
They only differ if their value is taken.
Yes, you'll get exactly same outputs for both. why do you think they should give you different outputs?
Post-increment or pre-increment matters in situations like this:
int j = ++i;
int k = i++;
f(i++);
g(++i);
where you provide some value, either by assigning or by passing an argument. You do neither in your for loops. It gets incremented only. Post- and pre- don't make sense there!
There is a difference if:
int main()
{
for(int i(0); i<2; printf("i = post increment in loop %d\n", i++))
{
cout << "inside post incement = " << i << endl;
}
for(int i(0); i<2; printf("i = pre increment in loop %d\n",++i))
{
cout << "inside pre incement = " << i << endl;
}
return 0;
}
The result:
inside post incement = 0
i = post increment in loop 0
inside post incement = 1
i = post increment in loop 1
The second for loop:
inside pre incement = 0
i = pre increment in loop 1
inside pre incement = 1
i = pre increment in loop 2
Compilers translate
for (a; b; c)
{
...
}
to
a;
while(b)
{
...
end:
c;
}
So in your case (post/pre- increment) it doesn't matter.
EDIT: continues are simply replaced by goto end;

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];
}
}

Beginner for loop problem

[EDIT]Whoops there was a mistake in the code, and now all the responses to the question seem bizzare, but basically the for loop used to be, for(i=0; i<15; i++). I also edited to make the question more clear.[/EDIT]
I am trying to make a for loop, that checks a 16 element array, so it loops from 0 to 15. I then use the i variable later, however sometimes i == 16, which causes problems by being out of bounds.
I have a solution but it doesnt seem elegant, which makes me think I am missing something. I've tried while loops, but I can never get any loop to go from 0 to 15, and never end at a value greater than 15.
Is there any way to make a loop go and check all 16 elements of the array, while never being greater than 15 at the end of the loop?
int i;
for(i=0; i<16; i++)
{
someClass.someMethod(i);
if(someClass.Test())
{
break;
}
}
if (i == 16)
{
i = 15;
}
I suggest using some other variable other than i after your loop is finished. The criteria of using a for loop instead of a while loop is that you know beforehand exactly how many times a for loop will execute. If you already know this, just set some other variable to the ending value of your loop and use it instead of giving i a dual purpose.
int j = 15;
for(int i=0; i <= j; i++)
{
someClass.array[i];
}
// continue on using j, which value hasn't changed
Well for starters, your sample code loops from 0 to 14. But if you loop from 0 to 15, naturally i has to be 16 before the loop can end. What happens is it becomes 16, THEN your loop notices it's out of bounds and breaks out. If you want it to end at 15, honestly the easiest thing to do is just decrement just after the loop end.
i is incremented on last check to be 16, which is not less than 15, so loop exits with i being 16.
Maybe it's useful to know that:
for (before; check; after) { body }
it's the same as:
before
while(check) {
body
after
}
If you think at your for loop in that term, maybe you'll find out easily why i, at the exit, is 16.
There seems to be some fundamental flaws in your approach.
You shouldn't really use an index variable outside the scope of the loop.
You should use a variable or function to determine the limit of the loop.
It would be better to use iterators instead of numeric indexes.
Generic algorithms can remove the need for loops.
Just my $0.02.
So - if you're checking a 16 element array, normally you'd do this:
for(i=0; i<16; i++)
How for works, is it starts with the first statement of three:
i=0
Then it does your check, in the second statement:
i < 16 // True here, since 0 < 16
That happens before your loop. Then it runs the block of your loop with that set:
someClass.array[i]; //0
Finally, it does the final statement:
i++
Then it repeats the second and third statements, in a sequence.
Before the last run, i == 14, then it does i++, setting i to 15, and executes the block. Finally, it does i++, setting:
i==16
At this point, the condition is no longer true:
i < 16 // False, since i==16
At this point, your block does not execute, but i is still set to 16.
You must have missed something.
In this loop it wouldn't even hit 15, you'd need to say i <= 15, as soon as i = 14 it'd run once and bail.
The for loop is equivalent to the following while loop:
i = 0;
while(i < 16) {
someClass.array[i];
i++;
} // while
i needs to reach 16 to get out of the loop correctly.
Technically there are ways of writing the loop such that i is 15 on exiting the loop, but you shouldn't do them:
int i = 0;
while (1) {
someclass.someMethod(i);
if (i < 15) {
i++;
} else {
break;
}
}
Yes, it does what you ask. But the flow is horrible.
You cannot accomplish this with the built-in loop structures, and as Bill The Lizard said, you probably don't really want to reuse the for-loop variable.
But, if you really want to, here's a way to do it. The trick is to put the loop condition in the middle of the loop:
int i = 0;
while (true)
{
someclass.array[i];
if (i == 15)
break;
++i;
}
The key issue to understand here is that there are 17 different answers to the question "What value of i causes the test to succeed?". Either i can be in {0, 1, ..., 15}, or no value of i causes the test to succeed, which is denoted by i == 16 in this case. So if i is restricted to only 16 values, the question cannot be answered.
There are legitimate cases where you do not want to go past the last valid value. For instance, if you had 256 values and for some reason you only have one byte to count with. Or, as happened to me recently, you want to examine only every ith element of an array, and the last addition to your iterator takes you far beyond the end of the array. In these cases loop unrolling is necessary.
However, for this problem it would be cleaner to use a flag:
bool flag = false;
for (int i = 0; i < 15; ++i)
{
someClass.someMethod(i);
if (someClass.Test())
{
flag = true;
break;
}
}
Then it's clear whether or not the test ever succeeded.
If your loop terminates natuarally, rather than with a break, i will be 16. There's no way to avoid this. Your code is perfectly acceptable if what you want is for i to end up as 15 or less:
int i;
for (i=0; i<16; i++) {
someClass.someMethod(i);
if (someClass.Test())
break;
}
if (i == 16)
i = 15;
Anything that changes i from 16 to 15 after the loop body will do:
if (i == 16) i = 15;
i = (i == 16) ? 15 : i;
i = MAX (15,i); /* where MAX is defined :-) */
and so on.
However that assumes that i is going to be used for something meaningful as a post-condition with respect to that loop. I find that's rarely the case, people tend to re-initialize it before re-use (such as another for loop).
In addition, what you are doing makes it very difficult (impossible, even) to figure out as a post-condition, wheteher your loop terminated normally or whether it terminated prematurely because someClass.Test() returned true for i == 15. This means using i to make further decision is fraught with danger.
My question would be: Why do you think you need to leave i as 15 or less?
I am trying to make a for loop, that
checks a 16 element array, so it loops
from 0 to 15. I then use the i
variable later, however sometimes i ==
16, which causes problems by being out
of bounds.
You need to check for the case where your for loop didn't break, because this information determines whether or not whatever you wanted to do with i is valid.
There are a couple of ways to do this. One is to keep track of it in a bool, such as "foundClass" or "testSucceeded". Default it to false, then set it to true on your break. Enclose any uses of i later in the function in "if (foundClass) { }" blocks.
Another is to just do what you've done. Although your fallback doesn't look right at all. If you're setting i to 15, you're lying to your code and telling it that someClass.Test() succeeded for i == 15, which isn't true. Avoid setting the value to something that's wrong just so your code doesn't error later on. It's much better to put bounds checks around the actual usage of i later in the code.
for(int i=0; i<17; i++)
{
if(i<16)
{
someClass.someMethod(i);
if(someClass.Test())
{
break;
}
}
else if(i==16)
{
i=15;
}
}
if you say you have an array with 16 elements, you don't have to define that, use the array to get that info (DO NOT DUPLICATE INFORMATION)
afterwards if you want to get the last index again use the array to get that info.
for(int i = 0; i < myArray.length; ++i){
myArray[i].somemethod();
}
// lastindex = myArray.length-1;