EECS168:Lab4

From ITTC
Jump to: navigation, search
Navigation
Home
Information

Syllabus
Schedule
Exam Reviews

Classwork

Labs
Submitting Work

Due Time

This lab is due by 11:59pm July 3rd

Lab conduct

  • Do not use any unauthorized aid, such sites like rentacoder or chegg to obtain answers
  • Do not use code provided by another student
  • Do not reuse code (by you or anyone) from prior semesters
  • If you need help, seek it from:
    • Your lab TA.
    • Me, Dr. Gibbons, my email is jwgibbo@ku.edu / jwgibbo@gmail.com
  • If equipment you don't own (e.g. cycle servers) needs attention or you're having account issues put in a ticket!


Nested For loops

A nested loop is when a loop is inside of another loop. You have already done board works where a while loop contains a for loop. But what happens when a for loop contains another for loop? Well, the rules for a loop haven't changed. The outer loop, the one with i, will repeat whatever code is inside. It just so happens that the code being repeated is another loop, the one with j. What does this mean? It means that the inner loop, the one with j, will be repeated, in this case, 4 times.


for (int i = 0; i < 4; i++)
{
    for (int j = 0; j< 3; j++)
    {
         std::cout << "i = " << i << " and j = " << j << "\n"; 
    }
    std::cout << '\n';
} 

This code will output:

i = 0 and j = 0
i = 0 and j = 1
i = 0 and j = 2
i = 1 and j = 0
i = 1 and j = 1
i = 1 and j = 2
i = 2 and j = 0
i = 2 and j = 1
i = 2 and j = 2
i = 3 and j = 0
i = 3 and j = 1
i = 3 and j = 2

Notice how the inner loops completes all of its iterations before the outer completes a single iteration.


Array Basics

An array is used to store a collection of data, or we can think as a collection of variables of the same data type. Instead of declaring individual variables such as number1, number2, ... , and number99, we declare one array variable, numbers and use numbers[0], numbers[1], ..., and numbers[99]. The usage of array data structure in C++ is as shown below;

You can create arrays in one of two places in memory, on the call-stack or on the heap.

When to make a stack-allocated array

  • When the size of the array is known at compile time

When to make a heap-allocated array

  • When the size of the array is known at runtime
double myNums[5]; //array created on call-stack

I can also use a const int as the size of a stack-allocated array

const int SIZE = 5; 
double myNums[SIZE]; //array created on call-stack
//Example of declaration for a pointer
// Make sure you include the argument -std=C++11 in your make file if you would like to use nullptr.
double* myNums = nullptr;

//Example of creating a heap allocated array size 5
myNums = new double[5];


In either case, the syntax to use an array is the same.

//Example of initializing all value to 0.0

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

//Example of assigning values one at a time
myNums[0] = 10.0;
myNums[1] = 20.0;
myNums[2] = 30.0;
myNums[3] = 40.0;
myNums[4] = 50.0;

</code>


Heap-allocated arrays must be deleted at the end of main. Stack-allocated arrays are automatically deleted.

//Example deleting an array when.
//Will come at the end of main
   //code from previous examples
   delete[] myList;
   return(0); //end of main

Another neat thing about heap-allocated arrays is that their sizes can be a variable. That's not to say their sizes can change, which they can't, but we can use a variable as the size of the array.


int userSize = 0;
int* nums = nullptr; //not referring to an array yet
std::cout << "Hey user, how big should the array be?: ";
std::cin >> userSize; 

nums = new int[userSize];


Arrays do not have a built in property to check their length. You'll need to have a variable to keep track of this.

int size = 5; //This doesn't need to const because heap allocated array sizes
              //can be variables
int* nums = new int[size];

for(int i = 0; i < size; i++)
{
   //access the array for needed operation
}


Myths about arrays

  • You can change the size of an array
    • Wrong! Once an array is created it's size cannot change, but you can create new array of a different size and copy any desired value over

File Input Basics

This lab will require you read values in from a file. Luckily, it's similar to terminal input and output.

Setup:

//Include the fstream library
#include <fstream>
#include <iostream>

int main()
{
  int x=0;
  int y=0;
  int z=0;
  std::ifstream inFile; //create a variable of type std::ifstream. It will enable reading from files.
  inFile.open("someFile.txt"); //open a file that has values in it
  
  //Check if file is open
  if(inFile.is_open())
  {
    inFile >> x; //Read a value from the file and put it in the variable x
    inFile >> y; //Read a value from the file and put it in the variable y
    inFile >> z; //Read a value from the file and put it in the variable z
  
    std::cout << "x = " << x << '\n';
    std::cout << "y = " << y << '\n';
    std::cout << "z = " << z << '\n';

    inFile.close(); //we're done using the file.
  }
  else
  {
     std::cout << "File could not be opened!\n";
  }
  return(0);
}

