Friday, November 18, 2016

Array, Enum, Function, Typedef



In this example, we have everything we learned in chapters 7 and 8. 

You should have the breakpoints set as shown below and run the code in debugger to visualize how the array is filled and how it is processed one element at a time.

 

#include<iostream>
#include<time.h>
#include<string>
#include<iomanip>

using namespace std;

namespace zoltan{
    enum models{ TOYOTA, FORD, CHEVY, MAZDA, PORSCHE };
    enum colors{ RED, YELLOW, BLUE, BLACK };
    typedef int dealerships[PORSCHE + 1][BLACK + 1];
}
using namespace zoltan;

void fillArray(int [][BLACK+1]);
int totalColor(dealerships,colors);
int totalModel(dealerships,models);
string decodeColor(colors);
string decodeModel(models);

int main(){
    cout << "Hello Enum based Arrays" << endl;
    int dealership[5][4] = { { 2, 3, 4, 5  },
                           { 3, 4, 5, 6  },
                           { 5, 6, 7, 8  },
                           { 7, 8, 9, 10 },
                           { 1, 2, 3, 4  } };
    zoltan::dealerships richland;
    fillArray(richland);
    int color=totalColor(dealership,BLUE);
    int model=totalModel(richland,PORSCHE);
  
    cout << setw(11) << " ";
    for (colors col = RED; col <= BLACK; col = static_cast <zoltan::colors>(col + 1))
        cout <<setw(8)<< decodeColor(col);
    cout << endl;

    for (models row = TOYOTA; row <= PORSCHE; row = static_cast <models>(row + 1)){
        cout << setw(10) << decodeModel(row) << ":";
        for (colors col = RED; col <= BLACK; col = static_cast <zoltan::colors>(col + 1)){
            cout << setw(8)<<richland[row][col];
        }
        cout << endl;
    }

    return 0;
}
void fillArray(dealerships passedArray){
    srand(time(NULL));
    for (models row = TOYOTA; row <= PORSCHE; row = static_cast <models>(row + 1))
    for (colors col = RED; col <= BLACK; col = static_cast <zoltan::colors>(col + 1))   //you can use the namespace or not
        passedArray[row][col] = rand() % 50;
}
int totalColor(dealerships d, colors c){  //Process by column
    int total = 0;
    for (models row = TOYOTA; row <= PORSCHE; row = static_cast <models>(row + 1))
        total+=d[row][c];
    return total;
}
int totalModel(dealerships d, models m){  //process by row
    int total = 0;
    for (zoltan::colors col = RED; col <= BLACK; col = static_cast <zoltan::colors>(col + 1))
        total+=d[m][col];
    return total;
}

string decodeColor(colors c){
    switch (c){
        case RED: return "red";
        case YELLOW: return "yellow";
        case BLUE: return "blue";
        case BLACK: return "black";
    };
}

string decodeModel(models m){
    switch (m){
    case TOYOTA: return "toyota";
    case FORD: return "ford";
    case CHEVY: return "chevy";
    case MAZDA: return "mazda";
    case PORSCHE: return "porsche";
    }
}

Wednesday, November 9, 2016

Place value of Integer digits

The process of program development starts with understanding the problem.
Problem: Find the highest place value exponent in a Base-10 integer.
Pre-requisite: i.e. 9,448,320,743 You may say, what does the 9 represent? (billion) what does the 4 next to the 9 represent? (hundred million) what number is in the hundred thousand's place?(3)
Base-10 123456 number is written as 1(100,000)+2(10000)+3(1000)+4(100)+5(10)+6(1) and that is 1(10^5)+2(10^4)+3(10^3)+4(10^2)+5(10^1)+6(10^0)
Analysis: In order to find the largest place value, we need to find the largest exponent of base 10.
We can find the highest exponent if we divide the integer by 10^exp where exp = {0,1,2,3,...}

i.e. 46578


num exp 10exp num/10exp
123456 0 1 123456
1 10 12345
2 100 1234
3 1000 123
4 10000 12
5 100000 1
6 1000000 0
7 10000000 0
As you can see, we can find the highest exponent as soon as the result of the division is between 1 and 9.  So, we could solve this problem by iterating in a loop with an increment exp until the division result is between 1 and 9.

Design: Design involves creating a pseudo code or flow chart in order to develop the algorithm.

 start
   output "Welcome"
   output "Enter a number"
   input as num
   if input not a number then
       output  "Error: Better luck next time."
       return 1
   endif
   call findExp use num
   output "The exponent in: "
   output "Thanks for using my program."
stop

start findExp reference myNum
   call abs using myNum as myNum
   declare exp = 0
   while myNum / 10^exp > 10 then
      exp=exp+1
   endhile
   myNum = exp
return


Code: Now, that we have the basic idea, you can pick the language and code the problem.

#include<iostream>
#include<cmath>

using namespace std;
void findExp(int& num);

