where to put while loop

this is my little problem. i have a add element exercise which is to add element in the last row and i decided to put a condition where if the element is already existing, prompt user to input different element. my first approach is replace line 17 with while(add==a[i]){ but if i input 2 and then 3 it will prompt me that it already exist and then 2 again, it will accept it. i asked someone and they said that i should use if conndition not while and add i=-1 after line 19. the problem is i dont understand its purpose. is it right?

what is the proper way to add loop in line 16 in case there is already existing element?


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
26
27
28
29
30
  #include<iostream>
using namespace std;

int main(){
	
	int a[4] = {2,2,3,3};
	int add,i;
	
	for(i = 0; i<4; i++){
		cout<<a[i] <<" ";
	}
	
	cout<<"\nAdd element: ";
	cin>>add;
	
	for(i = 0 ; i<4; i++){
        if(add==a[i]){
        cout<<"Element already exist, choose another integer : ";
    	cin>>add;
        }
    }			
	a[4] = add; //put add in last 

	cout<<"Add success! new array is" <<endl;
	
		for(i = 0; i<=4; i++){
			cout<<a[i] <<" ";
		}

}
Last edited on
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

int main() {

    // http://en.cppreference.com/w/cpp/types/size_t
    // note: we need to create an array with space for the element to be added
    const std::size_t ARRAY_SIZE = 5 ;

    int a[ARRAY_SIZE] = { 2, 2, 3, 3 }; // 2, 2, 3, 3, 0

    // current size is one less than the physical size of thew array
    // we want to add a new element at the end, as he last element
    std::size_t curr_sz = ARRAY_SIZE - 1 ; // logical size

    for( std::size_t i = 0; i<curr_sz; ++i ) std::cout << a[i] << ' ' ;

    std::cout<<"\nAdd a last element: ";

    int new_value ;
    bool already_exist ;

    do {

        std::cin >> new_value ;

        already_exist = false ;
        for( std::size_t i = 0; i<curr_sz; ++i )
        if( a[i] == new_value ) already_exist = true ;

        if(already_exist) std::cout << "Element already exist, choose another integer : ";
    }
    while(already_exist) ;

    a[curr_sz] = new_value ; // add the new value at the end
    ++curr_sz ; // the logical size is now one greater than what it was

    std::cout << "Add success! new array is\n" ;
    for( std::size_t i = 0; i<curr_sz; ++i ) std::cout << a[i] << ' ' ;
    std::cout << '\n' ;
}
Hello newguy17,

The for loop at line 16 is the right idea, but the wrong implementation. After entering into "add" you want to check each element of the array to see if it is a duplicate before you enter a new number. At least that is the idea I get.

I would refer to JLBorges's example for some ideas.

As a note arrays, vectors, lists, maps and any others are zero based meaning they start their indexing at zero not one. this means line 22 is trying to store a value at element 4 which is beyond the bounds of the array which goes from zero '0' to three '3'. There for the program will crash while trying to execute this line.

What you have for thee for loop at line 16 is fixable I just have not worked on it yet.

As JLBorges pointed out you may want to make array "a" larger than 4 in order to hold new numbers.

Hope that helps,

Andy
thank you @jlBorges and andy. i just thought that it will be ok since i adjust the array in line 26 for(i = 0; i<=4; i++) and it will be able to hold the add value. i always do this when im adding and inserting elements in array and sometimes it is working just fine
i never thought that sometimes it will give unexpected behavior. thanks again
Hello newguy17,

Here is an idea trying to work with what you have done:

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
26
27
28
29
30
31
constexpr std::size_t MAXSIZE{ 10 };
int a[MAXSIZE] = { 2,2,3,3 };
std::size_t index{ 4 };  // <--- Because you start with 4 elements used in the array and element 4 is next.
bool exist{ false };

do
{
	for (i = 0; i < index; i++)  // <---  Only checks the part of the array used.
	{
		if (add == a[i] && !exist)
		{
			std::cout << "Element already exist, choose another integer : " << std::endl;
			exist = true;  // <--- Defined as a bool.
		}
	}

	if (exist)
	{
		std::cout << "\nEnter another number that is not " << add << ": ";
		std::cin >> add;
		exist = false;
	}
	else
		break;

} while (!exist);

if (index < MAXSIZE)
	a[index++] = add;
else
	std::cout << "Error message for exceeding the size of the array. Your choice." << std::endl;


Lines 1 - 4 I normally put at the beginning of a function so I know where to find them.
Line 2 is here more for reference.
Line 3 I added and defines "index" with a value of 4 because 4 is the next element of the array to store something.
Line 4 I added to use in the do/while loop.

The do/while loop continues until you enter a number that does not already exist.

The for loop will check each element of the part array that is used .

The if statement will only print the message once even if there is more than one match.

The second if statement allows you to enter a new number if the first number exists in the array. Setting "exist" back to false allows the do while loop to check the new number.

The else statement is reached when "add" does not match anything in the array.

I started with just line 29 then added the if/else to make sure "index" does not go past the end of the array. The use of line 29 is to add after the used portion of the array and then add 1 to "index" before printing out the new array and ending the program.

A do while loop around most of your code would allow you to add more than one element to the array. This is an idea of what I usually do in this case:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <cctype>  // <--- For the touppet, tolower and others.

int main()
{
	char choice{};
	bool cont{ true };

	do
	{
		// Your code here.

		std::cout << "\n Do another Y/N: ";
		std::cin >> choice;
		choice = std::toupper(choice);

		if (choice != 'Y')
			cont = false;
	} while (cont);
}


All this can be added to what you already have.

Hope that helps,

Andy
@andy thanks again andy this is very helpful and informative.
Hello newguy17,

Just so you understand this:
i just thought that it will be ok since i adjust the array in line 26


At line 6 you define the array to be a size of 4. This is a fixed size through out the program and never changes. When the program runs space is set aside on the stack for this array. After that there is no room to change the size of the array. Line 26 nor any other line of the program will change the size of the array.

Line 26 the for loop does not extend the array it just tries to read whatever is past the end of the array the size of an "int" in length.

Hope that helps,

Andy
Topic archived. No new replies allowed.