2016-01-13 22 views
-1

我爲大小6的陣列的第一個元素被複制到變量與陣列多數元素。這將是非常有益的,如果有人可以指出

#include <stdio.h> 

int main() 
{ 
    int arr[6],i,j,k,count=0; 
    printf("enter the nos"); 
    for(i=0;i<=5;i++)   //loop to accept values from the user 
    { 
     scanf("%d",&arr[i]); 
    } 
    for(i=0;i<=5;i++) 
    { 
    arr[i]=j;    //the 1st element is assigned to j 
     for(k=0;k<=5;k++) 
     { 
      if(arr[k]==j) 
      { 
       count++; //whenever the required element is found in the array count is increased 
      } 
     } 
     if(count>=3) 
     { 
      printf("the majority elt is %d",j); 
     } 
     else 
     { 
      count=0; //if above conditions dont satisfy the count is again set to 0 
     } 
    //the inner loop after completing its iterations gives control to the outer loop 
    } 
} 
+1

您的變量'j'從未初始化。 – Rabbid76

+1

你顯示的代碼有什麼問題?你的問題是什麼?請[閱讀關於如何提出好問題](http://stackoverflow.com/help/how-to-ask)。 –

回答

1

的其他元件相匹配的變量只提供的故障如果你想分配一個元素j如您在您的評論的意思是:

//第一個元素被分配到j

,你必須把它寫這樣這個:j = arr[i];

除此之外,你可以停止搜索,如果你發現大多數。像這樣調整您的代碼:

for(i=0;i<=5;i++) 
{ 
    j = arr[i]; 
    for(k=0;k<=5;k++) 
    { 
     if(arr[k]==j) 
      count++; //whenever the required element is found in the array count is increased 
    } 
    if(count>=3) 
    { 
     printf("the majority elt is %d",j); 
     break; // <- you are finished 
    } 
    else 
    count = 0; 
} 
+0

感謝它的工作。 – avinoor

+0

問題是,如果我輸入1 2 1 3 1 3 – avinoor

+0

輸出不正確 – avinoor

相關問題