-2

so I was searching about a program that prints out the non repeated numbers in an array, the program is completely fine but I can't understand what exactly happens in the break statement part so can someone please explains what happens because I can't get it, here is the code down below.

#include<stdio.h>
int main(void){

int n;
printf("enter a value for n: ");
scanf("%d",&n);
int T[n];
int j;  
printf("fill in the array: \n");
for(int i=0 ; i<n ; i++)
{
    printf("enter value %d: ",i+1);
    scanf("%d",&T[i]);
}   
for(int i=0 ; i<n ; i++)
{
    printf("%d ",T[i]);
}


//---------------------------------------------------------------------//

        
printf("the non repeated elements are: \n");
for(int i=0 ; i<n ; i++)
{
    for( j=0 ; j<n ; j++)
    {
        if(T[i]==T[j] && i!=j)
        {
            break;
        }
            
            
    }
    if(j==n)
    {       
    printf("%d ",T[i]);         
    }
}   
return 0;
}
  • 1
    Does this answer your question? [When to use break, and continue in C language?](https://stackoverflow.com/questions/40080092/when-to-use-break-and-continue-in-c-language) – rsjaffe Mar 29 '21 at 18:15
  • ⟼Remember, it's always important, *especially* when learning and asking questions on Stack Overflow, to keep your code as organized as possible. [Consistent indentation](https://en.wikipedia.org/wiki/Indentation_style) helps communicate structure and, importantly, intent, which helps us navigate quickly to the root of the problem without spending a lot of time trying to decode what's going on. – tadman Mar 29 '21 at 18:50

1 Answers1

1

The inner loop for( j=0 ; j<n ; j++) goes over all elements of the array (except the ith element), and check if they contain the same value as that of the ith element. If it does, it stops the loop before j gets to n (break means: stop the loop immediately). I.e. if j == n after the loop, it means that no such element was found (no j != i such that T[i] == T[j]), hence we print it.

The inner loop could have been written as follows and it would have been equivalent:

for( j = 0 ; j < n && (T[i] != T[j] || i == j) ; j++)
{
    // empty
}

And the outer loop for(int i=0 ; i<n ; i++) does this for every element (every index i) in the array T.

Orielno
  • 409
  • 2
  • 8