am i right?

guyz firstly , i am a noob.. its been only a week since i started learnin c++ and c.
i got a task to produce an output of
1
22
333
4444

with loops..
i used this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream.h>
int main()
{
int a, b;
for(a=1;(a==1);++a)
cout<<"1\n";


for(b=1;(b<=2);++b)
cout<<"2";
for(a=1;(a<2);++a)
{
cout<<"\n";
for(b=1;(b<=3);++b)
cout<<"3";
}
for(a=1;(a<2);++a)
{
cout<<"\n";
for(b=1;(b<=4);++b)
cout<<"4";
}
system("pause");
return 0;
}

do you think that it has any type of contradiction?

thank you
I don't know what you mean by "contradiction," but it could definitely be written more concisely.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
int main()
{
    for ( int i=1; i <= 4;  ++i )
    {
        for ( int j=0 ; j<i; ++j )
            std::cout << i ;

        std::cout << '\n' ;
    }
}
Last edited on
alright, thanxx 4 dat.
i meant that will my code serve the purpose?
i mean the teacher will gimme full marks , isnt it?? :p
Your program is fundamentally correct, but it could be written in a much better way, like cire's. But I suppose that might be confusing if you started only a week ago.

One thing you can remove are the parenthesis from the condition in the for statements. For this kind of condition you don't need them
Also, since you know beforehand that some loops will be executed only once, like
1
2
3
4
5
6
for(a=1;(a<2);++a) // will be executed only once
{
cout<<"\n";
for(b=1;(b<=3);++b)
cout<<"3";
}

You can remove them

You mark will depend on if the teacher just cares that the output is correct
Last edited on
thank you guys.
One of the concepts in programming is to recognise patterns and sequences.
In the required output, the pattern is quite clear to see, even at a glance, though it may become clearer after a little more thought.

Now consider your code, that too has a pattern:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream.h>
int main()
{
int a, b;
for(a=1;(a==1);++a)
cout<<"1\n";


for(b=1;(b<=2);++b)
cout<<"2";
for(a=1;(a<2);++a)
{
cout<<"\n";
for(b=1;(b<=3);++b)
cout<<"3";
}
for(a=1;(a<2);++a)
{
cout<<"\n";
for(b=1;(b<=4);++b)
cout<<"4";
}
system("pause");
return 0;
}


The fact that there is in the series of loops a value steadily increasing from 1 to 4 is a good hint that there could have been a solution which uses that fact.
Topic archived. No new replies allowed.