- 1
how to make loop stop when its find the same number
example input 1 5 // the first 5 7 3 6 5 // 5 already inputed before so print only until this 9// dont print this number 2// dont print this number output 1 5 7 3 6 5
9 Antworten
+ 6
Sergey Ushakov really?! ;)
Yoaraci
From an already populated container vs. from user's input
(which one?)
1. Container example using array (unsorted)
int num_arr[] = {1, 5, 7, 3, 6, 5, 9, 2};
size_t arr_size = sizeof(num_arr)/sizeof(num_arr[0]);
// int last_item = num_arr[arr_size]; // 2 -- chances are the last item is 1 too, and then the following loop breaks immediately after printing the first item
sort(num_arr, num_arr + arr_size);// include <algorithm>
int last_item = num_arr[1]; // much better!
for (const auto &n : num_arr) {
cout << n << endl;
if (n == last_item) break;
else last_item = n;
}
2. User's input (whiteout type checking)
int num = 0;
int last_num = 0;
cin >> num; // get the first number
cout << num << endl;
last_num = num;
do {
cin >> num;
cout << num << endl;
if (num == last_num) break;
else last_num = num;
} while (true);
+ 3
Sergey Ushakov Ouch!!! ;)
+ 3
Hey Sergey, thanks for noticing. arr_size came to worth after all ! ;P
+ 2
C++ Soldier (Babak) You have to check all previous numbers, not only last.
+ 1
#include <set>
std::set<int> nums;
for each new number:
if (nums.count(number))
break;
else
nums.insert(number);
+ 1
don’t give full codes as answers, let him learn )
0
The simplest way is to use std::set.
0
create an array of numbers and push every inputed number to the array, check every input with for loop, if it matches any item stop loop.
You need to know do while, for loops, array and dynamic allocation*
- 1
sorry, can you give the example of using std::set? because i never use it before😅