Search code examples
c++ccppcheck

Sphere online judge ( Life, the Universe, and Everything )


Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.

Input: 1 2 88 42 99

Output: 1 2 88

I tried to solve this programme with the help of c++ and end up getting wrong result.

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int i,n;

    for(i=0;i<10;i++)
    {
        cin>>n;
        if(n == 42)
            break;
    }
    return 0;
}

Then with the help of C I solved the problem and it came out like this:

#include <stdio.h>

int main(void)
{
    int i = 0;

    while (scanf("%d\n", &i) && i != 42)
    {
        printf("%d\n", i);
    }
    return 0;
}

can you tell me what were my mistakes that i was making in the first programme. I am newbie to coding. Thanks in advance :)


Solution

    1. It's a bad practice to use #include <bits/stdc++.h> (More information here).
    2. It's a bad practice to use using namespace std; (More information here).
    3. You aren't printing anything. Use std::cout.
    4. For the readability of the code you should declare i in the for loop statement.
    5. I agree with Sam Varshavchik. If you want to learn C++, search a good textbook instead of online quiz sites.
    #include <iostream>
    
    int main()
    {
       int n;
       for(int i = 0; i < 10; i++)
       {
             std::cin >> n;
             if(n == 42)
                break;
             std::cout << n;
       }
       return 0;
    }