Code Examples, CS 102 - Final Exam

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Convert temperature function

#include <stdio.h> double convert(double temp_c) { double temp_f = 0.0; temp_f = (9.0/5.0)* temp_c + 32.0; printf("MARK: In convert function...\n"); return temp_f; }

while_grade_avg.c

#include <stdio.h> #include <stdlib.h> #include <math.h> void main(void) { int product; int num_of_iteration; product = 3; num_of_iteration = 0; printf("The initialized product is %d\n", product); while (product<= 100) { product = product * 3; num_of_iteration = num_of_iteration + 1; printf("In the %d iteration, product = %d\n", num_of_iteration, product); } printf("\n\n\n"); system("pause"); }

declare a pointer to the file in order to output to a file

FILE *outfile;

Close the file

fclose(outfile);

"Generate a random number between 50 and 100"

random_number = rand() % 100 + 50

initialize function

void initialize(int a[][COLS]) { int i, j; for(i=0; i<ROWS; i++) { for(j=0; j<COLS; j++) { a[i][j]=rand()%999;

Writing to a file

void main(void) { FILE *outfile; // You must declare a file pointer outfile=fopen("Hello.txt", "w"); // use fopen to open the file. The "w" flag indicates the file is open for write. printf("The file is now open.\n"); fprintf(outfile, "Hello World!\n"); // Use fprintf to write output to the file. fclose(outfile); // close the file }

Specifying an Array's size with a symbolic constant and initializing array elements with calculators.

#define SIZE 5 int main(void) { int j: int n[SIZE]; for (j=0; j<SIZE; j++) { n[j]=2+2*j; } }

BMI function

#include <math.h> float bmi(unsigned int feet, unsigned int inches, float weight) { float body_mass_index = 0.0; unsigned int height = 0; height = feet * 12 + inches; body_mass_index = weight/(pow(height,2)) * 703.0; return body_mass_index; }

area_Circle function

#include <math.h> double areaCircle(double radius) { double area = 0; double PI = 3.14159; area = PI * pow(radius, 2); return area; }

math_func_example.c

#include <math.h> #include <stdlib.h> #include <stdio.h> void main (void) { float x,y; int answer=1; double result_1, result_2, result_3; while(answer!=-1) { printf("Please enter two numbers:"); scanf("%f%f",&x,&y); result_1=pow(x,2)+pow(y,2); result_2=sqrt(pow(x,2)+x*y+pow(y,2)); result_3=fabs(log(x)-log(y)); printf("result I = %.3lf\n",result_1); printf("result II = %.3lf\n",result_2); printf("result III = %.3lf\n",result_3); printf("Do you want to enter two more numbers? (0 for yes , -1 for no):"); scanf("%d",&answer); } system("pause"); }

Template for user defined functions

#include <stdio.h> int square(int y): //function prototype int main(void) { int x; for (x=; <=10; x++) { printf("%d", square(x_)); //function call, x is the argument passing to square function } } jint square(int y) //square function definition returns square of its parameter { return y*y; //returns the square of y as an int }

For_Loop Stars Code Example

#include <stdio.h> void main(void) { int i, j; for (i=1; i<=5; i++) { for (j=1; j<=10; j++) { printf("*"); } printf("\n"); } printf("\n\n\n"); for(i=1; i<=5; i++) { for (j=1; j<=i; j++) { printf("*"); } printf("*"); } printf("\n"); } system("\n"); } system("pause"); }

factorial.c

#include <stdio.h> #include <stdlib.h> unsigned long long int factorial( unsigned int number ); int main( void ) { unsigned int i; unsigned int n; printf("Enter the term you want to calculate by factorial functionï¼"); scanf("%u",&n); for ( i = 0; i <= n; ++i ) { printf( "%u! = %llu\n", i, factorial( i ) ); } // end for system("pause"); } // end main unsigned long long int factorial( unsigned int number ) { unsigned long long int result; // base case if ( number <= 1 ) { result=1; } // recursive step else { result=number * factorial( number - 1 ) ; } // end else return result; } // end function factorial

pass_reference.c

#include <stdio.h> #include <stdlib.h> void change_element(int array[],int index,int new_value); void print_array(int array[]); int change_value(int a,int b,int c, int new_value); int main(void) { int a=0,b=1,c=2; int myArray[5]={0}; change_element(myArray,2,9999); print_array(myArray); change_value(a,b,c,9999); c=change_value(a,b,c,9999); printf("a=%d,b=%d,c=%d\n",a,b,c); printf("\n\n"); system("pause"); } void change_element(int array[],int index,int new_value) { array[index]=new_value; } void print_array(int array[]) { int i; for(i=0;i<5;i++) { printf("%8d\n",i,array[i]); } return; } int change_value(int a,int b,int c, int new_value) { c=new_value; return c;

do_while_switch_month.c

#include <stdio.h> #include <stdlib.h> void main(void) { int month = 0; do { printf("Please enter the month as an interger 1 through 12 (Enter -1 to stop): "); scanf("%d", &month); switch (month) { case 1: printf("January has 31 days\n"); break; case 2: printf("February has 28 days\n"); break; case 3: printf("March has 31 days\n"); break; case 4: printf("April has 30 days\n"); break; case 5: printf("May has 31 days\n"); break; case 6: printf("June has 30 days\n"); break; case 7: printf("July has 31 days\n"); break; case 8: printf("August has 31 days\n"); break; case 9: printf("September has 30 days\n"); break; case 10: printf("October has 31 days\n"); break; case 11: printf("November has 30 days\n"); break; case 12: printf("December has 31 days\n"); break; case -1: printf("You stoped the program.\n"); break; default: { printf("Invalid value entered.\n"); printf("Please enter a value between 1 and 12.\n"); }; } } while(month!=-1); printf("\n\n"); system("pause"); }

product.c

#include <stdio.h> #include <stdlib.h> #include <math.h> void main(void) { int product; int num_of_iteration; product = 3; num_of_iteration = 0; printf("The initialized product is %d\n", product); while (product<= 100) { product = product * 3; num_of_iteration = num_of_iteration + 1; printf("In the %d iteration, product = %d\n", num_of_iteration, product); } printf("\n\n\n"); system("pause"); }

fibonacci.c

#include <stdio.h> #include <stdlib.h> unsigned long long int fibonacci( unsigned int n ); int main( void ) { unsigned long long int result; unsigned int answer=1; while(answer==1) { printf( "%s", "Enter an integer: " ); scanf( "%u", &number ); // calculate fibonacci value for number input by user result = fibonacci( number ); // display result printf( "Fibonacci( %u ) = %llu\n", number, result ); printf("More inputs?1 for YES 0 for NO"); scanf("%u",&answer); } } // end main // Recursive definition of function fibonacci unsigned long long int fibonacci( unsigned int n ) { // base case if ( n == 0) { return 0; } else if(n==1) { return 1; } else { // recursive step return fibonacci( n - 1 ) + fibonacci( n - 2 ); } }

BMI driver

#include <stdio.h> #include <stdlib.h> #include <math.h> // You must define function prototypes here float bmi(unsigned int feet, unsigned int inches, float weight); void main(void) { unsigned int feet, inches, weight; printf("Testing function BMI\n\n"); printf("Enter your height in feet and inches and your weight in lbs\n\n"); scanf("%u%u%u",&feet,&inches,&weight); printf("\n\nRESULT: Height = %u feet %u inches weight = %u: bmi = %5.2lf\n", feet, inches, weight, bmi(feet,inches,weight)); system("pause"); }

metric_convert_scope.c

#include <stdio.h> #include <stdlib.h> #include <math.h> float convert_metric(float weight, unsigned int feet, unsigned int inches); float weight_kg = 0.0; int main(void) { unsigned int ft, in; float weight = 0.0; unsigned int answer = 0; do { printf("Please enter your height in feet and inches.\n"); scanf("%u%u", &ft, &in); printf("Now enter your weight in pounds\n"); scanf("%f", &weight); convert_metric(weight, ft, in); printf("Your weight in kilograms is: %6.2f\n", weight_kg ); printf("Your height in meters is: %6.2f\n", height_m); printf("Do you want to continue? (1 = Yes/ 0 = No)"); scanf("%u", &answer); } while (answer != 0); system("pause"); } // // Function convert to metric // // This function convers height from feet to meters // and weight from pounds to Kiligrams // // Inputs: // 1. Weight in pounds - Type float // 2. Height in feet - Type unsigned int // 3. Height in inches - Type unsigned int // float convert_metric(float weight, unsigned int feet, unsigned int inches) { unsigned int height = 0; height = feet * 12 + inches; weight_kg = weight / 2.2; height_m = height / 39.4; return 0; }

grade average.c

#include <stdio.h> #include <stdlib.h> #include <math.h> int main(void) { unsigned int counter; // An unsigned integer can contain only positive values int grade; // Variable for the grade int total; // The sum of all grades entered float average; // average of grades as real number // Initialize the variables counter = 0; total = 0; // Get the first value before entering the loop printf("Enter a grade or -1 to terminate input."); scanf("%d", &grade); // Now use a while loop to get the 10 grades while (grade != -1) { total = total + grade; counter = counter + 1; printf("Total = %d Counter = %d\n", total, counter); printf("Enter a grade or -1 to terminate input."); scanf("%d", &grade); } // Now compute the average average = (float)total/counter; printf("The average is = %4.2f\n", average); printf("\n\n\n"); system("pause"); }

for_temp_table.c

#include <stdio.h> #include <stdlib.h> #include <math.h> int main(void) { float start_temp, stop_temp, degrees_c, degrees_f; printf("Enter a starting temperature in degrees C:"); scanf("%f", &start_temp); printf("Enter an ending temperature in degrees C:"); scanf("%f", &stop_temp); printf("Creating temperature table.\n\n\n"); printf("Faherenheit\tCelsius\n\n"); // Print column headers for (degrees_c = start_temp; degrees_c <= stop_temp; degrees_c += 5.0) //Repeat the calculations until degrees_c reaches stopping temp { degrees_f = (9.0/5.0)*degrees_c + 32.0; //Calculate temperature fahr printf("%5.1f\t\t%5.1f\n",degrees_f, degrees_c); // Print to screen } printf("\n\n\n"); system("pause");

while_repeat_program.c

#include <stdio.h> #include <stdlib.h> #include <math.h> int main(void) { unsigned int counter; // An unsigned integer can contain only positive values int grade; // Variable for the grade int total; // The sum of all grades entered float average; // average of grades as real number // Initialize the variables counter = 0; total = 0; // Get the first value before entering the loop printf("Enter a grade or -1 to terminate input."); scanf("%d", &grade); // Now use a while loop to get the 10 grades while (grade != -1) { total = total + grade; counter = counter + 1; printf("Total = %d Counter = %d\n", total, counter); printf("Enter a grade or -1 to terminate input."); scanf("%d", &grade); } // Now compute the average average = (float)total/counter; printf("The average is = %4.2f\n", average); printf("\n\n\n"); system("pause"); }

magic_number.c

#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> int main(void) { int guess = 0, count; int magic_num; srand(time(NULL)); magic_num=rand() % 100 + 1; // Generate a random number between 1 and 100 // Prompt the user to enter a number between 0 and 100 printf("Welcome to Guess The Number! \n\n"); printf("The number is between 0 and 100.\n"); printf("What is your guess?\n\n"); scanf("%d", &guess); //Did they guess the number the first time? If so then quit. for(count=1;count<=10;count++) { if (guess > magic_num ) { printf("Too high. Guess again.\n"); scanf("%d", &guess); } else if(guess < magic_num ) { printf("Too low. Guess again:\n"); scanf("%d", &guess); } else if (guess == magic_num) { printf("Congratulations. You Win!\n"); break; } } if (count >= 10) { printf("You have no chance"); } system("pause"); }

binarySearch.c

#include <stdio.h> #include <stdlib.h> #define MAXSIZE 10 int binarySearch(int array[],int key_value,int first,int last); int main(void) { int i, search, array[MAXSIZE]; int index; printf("Enter %d integers\n", MAXSIZE); for (i = 0; i < MAXSIZE; i++) scanf("%d",&array[i]); printf("Enter value to find\n"); scanf("%d", &search); index=binarySearch(array,search,0,MAXSIZE-1); if(index!=-1) { printf("Array[%d] match the key value %d.\n", index,search); } else printf("Not found! %d is not present in the Array.\n", search); printf("\n\n"); system("pause"); } int binarySearch(int array[],int key_value,int first,int last) { //int first = 0; //last = n - 1; int middle = (first+last)/2; while (first <= last) { printf("First=%d, Middle=%d,Last=%d\n",first,middle,last); if (array[middle] < key_value) first = middle + 1; else if (array[middle] == key_value) { return middle; } else last = middle - 1; middle = (first + last)/2; } //if (first > last) return -1;

char_array_01.c

#include <stdio.h> #include <stdlib.h> void main (void) { // Declare two character arrays using the char type, // and initialize them to all zero with {NULL} char first_name[20] = {NULL}; char last_name[20] = {NULL}; char eol, answer; answer = 'Y'; do { printf("Please enter your first name - maximum of 20 characters. \n"); scanf("%s", first_name); printf("Please enter your last name - maximum of 20 characters. \n"); scanf("%s", last_name); // NOTE do not use & in scanf when reading into an array printf("Hello %s %s \n", first_name, last_name); printf("Do you want to enter another name? (Y/N)"); scanf("%c%c", &eol, &answer); //eol is a end of line mark \n } while (answer == 'Y' || answer == 'y'); printf("\n\n"); system("pause");

char_array_03.c

#include <stdio.h> #include <stdlib.h> void main (void) { char first_name[20] = {NULL}; // Initialize the array to zeroes char last_name[20] = {NULL}; char letter = ' '; int i = 0; // Enter the first name printf("\nPlease enter your first name - Max 20 characters. \n"); i = 0; do { letter = getchar(); first_name[i++] = letter; } while (letter != '\n'); // Now do the same for the last name printf("Please enter your last name - Max 20 characters. \n"); i = 0; do { letter = getchar(); last_name[i++] = letter; } while (letter != '\n'); // Output the names using the putchar() function one letter at time printf("\nOutput produced by function putchar( )\n\n"); i = 0; while(first_name[i] != '\n'){ putchar(first_name[i++]); } putchar(' '); // Put a space between names i = 0; while(last_name[i] != '\n'){ putchar(last_name[i++]); } putchar('\n'); putchar('\n'); system("pause");

functions_1d_array.c

#include <stdio.h> #include <stdlib.h> #define ELEMENTS 20 void print_array(int array[]); void initialize(int array[]); int sum_array(int array[]); double find_average(int array[]); void main (void) { int numbers[ELEMENTS] = {0}; //initialize all the elements in the array into 0 srand(time(NULL)); initialize(numbers); print_array(numbers); printf("The sum of all values is %d\n", sum_array(numbers)); printf("The average of all values is %6.2f\n", find_average(numbers)); system("pause"); } /* FUNCTION PRINT ARRAY */ /* Print out all values in the array */ void print_array(int array[]) { int i; printf("CONTENTS OF ARRAY\n\n"); for (i = 0; i < ELEMENTS; i++) { printf("array[%d] = %d\n",i, array[i]); } printf("\n\n\n"); return; } /* FUNCTION INITIALIZE */ /* Initialize all the values in the array with values from 0 to 999 */ void initialize(int array[]) { int i; for (i = 0; i < ELEMENTS; i++) { array[i] = rand()%1000; } return; } /* FUNCTION SUM ARRAY */ /* Sum all the values in the array */ int sum_array(int array[]) { int i, sum = 0; for (i = 0; i < ELEMENTS; i++) { sum = sum + array[i]; } return(sum); } // FIND AVERAGE FUNCTION // double find_average(int array[]) { int i, sum = 0; double avg = 0.0; for (i = 0; i < ELEMENTS; i++) { sum = sum + array[i]; } avg = (float)sum/ELEMENTS; return(avg);

LinearSearchArray.c

#include <stdio.h> #include <stdlib.h> #define MAXSIZE 10 int LinearSearch(int array[],int key_value); void main() { int array[MAXSIZE]; int i, index; int key_value=-999; //Inputing the array printf("Enter the elements one by one \n"); for (i = 0; i < MAXSIZE; i++) { scanf("%d", &array[i]); } //Input key_value printf("Enter a key value:"); scanf("%d",&key_value); //Print out the Array printf("Input array is \n"); for (i = 0; i < MAXSIZE; i++) { printf("%d\t", array[i]); } printf("\n\n"); /* Call Linear Search Function */ index=LinearSearch(array,key_value); if(index==-1) { printf("Key value not found in the array."); } else{ printf("array[%d] match the key value %d\n",index,key_value); } printf("\n\n"); system("pause"); } int LinearSearch(int array[],int key_value) { int i=0; for(i=0;i<MAXSIZE;i++) { if(array[i]==key_value) return i; } return -1;

bubbleSort.c

#include <stdio.h> #include <stdlib.h> #define MAXSIZE 10 void main() { int array[MAXSIZE]; int i, j, temp; //Inputing the array printf("Enter the elements one by one \n"); for (i = 0; i < MAXSIZE; i++) { scanf("%d", &array[i]); } //Print out the Array printf("Input array is \n"); for (i = 0; i < MAXSIZE; i++) { printf("%d\t", array[i]); } printf("\n\n"); /* Bubble sorting begins */ for (i = 0; i < MAXSIZE; i++) { for (j = 0; j < (MAXSIZE - i - 1); j++) { if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } printf("Sorted array is...\n"); for (i = 0; i < MAXSIZE; i++) { printf("%d\t", array[i]); } printf("\n\n"); system("pause")

Rand_Mod.c

#include <stdlib.h> #include <stdio.h> #include <math.h> void main(void) { unsigned int number =0; unsigned int values = 0; unsinged int range_1, range_2; int i = 0; j=0; //prompt users to input the range printf("\n Enter two numbers for the range:"); scanf("%u%u", &range_1, &range_2); printf(\nRandom numbers between your range\n\n"); for (i=1; i < 100; i++) { number = rand() % range_2 + range_1; printf("%4u\n", number); } system("pause"); }

Temperature convert driver

#include <stdlib.h> #include <stdio.h> #include <math.h> // You must define function prototypes here double convert(double); void main(void) { double celsius = 0.0, fahr = 0.0; unsigned int answer = 0; do { printf("The main function...\n\n"); printf("Please enter a temperature in degrees Celsius "); scanf("%lf", &celsius); fahr = convert(celsius); ("Back in the main function again... \n\n"); printf("Converted temperature = %8.2lf\n", fahr); printf("Do you want to continue? Enter 1 for Yes and 0 for No"); scanf("%u", &answer); } while ( answer != 0); system("pause"); }

array_grades.c

// // This program illustrates the use of single dimensional arrays. // #include <stdio.h> #include <stdlib.h> #include <math.h> int main (void) { int score = 0, drop = 99, hw_points = 0; int grades [8] = {8, 9, 9, 7, 8, 9, 9, 10}; // Initialize by list unsigned int i = 0, j = 0, k = 0; unsigned int count = 0; int sum = 0; // Print the homework grades printf("\n\nHOMEWORK GRADES\n\n"); for (i = 0; i < 8; i++){ printf("Grade %2u = %3d\n", i, grades[i]); } printf("\n\n\n"); // Use a loop to enter new homework grades i = 0; // Reset Count while (i < 8) { printf("Enter homework grade %u: ", i+1); scanf("%d", &grades[i]); i++; } // Print the homework grades printf("\n\nHOMEWORK GRADES\n\n"); for (i = 0; i < 8; i++){ printf("Grade %2u = %3d\n", i, grades[i]); } printf("\n\n\n"); // Sum the grades dropping the lowest score for (i = 0; i < 8; i++){ if (grades[i] <= drop){ drop = grades[i]; } sum = sum + grades[i]; } hw_points = sum - drop; printf("The lowest score is %d. It will be dropped.\n\n", drop); printf("Your homework points are %d \n\n", hw_points); printf("\n\n\n"); system("pause"); }

add_two_simple.c

// Function Prototype // int addTwo(int, int); int main(void) { int answer = 1; int num1, num2, sum; printf("\n\n Test function addTwo with integer numbers\n\n"); do { printf("Enter two integer values.\n"); scanf("%d%d", &num1, &num2); printf("The sum is %d \n", addTwo(num1, num2)); printf("Do you want to add two more integers? (Enter 1 for yes, 0 for no)\n"); scanf("%d", &answer); } while (answer == 1); system("pause"); } // Function add two int addTwo(int firstNum, int secondNum) { int sum; sum = firstNum + secondNum; return sum; }

To write to a file, you need to declare a file type pointer. How do you declare a file pointer?

FILE *outfile;

Format of a function definition

Return-value-type function-name (parameter-list) { statements; return return-value; }

test of average function

average=average_of_elements(myArray); printf("Average of the elements in the array = %f\n", average);

area driver

double areaCircle(double); double areaRectangle(double, double); double areaTriangle(double, double); int main(void) { double area_C, area_R, area_T; // Test Case 1 for function areaCircle // Call the function three times with the test values 3.5, 5.81, 6.7 printf("\n\n Test function areaCircle with three calls using real numbers\n\n"); area_C = areaCircle(3.5); printf("The area of a circle with radius %5.2lf is %5.2lf\n", 3.5, area_C); area_C = areaCircle(5.81); printf("The area of a circle with radius %5.2lf is %5.2lf\n", 5.81, area_C); area_C = areaCircle(6.7); printf("The area of a circle with radius %5.2lf is %5.2lf\n", 6.7, area_C); // Test Case 2 for function areaRectangle // Call the function three times with these test values: printf("\n\n Test function areaRectangle with three calls using real numbers\n\n"); area_R = areaRectangle(4.0, 3.0); printf("The area of a rectangle with length %5.2lf and width %5.2lf is %5.2lf\n", 4.0, 3.0, area_R); area_R = areaRectangle(6.7, 5.25); printf("The area of a rectangle with length %5.2lf and width %5.2lf is %5.2lf\n", 6.7, 5.25, area_R); area_R = areaRectangle(12.0, 8.0); printf("The area of a rectangle with length %5.2lf and width %5.2lf is %5.2lf\n", 12.0, 8.0, area_R); printf("\n\n Test function areaTriangle with three calls using real numbers\n\n"); area_T = areaTriangle(4.45, 3.88); printf("The area of a triangle with base %5.2lf and height %5.2lf is %5.2lf\n", 4.45, 3.88, area_T); area_T = areaTriangle(16.65, 12.34); printf("The area of a triangle with base %5.2lf and height %5.2lf is %5.2lf\n", 16.65, 12.34, area_T); area_T = areaTriangle(24.41,17.77); printf("The area of a triangle with base %5.2lf and height %5.2lf is %5.2lf\n", 24.41,17.77, area_T); printf("\n\n\n"); system("pause");

area_Rectangle function

double areaRectangle(double length, double width) { double area = 0; area = length * width; return area; }

area_Triangle function

double areaTriangle(double base, double height) { double area = 0; area = base * height * 0.5; return area; }

Print the column headings for the table to the file using fprintf

fprintf(outfile, "Celsius to Fahrenheit Temperature Conversion\n\n");

How do you check to make sure a file opened?

if (outfile == NULL ) { printf("Could not open the file for output.\n"); system("pause"); return; } else { printf("The file was opened successfully.\n\n"); }

Initialize the file pointer

if((outfile = fopen("C:/Users/mini/Desktop/Files/Mydoc2.txt", "w"))==NULL) printf("Directory could not found");

test of initialize function

initialize (myArray);

Totaling the elements in a two-dimensional array

int Total=0; int myArray[3][4]={{4, 5, 6, 7}, {8, 9, 10, 11}, {12, 13, 14, 15}}; for (row=0; row<=3; row++) { for(column=0; column<=4; column++) { total+=myArray[row][column]; } }

Setting the elements of an array in one row

int a[3][4]={0}; //setting all the elements in row 1 of array a into 9 for (column = 0; column<4; column++) { a[1][column]=9; }

Add_Two function

int addTwo (int num1, int num2) { int sum; sum=num1+num2; return sum; }

changing_value function

int changing_value(int a[][COLS], int x, int y, int z) { int old_value; old_value=a[x][y]; a[x][y]=z; return old_value; }

low_high function

int low_high(int a[][COLS], int x,int y) { int i,j; int count=0; for(i=0; i<ROWS; i++) { for(j=0; j<COLS; j++) { if((x <= a[i][j]) && (y >= a[i][j])) count++; } } return count;

maximum function

int maximum(int a[][COLS]) { int i,j; int max=0; for(i=0; i<ROWS; i++) { for(j=0; j<COLS; j++) { if(max < a[i][j]) max=a[i][j]; } } return max;

Initializing a two-dimensional array

int myArray[3][4] = {{4, 3, 6,7},{8, 9, 10, 11}, {12, 13, 14, 15}}; Note: the values are grouped by rows in braces. int myArray[3][4]={{4, 5},{8}, {12, 13, 14, 15}}; Note: if there are not enough initializers for a given row, the remaining elements of that row are initialized to 0. int myArray[3][4]={1, 2, 3, 4, 5, 6, 7}; Note: fill in the elements one by one if the initializer list did not group by row, fill in the remaining with 0. The initializers are assigned to the first row, then the second row, then the third row.

Initializing the elements of an array to zeros

int n[5]; int i; for (i=0; i < 5; i++) { n[i]=0; }

Initializing the elements of an initializer list

int n[5]={56, 23, 10, 63, 89} or int n[]={56, 23, 10, 63, 89};

Passing arrays to functions:

int numbers [5]={9, 8, 7, 10, 9};

sum_of_column function

int sum_of_column(int a[][COLS], int y) { int j; int sum=0; for(j=0; j<ROWS; j++) sum=a[j][y] + sum; return sum; }

sum_of_elements function

int sum_of_elements(int a[][COLS]) { int i, j,z=0; for(i=0; i<ROWS; i++) { for(j=0; j<COLS; j++) { z=z+a[i][j];

sum_of_row function

int sum_of_row(int a[][COLS], int x) { int i; int sum=0; for(i=0; i<COLS; i++) sum=a[x][i] + sum; return sum;

test of maximum function

max=maximum(myArray); printf("Maximum value stored in the array = %d\n", max);

test of minimum function

min=minimum(myArray); printf("Minimum value stored in the array = %d\n", min);

Open a file using the fopen function. Specify the path for the file on disk and "w" to designate the file writing.

outfile = fopen("C:/Users/mini/Desktop/Files/MyDoc3.txt", "w");

test of print_array function

print_array(myArray);

print confirmation to the console if a file was opened successfully

printf("The output file is open\n");

test of changing_values function

printf("What is the index of the row?\n"); scanf("%d", &row); printf("What is the index of the column?\n"); scanf("%d", & col); printf("What is the new value?\n"); scanf("%d", &original_value); value=changing_value(myArray, row, col, original_value); printf("Original value stored %d row and %d column = %d\n", row, col, value); print_array(myArray);

test of low_high function

printf("What is the low integer value?\n"); scanf("%d", &low); printf("What is the high integer value?\n"); scanf("%d", &high); num=low_high(myArray, low, high); printf("Number of elements that are between %d and %d = %d\n", low, high, num);

test of sum of column function

printf("Which column do you want to sum up?\n"); scanf("%d", &sum_all); sum_col=sum_of_column(myArray, sum_all); printf("Sum of %d column = %d\n", sum_all, sum_col);

test of sum_of_row function

printf("Which row do you want to sum up?\n"); scanf("%d", &sum_up); sum_row=sum_of_row(myArray, sum_up); printf("Sum of %d row = %d\n", sum_up, sum_row);

Random number function example:

random_number = rand() % range_2 + range_1

test of sum of elements function

sum=sum_of_elements(myArray); printf("Sum of the elements in the array = %d\n", sum);

Sequentially reading from a file

void main(void) { FILE *infile; // You must declare a file pointer char message[30]; infile= fopen("Readout.txt", "r"); // use fopen to open the file. The "r" flag indicates the file is open for read. fscanf(infile, "%29s", message); // Use fscanf to read message from the file. printf("%s",message); fclose(infile); // close the file }

print_array function

void print_array(int a[][COLS]) { int i, j; for(i=0; i<ROWS; i++) { for(j=0; j<COLS; j++) { printf("%d ", a[i][j]);

While loop statement:

while (variable = -1) { statements }


Set pelajaran terkait

1.1.1: Current systems of representative and direct democracy

View Set

Klemm: Chapter 3- The Fathers of the Church

View Set

Sensoriske receptormekanismer (excitable celler)

View Set

Hospital Unit Procedures 2 Test 1

View Set

ISYS EXAM 2: 7.3 (Wireless Network Categories)

View Set

Geography - Records, Longest Rivers by Continent & US

View Set

Chapter 17- Externalities & Public Goods

View Set