Some fast steps ... into arrays of char's and int's and doubles ... in C ... pointing out, in the comments, some things to note ... so please run these programs ... and note ...
And again ... see if you can re-code these in C++ ... for some easy practice ...
NOTE:
C strings are just 'null terminated' arrays of char's ... and arrays are just blocks of memory to hold (normally) adjacent data, one after the other, in equal chunks of memory, for each element ... For example, a 'char' takes 1 byte ( 8 bits) ... and at present, 2008-2009, an 'int' is usually 4 bytes, i.e. 32 bits. In a 32 bit addressing mode system, pointers, ( i.e. variables that hold addresses ), will use 32 bits of memory ... 4 bytes.
NOTE 2: If you want to jump now to see a C++ student array type problem, solved step by step, click on this next link now ...
http://developers-heaven.net/forum/index.php/topic,106.15.html#include <stdio.h>
int main ()
{
/* a NULL terminated array of characters, i.e. a 'C string' */
char book[] = "It was a dark and stormy night."; /* compiler adds 0 at end */
char test1[]= { 'a', 'b', 'c','\0'};/*NOTE: last '0' if want C string */
char test2[4] ={'X','Y','Z'};/* NOTE: reserve a 4th spot for '0' */
/* now ... */
test2[3] =0; /* null terminate ... to convert array to C string */
char letter = book[3]; /* 'w' = book[3] i.e. w is the 4th char in the string */
/* an array of integers */
int coin[] = {1, 2, 5, 10, 20, 50, 100, 200}; /* compiler COUNTS int's */
/* an empty array to hold two int */
int cost[2];
/* set values ... */
cost[0] = coin[2]; /* 5 = coin[2] ... i.e. the 3rd position coin ... */
cost[1] = coin[4]; /* 20 = coin[4] ... i.e. the 5th position coin ... */
printf("Item %i costs %3i cents.\n", 1, cost[0]);
printf("Item %d costs %3d cents.\n", 2, cost[1]);
printf("book = %s\n", book );
printf("4th letter in book at index=3 is %c\n", letter);
printf("5th letter in book at index=4 is %c\n", book[4]);
printf("1st letter in book at index=0 is %c\n", book[0]);
printf("Some test C strings 1:%s 2:%s ", test1, test2);
getchar(); /* to hold window open until 'Enter' key pressed ... */
return 0;
}
Passing (simple 1-D) arrays to functions ... (note: in C/C++ arrays are
always automatically passed by reference)
#include <stdio.h>
/*
Calling a function ... 'show' array ... via passing a simple 1-D array of 'int' ...
Note: the C / C++ (compiler) automatically take/pass the address, so NO copy
is made ... (but, a local copy of the ADDRESS is made ... that holds/points to the
original object. Using the address (pointing to the array) ... we are working on the
original array itself ... so any changes made to values in the array, inside a
function ... are changes made to the array itself.
*/
void show( int a[], int num ) /* or ... // void show( int * a, int num ) */
{
int i;
for (i=0; i<num; ++i)
printf("%d ", a[i]);
puts( "" );
a[0] = -1*a[0]; /* Note how we can flip / flop the values here ... each pass ...*/
for (i=0; i<num; ++i)
printf("%d ", *a++); /* same output as above ... */
}
int main()
{
int myAry[] = {1,2,3,4,5};
show( myAry, 5 );
myAry[0] = -2*myAry[0];
puts("\nOr ...");
show( myAry, sizeof myAry / sizeof myAry[0] );
printf("Press 'Enter' to continue ... ");
getchar();
return 0;
}
Lot's of things/tricks to note here ... jumping right into addressing ... (i.e. using pointers to hold the address of the start of blocks of new memory obtained by
malloc or
calloc or
realloc in C ... and by
new in C++)
/*
C program to find ... the maximum, the minimum and the average values of ...
an array of numbers entered via the keyboard ... using a DYNAMIC ARRAY of doubles
*/
#include <stdio.h>
#include <stdlib.h>
void getAryInfo(double* ary, int size, double* max, double* min, double* avg);
int main()
{
double* ary; /* this is a pointer ... i.e. ary holds an address */
int c, i, n;
/* get variables to hold info ... note: values to be returned by 'ref' */
double max, min, avg;
/* get n ... */
do
{
n = 0;
printf( "Please enter the number of observations : " );
scanf( "%d", &n );
while( getchar() != '\n' ); /* flush stdin ... */
if( n <= 0 ) printf("Please enter a number greater than 0 ...\n");
}while( n <= 0 );
/* now get a block of memory for the array of n doubles */
ary = (double*) malloc(n * sizeof(double));
if( ary == NULL )
{ fputs("Error: malloc failed to allocate memory.", stderr); exit(1); }
/*
ary now holds the address of the start of memory
just allocated to hold n 'doubles'
*/
/* now ... get the numbers into the 'ary' array memory reserved above ... */
for( i=0; i<n; ++i )
{
printf( "observation %-3d : ", i+1 );
ary[i] = 0;
scanf( "%lf", &ary[i] ); /* Note: 'lf' for correct input of doubles */
while( getchar() != '\n' ); /* flush all chars in stdin stream */ ;
if( ary[i] == 0 )
{
printf("Is this value %lf correct that you entered (y/n) ? :", ary[i]);
c = getchar();
if( !(c == 'y' || c =='Y') )
{
printf("Ok ... skipped ...\n");
--i;
while( c != '\n' ) c=getchar(); /* flush all chars in stdin stream */ ;
continue;
}
while( c != '\n' ) c=getchar(); /* flush all chars in stdin stream */ ;
}
}
/* show numbers in the array ... */
printf( "\nYou entered ...\n\n" );
for( i=0; i<n; ++i )
{
printf( "%-3d : ", i+1 );
printf( "%g\n", ary[i] );
}
/* Note: ary below already holds an 'address' to the first 'double' in the array of doubles */
getAryInfo( ary, n, &max, &min, &avg ); /* we pass 'addresses' to pointer variables */
printf( "\nThe info you desired is ... \n\n" );
printf( "Max: %g Min: %g Average: %g\n\n", max, min, avg );
printf("Press 'Enter' to continue ... ");
getchar();
free( ary ); /* free the dynamic memory allocated for the array of n doubles */
return 0;
}
/* Note .... We are catching 'addresses' .... */
/* so inside ... we have to use the value at that address by using *var */
void getAryInfo(double* ary, int size, double* max, double* min, double* avg)
{
double sum = *min = *max = ary[0]; /* use this as a 'opening' value .... */
int i;
for( i=1; i<size; ++i ) /* start at 1 since already used 0 above */
{
sum += ary[i]; /* sum = sum + ary[i] */
if (ary[i] < *min) *min = ary[i]; /* update ... if applies */
if (ary[i] > *max) *max = ary[i];
}
/* when we reach ... we have max, min and sum ... So can find average */
*avg = sum/size;
}
And here is a mini-tutorial on a common student problem, finding if a particular element exits in an array of elements ... here we are looking for a C++ string in an array of C++ strings and will return the index of that string, in the array, if it is found, ... otherwise ... -1 is returned
http://www.dreamincode.net/forums/showtopic99556.htmA student presents (problematic) code like this:
int search_name(const string find_name[], const string in_name, const int size1)
{
int index = 0, not_found = -1;
while (in_name != find_name[index] && index <= size1)
index++;
if (in_name != find_name[index] && index > size1)
return not_found;
else
return index;
}
A first fix suggested ... is this:
int search_name(const string find_name[], const string in_name, const int size1)
{
for( int i=0; i<size1; ++i )
if( in_name == find_name[i] )
return i;
return -1;
}
Do you recognize yet ... what is trying to be accomplished by this function ... ?
See if this following re-worked version makes it clearer to see what the function does ...?
// test if the C++ string 'name' is in the array of strings with 'ary_size' number of names
// return the index 'i' in the array, if found ... i is in the range 0..ary_size-1
// otherwise, return -1
int get_index(const string& name, const string name_ary[], const int ary_size )
{
for( int i = 0; i < ary_size; ++i )
{
if( name == name_ary[i] )
{
return i; // found ... so return the index where it was found
}
}
// else ... if reach here ... NOT found, so ...
return -1;
}
Now see this ...
Re. some recommendations for student hand-ins ... for top marks:
* included appropriate comments with functions re. what is passed in and back ...
and ... what the function does, if the function name is not self explanatory
* use brackets for each block of code in if(...){ ...;}else if(...){ ...;}else{...;}
(Some schools insist on this ... others just insist on clarity of logic flow.)
* rather than passing a copy, by value, into a function, where appropriate,
pass in by const reference, especially for large C++ obj's
* use as descriptive names as possible to help
see the program logic flow
and to self-document, as you go, what is happening
there ...