Pesky Patterns

 

Modules - CSE1120

 

Teacher’s Notes:

=======================================

Students find this assignment to be quite difficult - especially for new programmers.  I feel like it's important to master these skills since generating patterns in a FOR loop can be essential for programming. 

The assignment is written in C++ but can easily adapted to JAVA or any other programming language by swapping the cout<< for whatever output syntax your language uses.

 
 

Assignment:

=======================================

Patterns are very important in programming and problem solving. In each of the following partial codes, erase the section labelled as /* BLANK */ and replace it with a single line/fragment of code that will generate the given pattern.

Pattern 1

0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50

Code for Pattern 1

 

for(int x = 0; x < 52; /* BLANK */)
    cout << x << " ";

cout << endl;

Pattern 2

52 48 44 40 36 32 28 24 20 16 12 8 4 0

Code for Pattern 2

 

for(/* BLANK */)
    cout << x << " ";

cout << endl;

Pattern 3

1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 12 13

Code for Pattern 3

for(int x = 0; x < 52; x++)
    cout << /* BLANK */ << " ";

cout << endl;

Pattern 4

1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4

Code for Pattern 4

for(int x = 0; x < 52; x++)
    cout << /* BLANK */ << " ";

cout << endl;
 

Solution (C++):

=======================================

#include <iostream>
using namespace std;
 
int main()
{
    for(int x = 0; x < 52; x+=2)
        cout << x << " ";
    cout << endl;
 
    for(int x = 52; x >= 0; x-=4)
        cout << x << " ";
    cout << endl;
 
    for(int x = 0; x < 52; x++)
        cout << x%13+1 << " ";
    cout << endl;
 
    for(int x = 0; x < 52; x++)
        cout << x/13+1 << " ";
    cout << endl;
 
    return 0;
}