Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

is this program in c++ wrong?

–4 votes
asked Nov 2, 2018 by Tessari Elena
Hi,

i was doing an exercise : "write a program in c++ or c, where your output is the biggest number of an array"

then i wrote whis:

#include <iostream>
using namespace std;
int main (){
    int a;
    int b;
    int c;
   cout<<"inserisci lunghezza array"; //put the array length
   cin>>a;
    while(a!=0){
       cout<<"inserisci numero"; //put a number
      
         cin>>b;
         if (b>c) c==b;
         a=a-1;
         
    }
    cout<<c;
    return 0;
            }

//when i compile it the result is always 0. why? please, help me

6 Answers

+1 vote
answered Nov 3, 2018 by khkwa (160 points)

If the length of the array is not zero, you possibly want to have the user key in the first element of the array first (before the while loop), so that it can be compared to the second element to see if you should pick the first element or the second element as a potential candidate for the biggest value and so on.

Also, the line 

if (b>c) c==b;

does not work. If b>c, shouldn't b be chosen as a potential candidate for the biggest value? Not least is that be careful with the distinction between the assignment operator (=) and the relational operator (==).

0 votes
answered Dec 3, 2018 by Kadir (190 points)
you can't use c==b, it is assignment operator. You can use c=b;
0 votes
answered Dec 3, 2018 by femrost
in addition to that sometimes b>c will be false because not assigning anything to c by int c; means that you will have what i call ram trash or just random numbers.
0 votes
answered Mar 4, 2019 by Lokesh Nani (140 points)
using c==b is the mistake,it gives a boolean value checking c is equal to b or not.You have to use c=b for assigning value of c
0 votes
answered Mar 27, 2019 by soumyak subham
#include<iostream.h>

void main()

{    int x[100],n,lar;

cout<<"Insert the array length"<<endl;

cin>>n;

lar=x[0];

for ( int i=0;i<n;i++)

 {   

     if( x[i]>lar)

       lar=x[i];

}

cout<<"The largest no. in the array is "<<lar;

}
+2 votes
answered Nov 4, 2019 by ROSHAN SHANDRES C (250 points)
Before comparing the value of c with b. The variable c must have a value.

Since your source code hasn't assigned a value for variable c, It doesn't process (b>c)command.

try getting a value for c from user before while loop.

Also, to assign value for c use c=b and not c==b.
commented Nov 6, 2019 by SREERENUSANKAR V (230 points)
Yeah, that's right.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...