For this to work, you need to create a file called "someFile.txt" and place it in the same folder as this main.cpp.

File Output Basics

Just like file input, file output is similar to terminal output.

Setup:

//Include the fstream library
#include <fstream>
#include <iostream>

int main()
{
     std::ofstream myOutFile;
     std::string fileName = "myOutputFile.txt";
     myOutFile.open(fileName); //You can pass in strings if you want

     int x = 99;
     
     //Put some stuff in the file
     myOutFile << "Text!\n"; //Just like cout, you pick when newline occur
     myOutFile << 42 << '\n'; //Numbers and characters!
     myOutFile << x << '\n'; //Variables!
     

     myOutFile.close(); //VERY important to do with output files
     
     return(0);

}

Checking for Memory Leaks

An easy way to check for memory leaks is to use a program called valgrind. It's a program that you can hand your lab off to and it will run your lab and tell if you have any memory leaks.

valgrind --leak-check=full --show-leak-kinds=all ./YourProgram


Example of running your program with valgrind:

valgrind --leak-check=full --show-leak-kinds=all ./progNameHere

It will tell you if any leaks occurred. Make sure you have the -g flag in your Makefile and you'll get the added bonus of see what lines of code created an object that was never deleted. Science!


See the Makefile tutorial for an example.

Exercise 1: Rook Path Visualizer

Rook Path

Present the user with a menu for picking the size of an nXn chess board and the position of a lone Rook. The positions will range from 0 up to, but not including, n. Obtain the row then the column. You will then print the nxn board displaying where the Rook could travel.


Use the following format for the board:

  • In the column, display | (the same symbol used in logical or)
  • In the row, display - (dash)
  • In the exact position of the Rook, display a capital R
  • Display *s everywhere else.

Recall that Rooks can move vertically and horizontally from edge to edge on the board.

Example where n=5 and position of the Rook is (1,3)

 ***|*
 ---R-
 ***|*
 ***|*
 ***|*

Example where n=5 and position of the Rook is (4,2)

 **|**
 **|**
 **|**
 **|**
 --R--


Exercise 2: Basic Numeric Computation

  1. Create an array of 5 doubles. (We know the size at compile time, where do you want to allocate this?)
  2. Now that you have an array, we need to get values. Create a loop that will ask the user to input values for the array. Display the values back to the user after you obtain all of them. Test this before moving on.
  3. Calculate sum, average, min, and max for the array of doubles.
Please enter 5 numbers
Input a number into your array: 10.0
Input a number into your array: 6.0
Input a number into your array: 4.0
Input a number into your array: 0.0
Input a number into your array: 15.0
Here are all the numbers in your array: 
10.0
6.0
4.0
0.0
15.0
The sum of all the values is: 35.0
The average of all the values is: 7.0
The largest value is : 15.0
The smallest value is : 0.0

Exercise 3: Arrays with File Input

Create an empty text document name "input.txt" and copy the example contents from below:

5
105
15
20
35
47

The first value in the file tells you how many ints (the type must be int!) are in the file. The rest of the values are the ints you want to store.


Create a program that reads in the first value, always an int, that tells you how many values are in the file. Then, create an array to store all of those values.


After you've read in the values display them to the screen in the following format:

Contents of input.txt:
[105, 15, 20, 35, 47]

Input a value to search for: 

The search prompt obtains a value from the user and confirms whether or not it is in the array.

Example:

Contents of input.txt:
[105, 15, 20, 35, 47]

Input a value to search for: 5
5 is not in the array.
Do you wish to quit (y/n): n
Input a value to search for: 105
105 is in the array.
Do you wish to quit (y/n): y

Let the user search as many times as they want.


Lab Submission

  • Your tarball and the directory inside it should be named like Smith-123456-Lab-4
  • DO NOT put your .o or executable files in your package.
  • Ask your TA if they use Blackboard or email

Rubric

  • [30pts] Rook Path
    • [15pts] Column path displayed correctly
    • [10pts] Row path displayed correctly
    • [5pts] Size of board determined by user
  • [20pts] Array Basics
  • [40pts] Array with File I/O
    • [10pts] Displays original array in proper format
    • [15pts] Array is searchable
    • [15pts] User can search multiple times
  • [5pts] Output is as clean, as in examples
  • [5pts] No Memory leaks