int main(){
    int num,exp;
    cout << "Welcome" << endl;
    cout << "Enter a number: ";
    cin >> num;
    if (!cin){              //validating user input
        cout << "Error: Better luck next time." << endl;
        return 1;
    }

    findExp(num);          //function call
    cout << "The exponent in: " << num << endl;
    cout << "Thanks for using my program." << endl;

    return 0;
}
void findExp(int& myNum){
    myNum = abs(myNum);
    int exp = 0;

    while (myNum / pow(10, exp) > 10){
        exp++;
    }
    myNum= exp;      //setting the new value to the referenced value
}

Saturday, August 29, 2015

Code and the modern IDE

What is the difference between

#‎include‬ <stdio.h> 

int main(){ 
     char name[40]; 
     gets(name); 
     if((int) sizeof(name) > 39*4){ 
         printf("Something went wrong!!!"); 
        }
      else{ 
         printf("%s\n", name); 
        } 
}

and

#‎include‬ <stdio.h> 

int main(){ 
     char name[40]; 
     gets_s(name); 
     if((int) sizeof(name) > 39*4){ 
         printf("Something went wrong!!!"); 
        }
      else{ 
         printf("%s\n", name); 
        } 
}

Not much, the first example is an example of a primitive way to check the input for buffer overflow condition.  Unfortunately, the function gets() has a buffer overflow condition problem, so it is useless to rely on this function for checking the length of the input.  Programmers should use gets_s() function call instead.  These days, modern IDEs will check for old and deprecated functions that are not secure to use, so programmers will not make these kind of mistakes.  For example, Visual Studio, I used VS2013 in this example, will not even allow the re-processor to compile this code into an executable unless we force the code of the compiler to ignore security checking.


Why would someone run this command if the previous code was compiled as driver.exe?
python -c "print '\x42'*41" | driver.exe
 
Note: In order to compile the first example code, you might have to turn off error messages that might not allow you to compile it.  This can be done in the project's property ( see image below ) or by adding the code below before the pre-processor to the project in Visual Studio.

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
 

Wednesday, April 1, 2015

Challenge Question 1: Loop ( break / continue )

What does this code do?

#include<iostream>

using namespace std;

int main(){
    int MAX = 50;
    int counter = 0;

    while (counter++ < MAX){
        if (counter % 2 != 0)
            continue;

        cout << counter << endl;
       
        if (counter == 20)
            break;
    }
    return 0;
}

Tuesday, March 3, 2015

Random numbers

See the randomness of C++ generated random numbers by providing a fixed seed and a random seed.  Gather the numbers in may trials and chart the results.  Charts will give you an easier way to identify patterns to evaluate the randomness.  You should modify this code to write the values to a file and import them into Excel or OO Calc to chart.

Basic steps for file implementation:
#import<fstream>

ofstream outFile;
outfile.open("output.txt");
outfile<<zero<<one<<two<<three<<four<<endl;
outfile.close();

More details:
http://intro2cs-cpp.blogspot.com/2015/03/simple-file-io.html

Code to test randomness:
//Name: <Your Name>
//Class: 2012 Fall - COSC 1415/1436.8002
//Project 0: Random Number
//Revision: 1.0
//Date: 08/15/2012
//Description: This program show the concept of random  number generation

#include <iostream>   //string input/output header file
#include<time.h>

using namespace std;  //standard class library

int main(){
  srand ( time(NULL) );         //replace the seed with a fixed number a see the effects
  int zero=0,one=0, two=0, three=0, four=0;
for(int i=0;i<10000;i++){
  Richland = rand() % 5;
  switch(Richland){
  case 0:  zero++;   break;
  case 1:  one++;    break;
  case 2:  two++;    break;
  case 3:  three++;  break;
  case 4:  four++;   break;
  }
}
cout<<"The value of zeroes: "<<zero<<endl;
cout<<"The value of ones: "<<one<<endl;
cout<<"The value of twos: "<<two<<endl;
cout<<"The value of threes: "<<three<<endl;
cout<<"The value of fours: "<<four<<endl;

  system("pause");                           //pause the program so I can read the console 
  return 0;                                  //return 0 to show end of execution 
}

Monday, March 2, 2015

Simple File I/O

This code should give you a simple recipe type of instruction to learn how to handle file input and output operations.  The biggest challenge is to understand your file system navigation with Windows Explorer and the location of your source files.

Create an input file with a simple editor like Notepad.exe and make sure you know where you save the input file to.  Do not use spaces in creating the input file name.  also, understand the input file name does not have to match the ifstream variable name.  You can name your input file anything you'd like, just type the same file name when you open the file in your code.

In this example, the input_file.txt content is 92A98.76.

Start with a skeleton program like this one and place your pseudo code into the skeleton program as comments.

Write pseudo code 
1. Include strings in case if we need to specify a string for a file name
2. This library is needed for handling file input and output,  ifstream, ofstream
    Declare variables to store data read from file
3. Declare input file variable
4. Declare output file variable
4.1 Make sure there is an input file with proper data ( read only ) and your userID has write access to output location
5. Open input and output files.  The input file should be placed on the same path with your source code.  The output file will be written into the same path as your source code.
     if you need to specify a path to the file, escape the backslash
