Wednesday, January 11, 2012

Wednesday 1-11-12

#include

int main (int argc, const char * argv[])
{
int *numbers;
numbers = malloc(sizeof(int) *10);

//create a second variable to always point
//at the beginning of the same memory block
int *numbersStart = numbers;

*numbers = 100;
numbers++;
*numbers = 200;
printf("%i", *numbers);
numbers = numbersStart;
printf("%i", *numbers);
//use the numbersStart variable to free the memory instead
free(numbersStart);
}



int main (int argc, const char * argv[])
{
char *fullname;
asprintf(&fullname, "Albert Einstein");
printf("%s\n", fullname);
free(fullname);

int total = 81;
float ratio = 1.618;

//declare a string pointer and use asprintf() to
//format the string and reserve dynamic memory
char *result;
asprintf(&result, "total: %i, ratio: %f", total, ratio);

//display the 'result' string and free the memory
printf("%s \n", result);
free(result);
myFunction();

return 0;
}




typedef struct {
char *title;
int lengthInSeconds;
int yearRecorded;
} Song;

Song CreateSong(int length, int year);

void displaySong(Song theSong);

int main (int argc, const char * argv[])
{
Song song1;
song1.title = "Hey Jude";
song1.lengthInSeconds = 425;
song1.yearRecorded = 1968;

Song song2;
song2.title = "Let It Be";
song2.lengthInSeconds = 243;
song2.yearRecorded = 1970;

Song mySong1 = CreateSong(324, 2004);
displaySong(mySong1);
return 0;
}

Song CreateSong(int length, int year){
Song mySong;
mySong.lengthInSeconds = length;
mySong.yearRecorded = year;
return mySong;
}

void displaySong (Song theSong){
printf("The song is %i seconds long ", theSong.lengthInSeconds);
printf("and was recorded in %i.\n", theSong.yearRecorded);
}




#include

int main (int argc, const char * argv[])
{
int wholeNumbers[5] = {2, 3, 5, 7, 9};
int theSum = sum(wholeNumbers, 5);
printf("THe sum is: %i ", theSum);

float fractionalNumbers[3] = {16.9, 7.86, 3.4};
float theAverage = average(fractionalNumbers, 3);
printf("and the average is: %f \n", theAverage);
return 0;
}

int sum(int values[], int count)
{
int i;
int total = 0;

for(i = 0; i < count; i++)
{
//add each value in the array to the total
total = total + values[i];
}
return total;
}

float average(float values[], int count)
{
int i;
float total = 0.0;

for(i=0; i < count; i++)
{
//add each value in the array to the total
total = total + values[i];

}
//calculate the average
float average = (total / count);
return average;
}

No comments:

Post a Comment