when i run the following c++ code
#include<iostream>
int main()
{
for(int i=1;i<=10;i++)
{
cout<<i<<endl;
}
cout<<i;
getch();
return 0;
}
I get result from no. 1 to 11.
i don't understand why the value of i = 11 after the block of for loop is finished,Please give me the reason.I have declared i inside for loop and scope of i has been finished after loop so why i get the outpout i=11 after execute second cout statement .I have not declared i in the variable declaration inside main.My question is that is i is visible outside of for loop?
Thanks in advance.
For multiple reasons, this program does not compile. You are either using an extremely old compiler, an extremely permissive compiler, or not showing us the program you're actually having a problem with.
From your comments it seems that you actually can compile it. I can only guess that you are using a very old compiler. Perhaps an old MS-DOS compiler (Zortech C++? Turbo C++?) since the getch function is not generally a standard library function and doesn't do the right thing in the curses library anyway. It's probably an old BIOS-based function from the MS-DOS days.
The standard was changed awhile ago (over 10 years now) so that variable declarations in the parenthesized section of a for loop are local to that loop. It was once not actually the case that this was true.
I no longer have access to any compiler that's so old it doesn't handle things this way. I'm surprised anybody does. Your program will not compile on my compiler.
Here is a version of your program that does compile, even though it requires the -lcurses option to link:
#include <iostream>
#include <curses.h>
using ::std::cout;
using ::std::endl;
int main()
{
for(int i=1;i<=10;i++)
{
cout<<i<<endl;
}
getch();
return 0;
}
Notice how the offending cout << i; statement is gone? That because it will not compile on a modern compiler.
Now, lets edit your program some more so it will compile with the cout << i; statement you're vexed about:
#include <iostream>
#include <curses.h>
int main()
{
using ::std::cout;
int i;
for (i = 1; i <= 10; i++)
{
cout << i << '\n';
}
cout << "last: " << i << '\n';
getch();
return 0;
}
This, of course, does print out last: 11 at the very end. This happens for a very obvious reason. What value does i have to have in order for the i <= 10 test to fail? Why, any value greater than 10! And since i is having one added to it every loop iteration, the first value i has that has the property of being greater than 10 is 11.
The loop test happens at the top of the loop and is used to decide if the remainder of the loop should be executed or not. And the increment happens at the very bottom of the loop (despite appearing in the body of the for statement). So i will be 10, will be printed, and then 1 will be added to it. Then the loop test (i <= 10) will be done, it will be discovered that 11 <= 10 is false, and control will drop out of the loop down to the print statement after the loop, and last: 11 will be printed.
And yes, the exact same thing will happen in C.
Because the loop breaks when the condition i<=10 becomes untrue, and this can happen when i becomes 11. Simple!
I think you wanted to write i < 10 .
Also, as #Omnifarious noted in the comment, the code shouldn't even compile, as i doesn't exist outside the loop. Maybe, you've declared i outside the loop, in your original code?
Besides the fact that it shouldn't compile (because i doesn't exist outside the loop block).
The loop runs from 1 to 10, so it stops when i reaches 11 and the condition fails. So i is 11 in the end of the loop.
This is because you have an old compiler.
cout<<i<<endl; should not compile, as cout and endl need to be qualified by the std namespace.
Fixing that, std::cout<<i; shouldn't compile because your variable is loop-scoped, so shouldn't even be visible outside the loop.
Fixing that, here's your code:
#include<iostream>
#include<conio.h>
int main()
{
int i;
for(i = 1; i <= 10; i++)
{
std::cout << i << std::endl;
}
std::cout << i;
getch();
return 0;
}
It should become more obvious why 11 is printed now.
When i == 10, the loop executes, increments i, and checks its value. It is then equal to 11, so it exits the loop.
Then you have another print statement, that will print the post-loop value, which is 11.
Here's the output I get from that corrected program:
1
2
3
4
5
6
7
8
9
10
11
This is the same as you are getting.
If you only want to print 1-10, then why have the extra std::cout << i;?
Recommendation
Get an up to date C++ compiler that will give you syntax errors on things that are no longer valid in standard-compliant C++
Get rid of the extra std::cout << i;
Keep your i variable loop-scoped, as in your original code
The result from my recommendations will be that you only see 1 through 10 printed, and you will have slightly fewer unexpected surprises in the future (as some "bad" and surprising code won't even compile).
Related
I was writing a code, and accidentally put int before a variable twice, and noticed something different in the end product.
int main ()
{
int number = 123456789;
int step = 0;
while (number>0)
{
cout << number%10 << endl;
number = number/10;
step = step+1;
cout << "step ; " << step << endl;
}
return 0;
}
The output was:
9
step ; 1
8
step ; 2
7
step ; 3
6 ...
However, when I called it this way:
int main ()
{
int number = 123456789;
int step = 0;
while (number>0)
{
cout << number%10 << endl;
number = number/10;
int step = step+1;
cout << "step ; " << step << endl;
}
return 0;
}
The output suddenly changed to:
9
step ; 11006125
8
step ; 11006126
7
step ; 11006127
6
Can someone please explain the difference, so that I will be mindful next time?
C++ is block scoped. When you redeclare step inside the while loop (by using int step instead of just step), you "shadow" the step from outside that scope; while the outer step (with value 0) still exists, it cannot be read directly from the inner scope (a pointer/reference to the outer step with a different name could read/write the data, you just can't read the outer step directly through that name).
The outer step is invisible, so int step = step + 1; translates as "please assign to the local step the value of whatever is already stored in the local step (which, not existing until that moment, has no defined value yet) after adding 1". Since the step it reads from is garbage, this is undefined behavior, and in practice, it gets garbage (whatever junk happened to be left on the stack in that position from before you entered the while).
The second and subsequent creations of the inner step are still undefined behavior, but in this case (and in most cases where loop unrolling isn't involved) the compiler chose to reuse the same storage for them as the prior use of inner step (that expired when that iteration of the loop ended). Thus, as a coincidence of the new inner step reading from the same memory location as the expired inner step, it increments normally from then on, based on the original garbage value as a base.
But again, to be clear, all of this is undefined behavior. Be thankful you didn't get nasal demons, and only use the first form in the future. I'll note, if you enable all warnings, any compiler worth its salt should detect this error (the entire error exists in the scope of a single line); sadly, it appears at least GCC is not worth its salt, because the only thing it detects, even with -Wall -Wextra -Werror -pedantic is that you didn't use the outer step variable. If you used it, or deleted the declaration of the outer step, it compiles with no warnings, so I guess you're stuck just remembering not to initialize a variable in terms of its own value.
In the second case, you declare a second variable, which is also called step, but is visible only inside the loop.
Can anyone explain me the difference in the execution of both of the codes?
1)
#include <iostream>
using namespace std;
int main() {
// your code goes here
string code;
getline(cin,code);
for(int i=0;i<code.length();i++){
if(code[i]=='.'){
code.replace(i,1,"[.]");
}
}
cout<<code;
return 0;
}
The output screen of the above program code shows "time limit exceeded".
Time limit exceeded #stdin #stdout 5s 5220KB
#include <iostream>
using namespace std;
int main() {
// your code goes here
string code;
getline(cin,code);
for(int i=0;i<code.length();i++){
if(code[i]=='.'){
code.replace(i,1,"[.]");
i++;
}
}
cout<<code;
return 0;
}
whereas no.2 code shows the output as desired.
1[.]1[.]1[.]1
Can anyone explain how the execution took in both of the cases that one of the output shows "TLE"(the iteration count has to be declared in the for loop itself) and whereas the other one displays the output?
In this loop:
for(int i=0;i<code.length();i++){
if(code[i]=='.'){
code.replace(i,1,"[.]");
}
}
when you do a replacement of [.], in the next iteration of the loop i is now the index of the . that you just inserted. That . will be replaced again, and so on, infinitely many times, leading to a "time limit exceeded".
In the 2nd version, when a replacement is done, i is correctly being moved to point to the ] instead. You could move it one step further as well, since you know there is no . at that position either.
We can do this and see what happens, for example with this input:
code = "google.com"
After a while, i will be equal to 6, and then it happens:
i code
6 google[.]com (and now there's a dot on place 7)
7 google[[.]]com (and now there's a dot on place 8)
8 google[[[.]]]com (and now there's a dot on place 9)
... ...
And there is no way to stop this.
As the replacement makes the place of the dot shift one to the right, it might be a good idea to have a for-loop in the other sense:
for(int i=code.length()-1;i>=0;i--)
I have recently started learning c++ and I have a question regarding the last section I reached, the while loop one.
In this code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (i <= 5) {
cout << "Hello" << endl;
i = i + 1;
}
return 0;
}
will the while command continue checking if i <=5 after the value goes over 5 or will it stop?
If I was making a program and changed the value of i down the line to one that meets the condition of the loop would it start again or would I have to rewrite the loop code again?
Thanks in advance for the answers!
edit: Thanks for your answers and comments. I tried putting into code what I was thinking and I noticed that changing the value of i after the loop didn't make it start again(meaning that it had already stopped checking after i surpassed 5).
I realize it was a stupid question that I could have simply solved by trying to put it into code, but I still asked for answers just to be sure. Thanks again!
If you changed i to 0 after the loop has ended like this:
int main()
{
int i = 0;
while (i <= 5) {
cout << "Hello" << endl;
i = i + 1;
}
i=0;
return 0;
}
The loop wouldn't start again because it would just set i to 0 and then go to return 0. Once the loop is executed it won't be run again.
Note that C++ executes the code sequentially, this means that its goes through every line, executes it, then goes to the next one. This is confusing for loops because you see previous code being executed again; therefore, to solve this dilemma, think of the loop segment as a block, once this block executes, the normal sequential execution continues.
For Future reference: C++ has a beautiful feature called Multi-threading, where you can allow several code to execute in a parallel fashion. You will meet this feature sometime in the future.
so I'm trying to write a guess the number game in C++.The computer is Supposed to take a random number with 4 digits then the player should enter a number too.Rules are:
if the computer chooses:1234
And the player enters:1356
1 must be displayed in green,3 must in yellow since it's in the wrong place and 5&6 in red.the game goes on till the player gets the right answer.
#include<iostream>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include<unistd.h>
using namespace std;
int main()
{
int b;
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
cout<<"System is now generating a number...."<<"\n";
int *Number = new int[4];
srand (time(NULL));
for(int counter=0;counter<4;)
{
Number[counter]=(rand()%9)+1;
if(Number[counter]!=Number[counter-1]&Number[counter]!=Number[counter-2]
2]&Number[counter]!=Number[counter-3])
{
counter ++;
}
else
{
counter--;
}
}
cout<<Number[0]<<Number[1]<<Number[2]<<Number[3]<<"\n";
int *Guess=new int[4];
cout<<"please enter 4 digits for your number"<<"\n";
for(int counterG=0;counterG<4;counterG++) //line 34
{
cin>>Guess[counterG];
for(int counter;counter<4&counter>0;)
{
if((counter=counterG)&(Guess[counterG]=Number[counter])) //line 40
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,10);
cout<<b<<"\n";
}
if((counter=counterG)&(Guess[counterG]==Number[counter- 1]|Guess[counterG]==Number[counter+1]|Guess[counterG]==Number[counter-2]|Guess[counterG]==Number[counter+2]))
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,14);
cout<<b<<"\n";
}
else
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,12);
cout<<b<<"\n";
}
}
}
now the program is fine until line 34 but nothing happens after that!
It just gets the player digits
I'd be glad if you could tell me what I've done wrong
Not a complete answer, but it's too long for a comment:
if(Number[counter]!=Number[counter-1]&Number[counter]!=Number[counter-2]
2]&Number[counter]!=Number[counter-3])
This line alone contains a lot of errors:
To have the logical AND operator you need &&, not &.
You have typed an extra 2] at the beginning of the second line. I hope it's just a typo that you introduced when writing the question.
The first time you run this, counter is 0. What happens when you try to access Number[counter-3]? It's an out of bounds access, which leads to Undefined Behaviour, which can lead to anything.
And there are probably many more.
What to do now:
Work on your code indentation. It's really bad.
Start from a much simpler program, and verify that it works. Then, add one small step, verify it, and don't move on until you are happy with the result
Turn on your compiler warnings. Warnings are your friends, not a boring annoyance
Learn how to use a debugger. You won't go very far without debugging.
1- replace & with &&(AND operator)
2- take input in a simple integer variable and then validate the number by performing first check of number greater than 0 and less than 9999.
3- then seperate digits from this variable and then assign those digits to aaray indexes respectvely.
I've written a simple code to practice some stuff, but it's not running as it's supposed to.
I'm programming on my iPhone just for fun and l'm using an app called c/c++ offline compiler which seems to work really well.
Anyway, I wrote a program to display numbers, and if the number is less than 5 digits, in each empty space display a star. Then next to that, display the memory address.
There are two questions I have. First, why are the stars not displaying when I run this. Second, each time run it, the memory addresses are different. Is this because of the compiler, or because of how the iPhone's memory works?
Source Code:
//c plus plus program 1
#include <iostream>
using namespace std;
int main (void){
for(int i=0; i<150;i+=30){
cout.width(5);
cout.fill('*');
cout<<i<< "="<<&i <<endl;
}
return 0;
}
It is normal that address of i is changing each time you run your program. As I know it is because of how system works with memory. Why did you think it will place your program in the same part every time? :-)
I tried you code in http://cpp.sh only and stars were shown:
****0=0xffcde9dc
***30=0xffcde9dc
***60=0xffcde9dc
***90=0xffcde9dc
**120=0xffcde9dc
Note, that all after second << was not took into consideration when output width was determined. So first of all to investigate the problem I would try something like
int main (void) {
cout.width(5);
cout.fill('*');
cout << 1 << endl;
cout << 2 << endl;
}
to understand if it compiler problem or not.