Using Arrays in C++

Find a max in an array using dynamic dimension


Category: C++ Programming Tags: C++ Programming

        Last month I had  to create an example on array in C++ for my students; so I had an example on my study backgrond but I have to find the dynamic length of array not fixed before and know before; so the step was
  • Create the array, simple, example:          int a[] = {1, 20, 4, 8, 9, 12};
  • Find the lenght, it is the same method used in C also, I used:   int n = sizeof(a)/sizeof(a[0]);
find total bytes of array and divide for the bytes of a single element so we find the number of elements, so now we can go through the array and find our max, set the first max as the 1st element of array and then go through the array and set It.
/* 
 * File:   main.cpp
 * Author: ale
 *
 * Created on 22 ottobre 2013, 16.47
 */

#include <cstdlib>
#include <iostream>

using namespace std;

/*
 *
 */
int main(int argc, char** argv) {

    int a[] = {1, 20, 4, 8, 9, 12};
    int max = a[0];
    int n = sizeof(a)/sizeof(a[0]);
   
    for(int i=0; i<n; i++)
     {
       if(a[i]>max)
         {
           max = a[i];
           } 
        }
     cout<< max;
      }

Like 1 Person
Published on 10 December 2013
alex

alex
Atricles: 2
Questions: 0
Given Best Solutions: 0 *

Reference:


Comments:

Nikhil Joshi
Thanks @alex for this nice article....
Like 3 People on 23 December 2013

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x