- 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

26th Oct 2018, 9:16 AM
Yoaraci
Yoaraci - avatar
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);
26th Oct 2018, 10:35 AM
Babak
Babak - avatar
+ 3
Sergey Ushakov Ouch!!! ;)
26th Oct 2018, 12:28 PM
Babak
Babak - avatar
+ 3
Hey Sergey, thanks for noticing. arr_size came to worth after all ! ;P
26th Oct 2018, 12:57 PM
Babak
Babak - avatar
+ 2
C++ Soldier (Babak) You have to check all previous numbers, not only last.
26th Oct 2018, 12:22 PM
Sergey Ushakov
Sergey Ushakov - avatar
+ 1
#include <set> std::set<int> nums; for each new number: if (nums.count(number)) break; else nums.insert(number);
26th Oct 2018, 12:26 PM
Sergey Ushakov
Sergey Ushakov - avatar
+ 1
don’t give full codes as answers, let him learn )
26th Oct 2018, 12:27 PM
Sokrat_Poghosyan
Sokrat_Poghosyan - avatar
0
The simplest way is to use std::set.
26th Oct 2018, 9:29 AM
Sergey Ushakov
Sergey Ushakov - avatar
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*
26th Oct 2018, 10:38 AM
Sokrat_Poghosyan
Sokrat_Poghosyan - avatar
- 1
sorry, can you give the example of using std::set? because i never use it before😅
26th Oct 2018, 10:15 AM
Yoaraci
Yoaraci - avatar