Skip to content

Instantly share code, notes, and snippets.

@rszewczyk
Last active November 9, 2017 22:25
Show Gist options
  • Save rszewczyk/a7af87e5250232d7874b00f1ae1c002e to your computer and use it in GitHub Desktop.
Save rszewczyk/a7af87e5250232d7874b00f1ae1c002e to your computer and use it in GitHub Desktop.
class 16

Assignment - Class 16: 10/31/2017

In this assigment you will learn about looping logic in C.

As part of this assigment you will create a program in a file called loops1.c. When you complete the assigment you will submit loops1.c by uploading it to Slack. If you do not finish today, you have until the end of class (6:45pm) on Thursday, 11/2/2017 to turn it in. Note this doesn't necessarily mean you will have time to work on it in class on 11/2. If don't finish today, you should try and finish it before Thursday.

Step 1

Copy and paste the code below into a new file and save it. Give it the name loops1.c.

#include <stdio.h>

int main()
{
  int loopCount = 0;

  while (loopCount < 5)
  {
    printf("this is loop number %d\n", loopCount);
  }

  printf("loop complete\n");

  return 0;
}

Upload this file to the UMBC Linux server and compile it. The run the program and observe that the program never stops. You can interrupt the program (and thus stop it) by pressing and holding the ctrl key plus the c key until you see the command prompt reappear.

This type of structure is called a loop - specifically a while loop. A while loop has the following basic structure:

  while (conditionalExpression)
  {
    // loop body
  }

Make sure you pay attention to the placement of parenthesis and brackets. The conditional expression can be any of the same logical expressions we learned about when we covered if statements. The loop body is the code the appears between the open and closing curly brackets. The way the loops works is that first the conditional is checked. It it holds true then the loops body is executed. Next, the conditional is checked. If if it continues to hold true, the loop body is executed again. The conditional is continually checked before running the loop body - as soon as the condition is not true, the program terminates the loop (does not execute the body) and continues after the end of the loop body.

Step 2

In our program the conditional is loopCount < 5 and the body consists of a single printf statemenet. Also, note that the conditional is always true. We start off assigning the value 0 to loopCount and we never change it. Therefore the loop executes forever - which is why we have to intervene to stop the program with ctrl + c.

Modify the program so it looks like:

#include <stdio.h>

int main()
{
  int loopCount = 0;

  while (loopCount < 5)
  {
    printf("this is loop number %d\n", loopCount);
    loopCount = loopCount + 1;
  }

  printf("loop complete\n");

  return 0;
}

Save and upload your file to the UMBC Linux server. Then compile and run it. You should now see the following output.

this is loop number 0
this is loop number 1
this is loop number 2
this is loop number 3
this is loop number 4
loop complete

This is a common way to setup a loop so that it eventually finishes. We use the value stored in a variable to control how many times the loop runs. The variable is initialized to a value that ensures the loop is executed once (e.g. 0 is less than 5, so the loop will run at least once). Then the value stored in the variable is changed (often by incrementing it) so that the loop conditional is false at some point (e.g. if we keep adding 1, eventually the value will no longer be less than 5).

Note that the the last value printed is 4. This is because the conditional is checked before executing the loop body. So, after printing this is loop number 4, the value is incremented to 5 (on line 10). Then the conditional is checked. Since 5 < 5 is not true, the loop does not execute the body again and the program continues on line 13. We call the variable used to control the loop (in this case loopCount) the loop control variable

Step 3

A loop control variable does not need to be a number that is incremented. You can use any variable and condition. For example, we can control a loop with user input. Modify the program so that it looks like:

#include <stdio.h>

int main()
{
  int loopCount = 0;
  char userOption = 'y';

  while (userOption == 'y')
  {
    printf("this is loop number %d\n", loopCount);
    printf("Loop again? Enter y to continue and any other character to quit: ");
    scanf(" %c", &userOption);
    loopCount = loopCount + 1;
  }

  printf("loop complete\n");

  return 0;
}

Save and upload your file to the UMBC Linux server. Then compile and run it. When prompted, press y and hit enter. Do this a few times before typing some other character. For example:

this is loop number 0
Loop again? Enter y to continue and any other character to quit: y
this is loop number 1
Loop again? Enter y to continue and any other character to quit: y
this is loop number 2
Loop again? Enter y to continue and any other character to quit: y
this is loop number 3
Loop again? Enter y to continue and any other character to quit: n
loop complete

This is another common way to handle loop control - using some kind of user input for the control variable and letting the user control the logic.

Step 4

Modify your program so that it looks like:

#include <stdio.h>

int main()
{
  return 0;
}

Save and upload your file to the UMBC Linux server. Then compile and run it to make sure it works (it doesn't do anything yet, of course).

Now, modify the program so that it prompts the user for an integer. Then print all of the even integers that are less than the number the user provided. Here is a sample of what the output should look like:

Enter an integer: 10
0
2
4
6
8

Hint

Try to tackle this problem in stages. Perhaps make sure you're getting a value from the user correctly ( e.g. ask for the value then print it). Then set up the loop. Maybe at first, just print all the values less than the number the user provided. Then figure out how to make it print only even numbers.

Step 5

Once you complete Step 4 you can turn this assignment in. If you still need to work on your project, go ahead and do so now. You should still try to complete steps 5 and 6 on your own time. If you are done with Project 1, do steps 5 and 6 now. Either way, you don't have to turn in steps 5 and 6.

Modify your overtime pay program so that it prompts the user for hours worked and pay rate as before. However, after printing the first result it should ask the user if they want to continue. If they press y then repeat the prompt and calculation. If the press any other character, the program should exit.

Step 6

Write a program so that it prompts the user for an integer. Then print a number of rows equal to the number the user entered. On the first row, print a single *, on the second row print **, and so on... each time adding another star to the row. For example:

Enter an integer: 10
*
**
***
****
*****
******
*******
********
*********
**********
#include <stdio.h>
int main()
{
int valueFromUser = 0;
int currentValue = 0;
printf("Enter a non negative integer: ");
scanf("%d", &valueFromUser);
while (currentValue < valueFromUser)
{
printf("%d\n", currentValue);
currentValue = currentValue + 2;
}
return 0;
}
#include <stdio.h>
int main()
{
int valueFromUser = 0;
while (valueFromUser < 1)
{
printf("Enter a positive integer: ");
scanf("%d", &valueFromUser);
if (valueFromUser < 1)
{
printf("%d is not a positive integer\n", valueFromUser);
}
}
int rowNum = 1;
while (rowNum <= valueFromUser)
{
int columnNum = 1;
while (columnNum <= rowNum)
{
printf("*");
columnNum = columnNum + 1;
}
printf("\n");
rowNum = rowNum + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment