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;
}
Comments: