My If Else statement is not working to provide maximum value in a vector (C++)

c++ vector max element index
vector max c++
if else statement in c example
if else statement in c++ example program
r if statement multiple conditions
if else statement in r
max element in 2d vector c++
if else in r data frame

I am trying to return the max. value in a vector in C++, but I am constantly getting only the last value as the response (I am guessing it is because the if-else loop is somehow not doing the comparison and is just assigning the next value to "maxVal"). For example, the below code is returning 30 as the answer. What am I doing wrong? Can you please help?

Below is the code ->

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

double max (const vector<double>& myVector)   {
int n = myVector.size();
double maxVal;
for (int i=0; i<=n-1; i++) {
    if (maxVal <= myVector[i+1])  {
        maxVal = myVector[i+1];   
    }
    else {
        maxVal = myVector[i];
    }

}
return maxVal; 
}

int main() {
vector<double> testVector;
testVector.push_back(10.0);
testVector.push_back(200.0);
testVector.push_back(30.0);
cout << max(testVector);
return 0;

}

C++ has a rich library and I don't understand why people don't use it. Here is a two line version that finds the maximum value of a vector. Please, don't reinvent the wheel.

#include <iostream>                                                                                                                                                                                                
#include <vector>                                                                                                                                                                                                  
#include <algorithm>                                                                                                                                                                                                

int main()                                                                                                                                                                                                         
{                                                                                                                                                                                                                  
  auto v = std::vector{4, 3, 2, 1};                                                                                                                                                                               
  std::cout << *max_element(v.cbegin(), v.cend()) << "\n";                                                                                                                                                         
}                                                                                                                                                                                                                  

How can I get the max (or min) value in a vector?, auto it = max_element(std::begin(cloud), std::end(cloud)); // c++11. Otherwise If the vector is not sorted then you have to iterate over the vector to get the smallest/​largest element.In this So as per the problem you can get the maximum element in an vector as: It will give you the maximum element in your vector "​cloud". As soon as a test expression is true, the code inside of that if ( or else if ) block is executed. Then the control jumps out of the ifelse if block. If none of the expression is true, the code inside the else block is executed. Alternatively, we can use switch statement in such condition.


(I assume that the vector is not empty)

This work:

double max(const std::vector<double>& myVector)
{
    size_t n = myVector.size();
    double maxVal = myVector[0];

    for (size_t i = 0; i < n; i++)
    {
        if (myVector[i] > maxVal)
            maxVal = myVector[i];
    }

    return maxVal;
}

int main()
{
    std::vector<double> testVector{ 10.0 , 200.0 , 30.0 };

    std::cout << max(testVector);

    return 0;
}

Keep it simple & readable: Initialize the maxVal with the 1st element of the vector, Run on all elements, & if one is bigger than maxVal, update maxVal.

How to find max value of three varibles using if,else,end., Learn more about if statement, compare 3 varibles with if statements if a>b && a>c You would be able to make the variable "data" listed here as a vector of  When your compiler give you a warning that a path does not returns a value, fix it when it is obvious that the code is wrong! – Phil1970 Sep 26 at 3:52 Hey Phil1970, sorry what do you mean by the "path does not returns a value"? – john_w Sep 26 at 3:53


Make things easy on yourself, use the standard algorithms.

See https://en.cppreference.com/w/cpp/algorithm/max_element

How to Use If-Else Statements and Loops in R – Dataquest, Learn to use if-else statements, for loops, and while loops to build complex conditional programs in “If I'm not home by eight, make yourself dinner.” It worked! Because Team A had more goals than Team B, our conditional statement( For example, this could be a vector of numbers c(1,2,3,4,5). value: This is an iterator  So, the first value of the result is the first value of the second argument, which is 1. The next value is FALSE, because 3 is larger than 2.5. Hence, ifelse() takes the second value of the third argument (which is 4) as the second value of the result. A vector with the selected values is returned as the result. Try it out


Here

for (int i=0; i<=n-1; i++) {
    if (maxVal <= myVector[i+1])  {
        maxVal = myVector[i+1];   
    }
    else {
        maxVal = myVector[i];
    }
}

you change the value of maxVal on every iteration. In the end maxVal can only be either the value of the last element or an elements one past your array. Which brings me to the next problem: Valid indicees are 0 up to (including) n-1, so when you are at i==n-1 then i+1 is out of your array.

Actaully there is no need to consider the next or previous element so change it to

for (int i=0; i<n; i++) {        // loop from 0 till n-1 
    if (maxVal < myVector[i]) {  // no need to check equality
        maxVal = myVector[i];   
    }                            // no need for else
}                                // if maxVal is bigger then it 
                                 // is already the max so far

Decision Making in C / C++ (if , if..else, Nested if, if , C if statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. If we do not provide the curly braces  x = 42; if exist ( 'myfunction.m', 'file') && (myfunction (x) >= pi) disp ( 'Expressions are true' ) end. The first part of the expression evaluates to false. Therefore, MATLAB does not need to evaluate the second part of the expression, which would result in an undefined function error.


Control Structures in R: Using If-Else Statements and Loops, Control structures allow you to specify the execution of your code. Control Structures in R: Using If-Else Statements and Loops As a result, if we ran our, expression the R interpreter would not return anything: For example, this could be a vector of numbers c(1,2,3,4,5) . value: This is an iterator variable you use to refer  In C++, there are two statements break; and continue; specifically to alter the normal flow of a program. Sometimes, it is desirable to skip the execution of a loop for a certain test condition or terminate it immediately without checking the condition. For example: You want to loop through data of all aged people except people aged 65.


Mutate and ifelse() fail upon NA comparison and is grouping , I've encountered an issue trying to select the maximum value of a column and mutating that column with NAs present. x <- rep(c("Bob", "Jane"), each Sign in to your account Error: incompatible types, expecting a logical vector a problem using mutate, ifelse, groups and NA in the ifelse conditional. Here’s a flow chart representation, and the syntax in R (which looks very similar to the if syntax). In this diagram, for each value in the sequence, the loop will execute the code block. When there are no more values left in the sequence, this will return FALSE and exit the loop. Let’s break down what’s going on here.


C Basics - C Programming Tutorial, Comments are used to document and explain your codes and program logic. Comments are not programming statements and are ignored by the compiler, could comment-out these statements so that you could get them back later, if needed. <stdio.h> #include <limits.h> // integer limits int main() { printf("int max = %d\n"  if-else-if ladder in C/C++. Here, a user can decide among multiple options. The C if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed.