Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

code returning 0 before for loop (c++)

+2 votes
asked Oct 12, 2020 by Ike Roland (320 points)
i am makeing a code that will list the perfect squares between two numbers but when ever i put the line of code in (after the backslashes)it doen't print the for loop but if i take the code out it works please help

#include <iostream>
using namespace std;

int main()
{
    int limit;
    cout<<"the perfect squares are bettween 1-______?\n";
    cin>>limit;
    //cout<<"1-"<<limit<<"\n"; <------line i am trying to put in
    int square;
    for(int number = 1 ; square < limit ; number++)
    {
        square=number * number;
        cout<<square<<"-";
    }
}

4 Answers

0 votes
answered Oct 12, 2020 by SHYAM SHANKAR V (140 points)
#include <iostream>
using namespace std;
int main()
{
    int limit,square;
    cout<<"Enter the limit\n";
    cin>>limit;
    cout<<"The squares between 1 and "<<limit<<" are : \n";
    for(int i=1;i < limit ; i++)
    {
        square=i*i ;
        cout<<square<<" ";
    }
return 0;
}
0 votes
answered Oct 12, 2020 by Ron McCloskey (220 points)

//cout<<"1-"<<limit<<"\n"; <------line i am trying to put in

cout<<"1-"<<limit<<'\n'; //remember \n is a character not a string

or

cout<<"1-"<<limit<<endl;

I would also change: 

int square; -----> int square=0; //gets rid of any inadvertent stuff in memory

0 votes
answered Oct 13, 2020 by Umar Azam Shahid (150 points)

try this. (in C++, always initialize your variables with some value, don't leave them hanging.)

int main()
{
    int limit = 0;
    cout<<"the perfect squares are bettween 1-______?\n";
    cin>>limit;
    cout<<"1-"<<limit<<endl; //<------line i am trying to put in
    int square = 0;
    for(int number = 1 ; square < limit ; number++)
    {
        square=number * number;
        cout<<square<<"-";
    }
}

0 votes
answered Oct 13, 2020 by Peter Minarik (84,720 points)
I uncommented the commented out line (and commented out the "<------ [...]" part of course) and the code runs for me.

I don't see why the for loop wouldn't run for you.

Note: the program doesn't work correctly, it prints squares over the limit. Nevertheless, the problem you described doesn't seem to happen for me.

Also, please note that you put the "C" tag on the question. This is "C++" code. ;)
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...