Arrays

12 Individual variables vs. one array

The most common use of a for loop in C++ is to loop through the subscripts of the elements of an array. See output3.C and sum3.C.

  1. Output a dozen values.
    1. output1.C: store the values in 12 separate int variables, and output the values with 12 cout statements.
    2. output2.C: store the values in an array of 12 ints, and output the values with 12 cout statements.
    3. output3.C: store the values in an array of 12 ints, and output the values with one cout statement in a for loop.
      We saw the sizeof operator in integer.C.
    4. output4.C: store the values in an array of 12 ints, and output the values and their subscripts with one cout statement in a for loop.
      Exercise. In output4.C, number the elements from 1 to 12 instead of from 0 to 11, because human beings like to start counting at 1, not at 0.
      Simply output the expression i+1 in place of i.
  2. Sum a dozen values.
    1. sum1.C: store the values in 12 separate int variables, and sum them with one big expression.
    2. sum2.C: store the values in an array of 12 ints, and sum them with 12 little expressions.
    3. sum3.C: store the values in an array of 12 ints, and sum them with one little expression in a for loop.

An array of strings

  1. names.C: loop through an array of 12 strings instead of an an array of 12 ints.
  2. number1.C: loop through an array of strings, in either direction.
    Exercise: change the if/else if/else statement in number1.C to a switch/case/default statement. See switch1.C and switch2.C.
  3. switch4.C: pick a string out of an array of strings instead of looping through the array.
    switch4.C holds all its data in a “data structure” (an array), and is therefore simpler than switch1.C and switch2.C.
    Exercise. Make the C++ program month.C output the name of the current month. Imitate switch4.C.
  4. The Chinese zodiac: pick a string out of an array of strings
    1. monkey1.C. Compute the desired array subscript with the % (remainder) operator.
    2. monkey2.C. The same program, but with a long chain of else/if statements instead of an array.
      The %= operator knocks the year down to a much smaller number, in the range 0 to 11 inclusive.
    3. monkey3.C. The same program, but with a switch statement instead of an array.
    monkey1.C holds all its data up in a “data structure” (an array).
    That’s better than monkey2.C and monkey3.C, which kept all their data down in the “code” (the if and switch statements).
    Exercise. Instead of outputting “was the year of the” in monkey1.C, output “was/is/will be”. Use a three-way if.
            time_t t {time(nullptr)};            //remember to #include <ctime>
            tm *p {localtime(&t)};
            int currentYear {p->tm_year + 1900}; //the current year
    
  5. plot1.C: pick a string out of an array of strings.
    From the The Official Movie Plot Generator by the Brothers Heimberg.

Initialize, copy, and assign to an array. A range for loop.

  1. initialize.C: three ways to initialize an array (or else leave it full of garbage).
  2. Take initial values from cin.
  3. Copy the values in one array into another array
    1. copy1.C without a loop
    2. copy2.C with a plain old for loop. Can’t copy with a range for loop, because a range for loop can loop through only one array at a time.
    3. copy3.C with the std::copy algorithm from the C++ Standard Lirary.
  4. random.C: change the values stored in an array.
  5. stack.C: LIFO: last hired, first fired.
    Exercise. If you list the stack when there is only one employee, it should say “The 1 current employee is:”.
  6. queue.C: FIFO: first in, first out. People are waiting on line to be served.
  7. range.C: loop through the values in an array using a range for loop.
  8. colbert.C: loop through the chars in a string of chars using a range for loop, just like the one in range.C.
    Exercise. Change the Ed Sullivan Theater to the Apollo Theater.