6. Use filestream variables like we use iostream variables
7. Close input and output files

Create actual skeleton program with pseudo code copied in as comments

#include <iostream> //cin, cout, endl

 //1. include strings in case if we need to specify a string for a file name
 //2. this library is needed for handling file input and output,  ifstream, ofstream


using namespace std;

int main()
{
//Declare variables to store data read from file
   
//3. declare input file variable

//4. declare output file variable

//4.1 make sure there is an input file with proper data ( read only ) and your userID has write access to output location

//5. open input and output files.  The input file should be placed on the same path with your source code.  The output file will be written into the same path as your source code.
     //if you need to specify a path to the file, escape the backslash

//6. use filestream variables like we use iostream variables
    //cin >> x >> grade >> y;

    /*    cout << "Your test score is: " << x << endl;
        cout << "Your letter grade is: " << grade << endl;
        cout << "Your class average is" << y << endl;        */

//7. close input and output files


    return 0;
}

Complete the code by first writing the cin/cout way of reading and printing values and change that to ifstream and ofstream variables later.

#include <iostream> //cin, cout, endl

#include <string>  //1. include strings in case if we need to specify a string for a file name
#include <fstream> //2. this library is needed for handling file input and output
                   //   ifstream, ofstream

using namespace std;

int main()
{
//Declare variables to store data read from file
    char grade;
    int x;
    float y;
   
//3. declare input file variable
    ifstream inFile;

//4. declare output file variable
    ofstream outFile;

//4.1 make sure there is an input file with proper data ( read only ) and your userID has write access to
     // output location


//5. open input and output files
    inFile.open("c:\\dell\\input_file.txt");  //if you need to specify a path to the file, escape the backslash
    outFile.open("c:\\temp\\output.txt");

//6. use filestream variables like we use iostream variables
    //cin >> x >> grade >> y;

    inFile >> x >> grade >> y;

    /*    cout << "Your test score is: " << x << endl;
        cout << "Your letter grade is: " << grade << endl;
        cout << "Your class average is" << y << endl;        */
   

    outFile << "Your test score is: " << x << endl;
    outFile << "Your letter grade is: " << grade << endl;
    outFile << "Your class average is" << y << endl;

//7. close input and output files
    inFile.close();
    outFile.close();

    return 0;
}

Compile the code by placing break points before and after the read operations.  Read the values for the variables before and after the read operations to identify problems with your input file.  Note: Later on, we'll learn how to validate input and code proper exit if the input or output files can not be manipulated.

if(!inFile){                                                              //validate input
    cout<<"Input file can not be located!"<<endl;
    return 2;                         //return a value to indicate error condition                                                  
}

if(!outFile){                                                             //validate output
    cout<<"You do not have enough space to store the output or you do not have right to write output at this location!"<<endl;
    return 4;                        //return a different value to indicate error condition

}

Read file into a c_string one line at a time.

ifstream inFile;
inFile.open("input.txt");
const int SIZE = 30;
 

if (!inFile){
     cout << "Input file was not found.";
     return 2;
}
 

char lineRead[SIZE];

while (!inFile.eof()){                                         //check to see if the end of the file is reached
          inFile.getline(lineRead, SIZE-1, '\n');
          cout << lineRead << endl;
}
 

inFile.close();

Read lines in a loop and make sure the first line is not empty before entering the loop.

    ifstream inFile;
    inFile.open("input.txt");
    const int SIZE = 30;
    if (!inFile){
        std::cout << "Input file was not found.";
        return 2;
    }
    char lineRead[SIZE];
    inFile.getline(lineRead, SIZE - 1, '\n');
    while (!inFile.eof() && lineRead[0]!='\0'){    //

        std::cout << lineRead << endl;
        //for (char ch : lineRead) cout << ch << endl;           //if you want to see each character read
        inFile.getline(lineRead, SIZE - 1, '\n');
    }
    inFile.close();

Sunday, February 22, 2015

Getting started

What is the output of string INSTITUTION = "Richland \rCollege"; ?  There is also a major implementation problem with this code that you should be able to find it easy.

//Project 0: Hello World
//Revision: 1.0
//Date: 08/15/2011
//Description: Chapter 2 Summary

#include <iostream>
#include <string>
#include <math.h>
#include"header.h"

using namespace std;
using namespace richland;

int main(){

    string INSTITUTION = "Richland \rCollege";
    cout << INSTITUTION << endl;

    float PI = 3.14E0;
    cout << PI << endl;

    int value = -200;

    cin >> celsius>>value;

    fahrenheit = (float)((celsius)*(9 / 5) + 32);

    cout << fahrenheit<< endl;

    float ans = (fahrenheit - 32)*(5 / 9);

    cout << ans << endl;

    char ch = 'A';
    cout << "The \"value\" is: " <<ch<< endl;
    cout << "The value is: " << ch+1 << endl;
    cout << "The value is: " << static_cast<char>(ch+1)<< endl;

    string hello = "Hello";

    hello[3] = 'p';

    cout << "The \nstring \tis: " << hello << endl;

    return 0;
}