0

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 :)

IrAM
  • 1,720
  • 5
  • 18
artgoblin
  • 15
  • 3
  • 2
    If you are a "newbie to coding", then the best resource for you how to solve these kinds of simple problems [is a good C++ textbook](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Unfortunately, Stackoverflow is not a replacement for a C++ textbook. Meaningless online quiz sites only result in acquiring bad programming habits, like [bits/stdc++.h](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [using namespace std;](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Sam Varshavchik Oct 19 '20 at 16:33
  • Please intend your code between the `{}`, like GaryNLOL did in his answer. – 12431234123412341234123 Oct 19 '20 at 17:01
  • You should check if the return value of `scanf()` is 1 and not `EOF`. `scanf()` returns `EOF` in case of an error or end of file and `EOF` is true (Because it is not `0`). – 12431234123412341234123 Oct 19 '20 at 17:04
  • 2
    The first program limits the input to 10 inputs. If `42` is the 12th input, that will be wrong anwser. Anyway, it does not output ***any*** answer at all. – Weather Vane Oct 19 '20 at 17:12
  • Have a new array initialised. Put each element into the array until you reach 42 or end of inputs. Sort your new array and print it. – Patrick Oct 19 '20 at 18:27

1 Answers1

4
  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;
}
Gary Strivin'
  • 908
  • 7
  • 20