Set numMatches to the number of elements in userValues (having NUM_VALS elements) that equal matchValue. Ex: If matchValue = 2 and userValues = {2, 2, 1, 2}, then numMatches = 3.
#include <stdio.h> int main(void) { const int NUM_VALS = 4; int userValues[NUM_VALS]; int i; int matchValue; int numMatches = -99; // Assign numMatches with 0 before your for loop userValues[0] = 2; userValues[1] = 2; userValues[2] = 1; userValues[3] = 2; matchValue = 2; numMatches = 0; for (i = 0; i < NUM_VALS; i++){ if(matchValue == userValues[i]){ numMatches = numMatches + 1; } } printf("matchValue: %d, numMatches: %d\n", matchValue, numMatches); return 0; }
Populating an array with a for loop.
Write a for loop to populate array userGuesses with NUM_GUESSES integers. Read integers using scanf. Ex: If NUM_GUESSES is 3 and user enters 9 5 2, then userGuesses is {9, 5, 2}.
#include <stdio.h> int main(void) { const int NUM_GUESSES = 3; int userGuesses[NUM_GUESSES]; int i; for(i = 0; i < NUM_GUESSES; i++){ scanf("%d", &userGuesses[i]); } for (i = 0; i < NUM_GUESSES; ++i) { printf("%d ", userGuesses[i]); } return 0; }
Array iteration: Sum of excess.
Array testGrades contains NUM_VALS test scores. Write a for loop that sets sumExtra to the total extra credit received. Full credit is 100, so anything over 100 is extra credit. Ex: If testGrades = {101, 83, 107, 90}, then sumExtra = 8, because 1 + 0 + 7 + 0 is 8.
#include <stdio.h> int main(void) { const int NUM_VALS = 4; int testGrades[NUM_VALS]; int i; int sumExtra = -9999; // Assign sumExtra with 0 before your for loop testGrades[0] = 101; testGrades[1] = 83; testGrades[2] = 107; testGrades[3] = 90; sumExtra = 0; for(i = 0; i < NUM_VALS; i++){ if(testGrades[i] > 100){ sumExtra = sumExtra + (testGrades[i] - 100); } } printf("sumExtra: %d\n", sumExtra); return 0; }
Printing array elements separated by commas.
Write a for loop to print all NUM_VALS elements of array hourlyTemp. Separate elements with a comma and space. Ex: If hourlyTemp = {90, 92, 94, 95}, print:
90, 92, 94, 95
#include <stdio.h> int main(void) { const int NUM_VALS = 4; int hourlyTemp[NUM_VALS]; int i; hourlyTemp[0] = 90; hourlyTemp[1] = 92; hourlyTemp[2] = 94; hourlyTemp[3] = 95; for(i = 0; i < NUM_VALS ; i++){ printf("%d", hourlyTemp[i]); if (i < NUM_VALS - 1) printf(", "); } printf("\n"); return 0; }