One-dimensional arrays: searching and sorting

  1. Carmodel: an example of a data structure (a “map”) for next semester.
    1. carmodel1.C holds all of its data in if statements and cout statements.
    2. carmodel2.C holds all of its data in a data structure.
    Exercise. In carmodel2.C, change the models and colors (adding extra ones, rearranging their order), without changing any part of the program except for the data structure.
  2. Dependents: a financial exmple for tax purposes.
    1. dependents1.C holds all of its data in if statements and cout statements.
    2. dependents2.C holds all of its data in a data structure (ann array).
  3. date.C: pretend there is no such thing as a leap year.
    1. Exercise. Use the operators / and % to break the distance down into a number of years and a number of remaining days, where days is in the range 0 to 364 inclusive. You can then add years to year, leaping in a single bound to within one year of the destination date. Then walk the remaining days.
    2. Another exercise. Make the for loop stride the rest of the way to the destination one month at a time, not one day at a time.
  4. Exercise. Use nested loops to output the lyrics to a song whose verses get longer and longer.
    (Hint 1: see how the lines of output in triangle1.C and triangle2.C got longer and longer.)
    1. The Twelve Days of Christmas. Hint 2: christmashint.C.
    2. Green Grow the Rushes, O
    3. There’s a Hole in the Bottom of the Sea
    4. There Was an Old Lady Who Swallowed a Fly
    5. The Green Grass Grew all Around, all Around
    6. A song in a non-English language.
  5. Search an array (of strings) for a given value.
    1. find1.C with a range for loop.
      string variables differ from int variables in three ways:
      1. Must #include <string>
      2. Initial value is "" by default.
        No need to say string name {""};
      3. cin >> name; would input only one word.
        Use the getline function (with parentheses) to input an entire line up to the terminating newline character.
    2. find2.C with a plain old for loop, to find the index of the value in the array
    3. find3.C with the C++ standard library find algorithm instead of a for loop
  6. Exercise.
    income.C: an array of 50 strings, giving the names of the U.S. States in order of decreasing 2021 median household income (from the Wikipedia article).
    Input the name of a state, find what its rank is in median household income.
    Imitate find2.C.
    Please type the name of a state: New York
    New York is number 14 of 50 in terms of median household income.
    
  7. Find the smallest element in an array. What happens if two or more elements are tied?
    1. minimumint.C: an array of ints.
    2. minimumstring.C: an array of strings.
    Exercise. Find the largest element in the array.
  8. A destructive sort that erases the values in the array.
    1. sortint.C: an array of ints.
      We saw the expression numeric_limits<int>::max() in integer.C.
    2. sortstring.C: an array of strings.
    3. Exercise.
      Count how many times sortint.C or sortstring.C iterates, by counting how many times the program executes the comparison
      			if (a[j] < a[smallest]) {
      
      Do this by creating a new variable
      	int count {0};   //how many times we compare pairs of elements
      
      immediately before the “for (int i” loop, and say
      		++count;
      
      immediately before the if statement, and say
      	cout << "We performed " << count << " comparisons.\n";
      
      immediately before the return EXIT_SUCCESS;. You should discover that the program compared 49 × 50 = 2450 pairs of elements while sorting the array of 50 elements. That’s (n − 1)n pairs, which we will round to n2 pairs.
    4. Exercise. Make sortint.C or sortstring.C sort the values into decreasing order. Simply reverse the comparison operator to
      			if (a[j] > a[smallest]) {
      
      and (for your own personal sanity) rename the varariable smallest to largest. In sortint.C change the biggest possible number numeric_limits<int>::max() to the smallest possible number numeric_limits<int>::min(). In sortstring.C, change the “biggest” string "zzzzzzzzzzzzzzzz" to the “smallest” string "AAAAAAAAAAAAAAAA". Then run the program again.
  9. A non-destructive sort that rearranges the values in the array without erasing them.
    1. swap.C: swap the values of two variables.
      Exercise. Why do we need the variable temp in swap.C? Why can’t we swap the values of x and y like this?
      	//Swap the values of x and y.
      	x = y;
      	y = x;
      
    2. bubblesortint.C: an array of ints.
    3. bubblesortstring.C: an array of strings.
    4. Exercise. Count how many times bubblesortint.C or bubblesortstring.C execute the comparison
      			if (a[j] > a[j + 1]) {
      
      You should discover that the program compared only (49 × 50)/2 = 1225 pairs of elements while sorting an array of 50 elements. That’s (n − 1)n/2 pairs, which we will round to n2/2 pairs.
    5. Exercise. Make bubblesortint.C or bubblesortstring.C sort the values into decreasing order.

Two-dimensional arrays

  1. A two-dimensional array of strings:
    1. language1.C with a two-dimensional array.
      Compare the one-dimensional array in switch4.C.
    2. language2.C with nested if statements
    3. Exercise. Add the following array of 4 strings to language1.C.
      	string langname[] {
      		"English",
      		"Spanish",
      		"French",
      		"German"
      	};
      
      Output the user instructions by looping through this new array.
    4. See language4.C for the correct way to program this problem in C++.
  2. Another two-dimensional array of strings:
    1. street1.C has no array
    2. street2.C has a one-dimensional array
    3. street3.C has a two-dimensional array
  3. Another two-dimensional array of strings: roman.C converts an integer to a Roman numeral.
  4. A two-dimensional array of ints.
    1. france.C (france.png) had three vertical stripes.
    2. flaghw2.C (flaghw2.png) has four vertical stripes.
    3. Make it easy to add more vertical stripes with verticalstripes.C.
      Here are three “cartridges” you can plug into verticalstripes.C:
      1. france.txt: three stripes
      2. papaya.txt: four stripes
      3. spectrum.txt: seven stripes (spectrum.png)
  5. date4.C: a two-dimensional array of ints to handle leap vs. non-leap years.
    Test it by going 1460 = 365 × 4 days into the future, which will take us past February 29, 2028.

Parallel arrays and arrays of structures

  1. parallel1.C. Parallel arrays: a column of ints and a column of strings.
    I wish they columns could be side-by-side as in structure2.C.
  2. Structures
    1. structure1.C: create 12 structures.
    2. structure2.C: create an array of structures, and loop through it with a plain old for loop.
      Exercise.
      In structure2.C, observer how the column of names is output left-justified, and the column of numbers is output right-justified.
    3. structure3.C: create an array of structures, and loop through it with a range for loop.
    Exercise.
    structure2.C has two columns. Add a third column, of type double, named temperature, giving the average temperature in Fahrenheit, in New York City, for each month in 2023. You will have to do three things:
    1. Add a third field
      		double temperature;   //2023 average, in fahrenheit
      
      to the blueprint for the data type month, after the two existing fields.
    2. Add a third value to the initialization of each structure. For example,
      		{"January",   31,  43.5},
      		{"February",  28,  41.1},
      		//etc.
      
    3. Also output the average temperature of each month.
  3. Exercise. parallel3.C: let the user type the name of a state, then output the 2021 median income for that state.
    parallel4.C: an array of 50 structures.
  4. plot2.C: how it all fits together. A one-dimensional array of structures, and a two-dimensional array of strings.
    From the The Official Movie Plot Generator by the Brothers Heimberg.
    An improved version of plot1.C.
  5. ants.C: two columns of strings.
  6. fly.C: two columns of strings.
  7. greengrass.C: two columns of strings.
  8. avenue.C: at what cross street is a given address on a Manhattan Avenue? Uses data from Wikipedia.
  9. wav.C and sine.wav: create an audio file.
    jsmith@storm:~$ cd
    jsmith@storm:~$ c++ wav.C
    jsmith@storm:~$ ./a.out
    jsmith@storm:~$ mv sine.wav public_html
    
    Move the file to your public_html directory on storm.cis.fordham.edu and then point your browser at
    http://storm.cis.fordham.edu/~jsmith/sine.wav.

Songs

  1. The Twelve Days of Christmas
    1. line.C
    2. rectangle.C
    3. triangle1.C
    4. triangle2.C
    5. christmashint.C
    6. ordinal.C
    7. christmas.C
  2. There’s a Hole in the Bottom of the Sea
    1. lyricsHomework.C
    2. hole.C
  3. There Was an Old Lady Who Swallowed a Fly
    1. FlysongHWupdated.C
    2. fly.C
  4. The Ants go Marching One by One
    The verses of this song do not get longer and longer.
    1. ants.C
      Exercise. How would you make it output “1 by 1” instead of “one by one”, etc.?
  5. And the Green Grass Grew All Around All Around
    1. greengrass.C

Old examples