Tag Archives: Count
Python || Random Number Guessing Game Using Random MyRNG & While Loop
Here is another homework assignment which was presented in introduction class. The following is a simple guessing game using commandline arguments, which demonstrates the use of generating random numbers.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
How To Get User Input
Getting Commandline Arguments
While Loops
MyRNG.py - Random Number Class
==== 1. DESCRIPTION ====
The following program is a simple guessing game which demonstrates how to generate random numbers using python. This program will seed the random number generator (located in the file MyRNG.py), select a number at random, and then ask the user for a guess. Using a while loop, the user will keep attempting to guess the selected random number until the correct guess is obtained, afterwhich the user will have the option of continuing play or exiting.
==== 2. USAGE ====
The user enters various options into the program via the commandline. An example of how the commandline can be used is given below.
python3 guess.py [-h] [-v] -s [seed] -m 2 -M 353
Where the brackets are meant to represent features which are optional, meaning the user does not have to specify them at run time.
The -m and -M options are mandatory.
• -M is best picked as a large prime integer
• -m is best picked as an integer in the range of 2,3,..,M-1
NOTE: The use of commandline arguments is not mandatory. If any of the mandatory options are not selected, the program uses its own logic to generate random numbers.
==== 3. FEATURES ====
The following lists and explains the command line argument options.
• -s (seed): Seed takes an integer as a parameter and is used to seed the random number generator. When omitted, the program uses its own logic to seed the generator
• -v (verbose): Turn on debugging messages.
• -h (help): Print out a help message which tells the user how to run the program and a brief description of the program.
• -m (minimum): Set the minimum of the range of numbers the program will select its numbers from.
• -M (maximum): Set the maximum of the range of numbers the program will select its numbers from.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# ============================================================================= # Name: K Perkins # Date: Aug 6, 2013 # Taken From: http://programmingnotes.org/ # File: guess.py # Description: This is the guess.py module which uses a random number # generator to simulate a simple guessing game. This program will seed the # random number generator (located in the file MyRNG.py), select a number at # random, and then ask the user for a guess. The user will keep attempting # to guess the selected random number until the correct guess is obtained, # afterwhich the user will have the option of continuing play or exiting # ============================================================================= # Sample commandline: guess.py -s 3454 -m 1 -M 1000 import sys, pdb from MyRNG import * def Usage(status, msg = ""): # Function prints out usage directions aswell as a simple # message if a string is sent as a 2nd parameter if(msg): print(msg) print("nUSAGE:n ", sys.argv[0],"[-h help] [-v] [-s seed] [-m minimum number]", "[-M maximum number]") sys.exit(status) def IsWarmer(userGuess, numGuess, randomNumber): # Function determines if the current number the user guesses is closer # to the random number than the previous guess. # Function returns TRUE if current user guess is 'warmer' # than previous, otherwise returns FALSE currGuessDifference = userGuess[numGuess] - randomNumber currGuessDifference = math.fabs(currGuessDifference) prevGuessDifference = userGuess[numGuess-1] - randomNumber prevGuessDifference = math.fabs(prevGuessDifference) if(currGuessDifference < prevGuessDifference): return True else: return False def main(): # This is the 'main' function which first takes a string via the commandline # and parses it to determine various modes of operation, namely being # 'seed,' 'minimum,' and 'maximum.' After the commandline options # are obtained, that information is sent to the MyRNG class in order # to generate a random number. After a random number is found, using # a while loop, the user is prompted to try and guess that specified # number, repeatedly doing so until a correct guess is found # declare variables index = 0 # counter which is used to index the sys.argv string verbose = False choices = (("y"),("yes"),("n"),("no")) # This is to be used for the while loop seed = 806189064 # saves the seed from the command line minimum = 1 # saves the minimum num from the command line maximum = 1000 # saves the maximum num from the command line loop = True # this controls the while loop randomNumber = 0 # this saves the random number from the generator userGuess = [] # this saves the user guesses numGuess = 0 # this is the counter wgich keeps track of the num of usr guesses newGame = True # bool to determine if the user is playing a new game programDescr = """nDESCRIPTION: The following is a simple guessing game in which the user is prompted to guess a number and the computer determines if the guess is above, below or exactly the random number which was selected.""" # == determine if the user entered enough args via commandline == # if(len(sys.argv) < 1): #if not enough args, stop the program and print an error message Usage(1, "n** Must provide atleast 1 argument") # == parse thru the argv string to find the appropriate tokens == # for currentArg in sys.argv: if(currentArg == "-h"): # print out the usage message and exit. Usage(2, programDescr) elif(currentArg == "-v"): # set verbose mode to be true for debugging messages verbose = True elif(currentArg == "-s"): # set the seed here # if the user doesnt specify a seed, the # default is my CWID if((index+1 < len(sys.argv)) and (sys.argv[index+1].isdigit())): seed = int(sys.argv[index+1]) else: seed = 806189064 elif currentArg == "-m": # set the minimum here # if the user doesnt specify a min, the default is 1 if((index+1 < len(sys.argv)) and (sys.argv[index+1].isdigit())): minimum = int(sys.argv[index+1]) else: minimum = 1 elif currentArg == "-M": # set the maximum here # if the user doesnt specify a max, the default is 1000 if((index+1 < len(sys.argv)) and (sys.argv[index+1].isdigit())): maximum = int(sys.argv[index+1]) else: maximum = 1000 # increment the index counter index += 1 # print debugging messages if debug mode is on if(verbose): print ("nThis message only appears if verbose mode is turned on.") print (""" ** To continue seeing debugging messages, press the "n" button when prompted. To print the current value of variables, press the "p" button followed by the name of the variable you wish to print. Press the "l" button to visually see where you are in the programs souce code. To quit debugging, press the "c" button.n""") pdb.set_trace() print("nSeed = %d, Minimum = %d, Maximum = %d" %(seed, minimum, maximum)) # == declare the class object == # random = MyRNG(minimum, maximum) random.Seed(seed) randomNumber = random.Next() print("nI'm thinking of a number between %d and %d" ". Go ahead and make your first guess. " %(minimum, maximum)) # * this is the while loop which simulates a guessing game. # * the loop gets a number from the user and determines if the # user input is a "winner, warmer, or colder" in relation to the # random number which was generated. # * once the user guesses correctly, they have a choice of continuing # play or exiting the game. If they choose to play again, a new # random number is generated while(loop): userGuess.append(int(input(">> "))) if(newGame): newGame = False if((userGuess[numGuess] > randomNumber) or (userGuess[numGuess] < randomNumber)): print("nSorry that was not correct, please try again...n") elif((userGuess[numGuess] > randomNumber) or (userGuess[numGuess] < randomNumber)): if(IsWarmer(userGuess, numGuess, randomNumber)): print("nWARMERn") else: print("nCOLDERn") if(userGuess[numGuess] == randomNumber): print("nWINNER! You have guessed correctly!") print("It took you %d attempt(s) to find the answer!" %(numGuess+1)) del userGuess[:] numGuess = -1 answer = input("nWould you like to play again? (Yes or No): ") answer = answer.lower() if(answer in choices[:2]): randomNumber = random.Next() print("nMake a guess between %d and %dn" %(minimum, maximum)) newGame = True elif((answer in choices[2:]) or (answer not in choices[2:])): loop = False numGuess += 1 print("nThanks for playing!!") if __name__ == "__main__": main() # http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output:
Seed = 806189064, Minimum = 1, Maximum = 1000
I'm thinking of a number between 1 and 1000. Go ahead and make your first guess.
>> 500Sorry that was not correct, please try again...
>> 400
WARMER
>> 600
COLDER
>> 300
WARMER
>> 150
WARMER
>> 100
COLDER
>> 180
COLDER
>> 190
COLDER
>> 130
WARMER
>> 128
WINNER! You have guessed correctly!
It took you 10 attempt(s) to find the answer!Would you like to play again? (Yes or No): y
------------------------------------------------------------
Make a guess between 1 and 1000
>> 500
Sorry that was not correct, please try again...
>> 600
COLDER
>> 400
WARMER
>> 300
WARMER
>> 280
WARMER
>> 260
WARMER
>> 250
COLDER
>> 256
WINNER! You have guessed correctly!
It took you 8 attempt(s) to find the answer!Would you like to play again? (Yes or No): n
Thanks for playing!!
Java || Searching An Integer Array For A Target Value
Here is another actual homework assignment which was presented in an intro to programming class which was used to introduce more practice using integer arrays.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Integer Arrays
For Loops
Methods (A.K.A "Functions") - What Are They?
Final Variables
If/Else Statements
This is a small and simple program which demonstrates how to search for a target value which is stored in an integer array. This program first prompts the user to enter five values into an int array. After the user enters all the values into the system, it then displays a prompt asking the user for a search value. Once it has a search value, the program searches through the array looking for the target value; and wherever the value is found, the program display’s the current array index in which that target value is located. After it displays all the locations where the target value resides, it display’s the total number of occurrences the search value was found within the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
import java.util.Scanner; public class ArraySearch { // global variable declaration static Scanner cin = new Scanner(System.in); static final int NUM_INTS = 5; public static void main(String[] args) { // declare variables int searchValue = 0; int numOccurences = 0; int[] numValues = new int[NUM_INTS]; // int array size is initialized with a const value // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); // get data from user via a 'for loop' System.out.println("Please enter "+ NUM_INTS +" integer values:"); for (int index=0; index < NUM_INTS; ++index) { System.out.print("#" + (index + 1) + ": "); numValues[index] = cin.nextInt(); } // get a search value from the user System.out.print("Please enter a search value: "); searchValue = cin.nextInt(); System.out.println(""); // finds the number of occurences the search value was found in the array numOccurences = SearchArray(numValues, searchValue); // display data to user System.out.println("nThe total occurrences of value "+ searchValue + " within the array is: " + numOccurences); }// end of main // ==== SearchArray =========================================================== // // This method will take as input the array, the number of array // elements, and the target value to search for. The function will traverse // the array looking for the target value, and when it finds it, display the // index location within the array. // // Input: // limit [IN] -- the array, the number of array // elements, and the target value // // Output: // The total number of occurrences of the target value in the array // // ============================================================================ public static int SearchArray(int[] numValues, int searchValue) { int numFound=0; for (int index=0; index < NUM_INTS; ++index) { if (numValues[index] == searchValue) { System.out.println("t" + searchValue + " was found at array " + "index #" + index); ++numFound; // if the search values was found, // increment the variable by 1 } } return numFound; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output:
Note: The code was compiled 3 separate times to display the different outputs its able to produce
====== RUN 1 ======
Welcome to My Programming Notes' Java Program.
Please enter 5 integer values:
#1: 25
#2: 25
#3: 25
#4: 25
#5: 25
Please enter a search value: 2525 was found at array index #0
25 was found at array index #1
25 was found at array index #2
25 was found at array index #3
25 was found at array index #4The total occurrences of value 25 within the array is: 5
====== RUN 2 ======
Welcome to My Programming Notes' Java Program.
Please enter 5 integer values:
#1: 8
#2: 19
#3: 97
#4: 56
#5: 8
Please enter a search value: 88 was found at array index #0
8 was found at array index #4The total occurrences of value 8 within the array is: 2
====== RUN 3 ======
Welcome to My Programming Notes' Java Program.
Please enter 5 integer values:
#1: 78
#2: 65
#3: 3
#4: 45
#5: 89
Please enter a search value: 12The total occurrences of value 12 within the array is: 0
C++ || Class & Input/Output – Display The Contents Of A User Specified Text File To The Screen
The following is another intermediate homework assignment which was presented in a C++ programming course. This program was assigned to introduce more practice using the class data structure, which is very similar to the struct data structure.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Header Files - How To Use Them
Class - What Is It?
How To Read Data From A File
String - Getline
Array - Cin.Getline
Strcpy - Copy Contents Of An Array
#Define
This program first prompts the user to input a file name. After it obtains a file name from the user, it then attempts to display the contents of the user specified file to the output screen. If the file could not be found, an error message appears. If the file is found, the program continues as normal. After the file contents finishes being displayed, a summary indicating the total number of lines which has been read is also shown to the screen.
This program was implemented into 3 different files (two .cpp files, and one header file .h). So the code for this program will be broken up into 3 sections, the main file (.cpp), the header file (.h), and the implementation of the functions within the header file (.cpp).
Note: The data file that is used in this example can be downloaded here.
Also, in order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in
Documents > Visual Studio 2010 > Projects > [Your project name] > [Your project name]
======== FILE #1 – Main.cpp ========
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
// ============================================================================ // File: Main.cpp // ============================================================================ // This program tests the "CFileDisp" object. It prompts the user for an input // filename, then attempts to display the contents of that file to stdout. // After the file contents have been displayed, a summary line indicating the // total number of lines that have been displayed is written to stdout. // ============================================================================ #include <iostream> #include <fstream> #include "CFileDisp.h" using namespace std; // ==== main ================================================================== // // ============================================================================ int main() { CFileDisp myFile; char fname[MAX_LENGTH]; int numLines; // get the filename from the user cout << "Enter a filename: "; cin.getline(fname, MAX_LENGTH); // copy the user's filename into the file object myFile.SetFilename(fname); // have the object open the file myFile.OpenFile(); // if all is good and well... if(myFile.IsValid()==true) { numLines = myFile.DisplayFileContents(); // close the file myFile.CloseFile(); // write how many lines were displayed to stdout cout << "nt*** Total lines displayed: " << numLines << endl; } return 0; }// http://programmingnotes.org/ |
======== FILE #2 – CFileDisp.h ========
Remember, you need to name the header file the same as the #include from the Main.cpp file. This file contains the function declarations, but no implementation of those functions takes place here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
// ============================================================================ // File: CFileDisp.h // ============================================================================ // This is the header file which declares the objects which are used to open // a text file and display its contents to stdout. // ============================================================================ #ifndef CFILE_DISP_HEADER #define CFILE_DISP_HEADER #include <fstream> using namespace std; #define MAX_LENGTH 256 class CFileDisp { public: // constructor CFileDisp(); // member functions void SetFilename(char newFilename[]); /* Purpose: Copy the user's filename into the file object */ void OpenFile(); /* Purpose: Open's the file which is specified by the user */ bool IsValid(); /* Purpose: Checks if the file exists. Post: Returns false if file cannot be found */ int DisplayFileContents(); /* Purpose: Display's the file contents to stdout Post: Returns the total number of lines contained in the file */ void CloseFile(); /* Purpose: Closes the file */ // destructor ~CFileDisp(); private: bool m_bIsValid; char m_filename[MAX_LENGTH]; ifstream m_inFile; }; #endif // CFILE_DISP_HEADER // http://programmingnotes.org/ |
======== FILE #3 – CFileDisp.cpp ========
This is the function implementation file for the CFileDisp.h class. This file can be named anything you wish as long as you #include “CFileDisp.h”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
// ============================================================================ // File: CFileDisp.cpp // ============================================================================ // This file implements the functions which are declared in the CFileDisp // class, which is located in CFileDisp.h // ============================================================================ #include <iostream> #include <cstring> #include <string> #include "CFileDisp.h" using namespace std; CFileDisp::CFileDisp() { m_bIsValid = 0; }// end of CFileDisp void CFileDisp::SetFilename(char newFilename[]) { strcpy(m_filename,newFilename); }// end of SetFilename void CFileDisp::OpenFile() { m_inFile.open(m_filename); }// end of OpenFile bool CFileDisp::IsValid() { if (m_inFile.fail()) { cout << m_filename << " was not found...nn"; return false; } else { return true; } }// end of IsValid int CFileDisp::DisplayFileContents() { int total=0; string inLine; cout << endl; while(getline(m_inFile, inLine)) { cout << inLine << endl; ++total; } return total; }// end of DisplayFileContents void CFileDisp::CloseFile() { m_inFile.close(); }// end of CloseFile // this is the destructor CFileDisp::~CFileDisp() { m_bIsValid = 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Enter a filename: input_file_display_programmingnotes_freeweq_com.txt 346 130 982 90 656 117 595 415 948 126 4 558 571 87 42 360 412 721 463 47 119 441 190 985 214 509 2 571 77 81 681 651 995 93 74 310 9 995 561 92 14 288 466 664 892 8 766 34 639 151 64 98 813 67 834 369 This is a line of text! *** Total lines displayed: 10 |
C++ || Cash Register Simulation – Display The Total Sales Amount In Dollars & Cents Using Modulus
The following is a simple program which demonstrates more use of the modulus (%) function to manipulate integer data.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
This program first prompts the user to enter in a monetary amount into the system. This number can be a decimal number, or a whole number. Once the user enters in an amount, the program will use the modulus operator to determine exactly how many 1 dollar bills, quarters, dimes, nickles, and pennies consisted of the amount that the user entered into the program. So for example, if the user entered the value of 2.34, the program would display the result of 2 dollars, 1 quarters, 0 dimes, 1 nickels, and 4 pennies.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 28, 2012 // Taken From: http://programmingnotes.org/ // File: MakeChange.cpp // Description: The following is a simple program which demonstrates // how to make change. // ============================================================================ #include<iostream> using namespace std; int main() { // declare variables double initialAmount = 0; int remainingAmount = 0; int numberOfOneDollars = 0; int numberOfQuarters = 0; int numberOfDimes = 0; int numberOfNickels = 0; int numberOfPennies = 0; // Receive the amount cout << "Enter the total sales amount in dollars & cents (for example 19.87): "; cin >> initialAmount; // convert a 'double' to 'int' value remainingAmount = static_cast<int>(initialAmount * 100); // Find the number of one dollars numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount numberOfPennies = remainingAmount; // Display the results cout << "\nThe amount of $" << initialAmount << " consists of: \n" << "\t" << numberOfOneDollars << " dollar(s)\n" << "\t" << numberOfQuarters << " quarter(s)\n" << "\t" << numberOfDimes << " dime(s)\n" << "\t" << numberOfNickels << " nickel(s)\n" << "\t" << numberOfPennies << " pennie(s)\n"; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Note: the code was compile three separate times to display different output)
====== RUN 1 ======
Enter the total sales amount in dollars & cents (for example 19.87): 19.87
The amount of $19.87 consists of:
19 dollar(s)
3 quarter(s)
1 dime(s)
0 nickel(s)
2 pennie(s)====== RUN 2 ======
Enter the total sales amount in dollars & cents (for example 19.87): 11.93
The amount of $11.93 consists of:
11 dollar(s)
3 quarter(s)
1 dime(s)
1 nickel(s)
3 pennie(s)====== RUN 3 ======
Enter the total sales amount in dollars & cents (for example 19.87): 3.00
The amount of $3 consists of:
3 dollar(s)
0 quarter(s)
0 dime(s)
0 nickel(s)
0 pennie(s)
C++ || Random Number Guessing Game Using Srand, Rand, & Do/While Loop
This is a simple guessing game, which demonstrates the use of srand and rand to generate random numbers. This program first prompts the user to enter a number between 1 and 1000. Using if/else statements, the program will then check to see if the user inputted number is higher/lower than the pre defined random number which is generated by the program. If the user makes a wrong guess, the program will re prompt the user to enter in a new number, where they will have a chance to enter in a new guess. Once the user finally guesses the correct answer, using a do/while loop, the program will ask if they want to play again. If the user selects yes, the game will start over, and a new random number will be generated. If the user selects no, the game will end.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
// ============================================================================ // Author: Kenneth Perkins // Date: Jan 20, 2012 // Taken From: http://programmingnotes.org/ // File: guessingGame.cpp // Description: Demonstrates a simple random number guessing game // ============================================================================ #include <iostream> #include <ctime> #include <iomanip> using namespace std; int main() { // declare & initialize variables char playAgain = 'y'; int userInput = 0; int numGuesses = 0; // Seed the random number generator with the current time so // the numbers will be different every time the program runs srand(time(NULL)); int randomNumber = rand() % 1000+1; // display directions to user cout << "I'm thinking of a number between 1 and 1000. Go ahead and make your first guess.\n\n"; do{ // this is the start of the do/while loop // get data from user cin >> userInput; // increments the 'numGuesses' variable each time the user // gets the guess wrong ++numGuesses; // if user guess is too high, do this code if(userInput > randomNumber) { cout << "Too high! Think lower.\n"; } // if user guess is too low, do this code else if(userInput < randomNumber) { cout << "Too low! Think higher.\n"; } // if user guess is correct, do this code else { // display data to user, prompt if user wants to play again cout << "You got it, and it only took you " << numGuesses <<" trys!\nWould you like to play again (y/n)? "; cin >> playAgain; // if user wants to play again then re initialize the variables if(playAgain == 'y'|| playAgain =='Y') { // creates a line seperator if user wants to enter new data cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; numGuesses = 0; cout << "\n\nMake a guess (between 1-1000):\n\n"; // generate a new random number for the user to try & guess randomNumber = rand() % 1000+1; } } }while(playAgain =='y' || playAgain =='Y'); // ^ do/while loop ends when user doesnt select 'Y' // display data to user cout<<"\n\nThanks for playing!!"<<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output:
I'm thinking of a number between 1 and 1000. Go ahead and make your first guess.
67
Too low! Think higher.
500
Too low! Think higher.
700
Too high! Think lower.
600
Too low! Think higher.
680
Too high! Think lower.
650
Too low! Think higher.
660
Too low! Think higher.
670
You got it, and it only took you 8 trys!
Would you like to play again (y/n)? y------------------------------------------------------------
Make a guess (between 1-1000):
500
Too low! Think higher.
600
Too low! Think higher.
700
Too low! Think higher.
900
Too high! Think lower.
800
Too high! Think lower.
760
Too high! Think lower.
740
Too high! Think lower.
720
Too high! Think lower.
700
Too low! Think higher.
710
Too high! Think lower.
705
Too high! Think lower.
701
Too low! Think higher.
702
Too low! Think higher.
703
Too low! Think higher.
704
You got it, and it only took you 15 trys!
Would you like to play again (y/n)? nThanks for playing!!
C++ || Searching An Integer Array For A Target Value
Here is another actual homework assignment which was presented in an intro to programming class.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
This is a small and simple program which demonstrates how to search for a target value that is stored in an integer array. This program prompts the user to enter five values into an int array. After the user has entered all the values, it displays a prompt asking the user for a search value. Once it has the search value, the program will search through the array looking for the target; wherever the value is found, it will display the index location. After it displays all the locations where the value is found, it will display the total number of occurrences the search value was found within the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
// ============================================================================ // File: ArraySearch.cpp // ============================================================================ // // Description: // This program allows the user to populate an array of integers with five // values. After the user has entered all the values, it displays a prompt // asking the user for a search value. Once it has the search value, the // program will search through the array looking for the target; wherever the // value is found, it will display the index location. After it displays all // the locations where the value is found, it will display the total number // of occurrences the search value was found within the array. // // ============================================================================ #include <iostream> using namespace std; // constant variable const int NUM_INTS = 5; // function prototypes int SearchArray(int numValues[], int searchValue); // ==== main ================================================================== // // ============================================================================ int main() { // declare variables int searchValue; int numOccurences = 0; int numValues[NUM_INTS]; // int array size is initialized with a const value // get data from user via a 'for loop' cout << "Please enter "<< NUM_INTS <<" integer values:nn"; for (int index=0; index < NUM_INTS; ++index) { cout << "#" << index + 1 << ": "; cin >> numValues[index]; cout <<endl; } // get a search value from the user cout << "Please enter a search value: "; cin >> searchValue; cout <<endl; // finds the number of occurences the search value was found in the array numOccurences = SearchArray(numValues, searchValue); // display data to user cout << "nThe total occurrences of value " << searchValue << " within the array is: " << numOccurences; cout << endl << endl; return 0; }// end of main // ==== SearchArray =========================================================== // // This function will take as input the array, the number of array // elements, and the target value to search for. The function will traverse // the array looking for the target value, and when it finds it, display the // index location within the array. // // Input: // limit [IN] -- the array, the number of array // elements, and the target value // // Output: // The total number of occurrences of the target in the array // // ============================================================================ int SearchArray(int numValues[], int searchValue) { int numFound=0; for (int index=0; index < NUM_INTS; ++index) { if (numValues[index] == searchValue) { cout << "t" << searchValue << " was found at array index #" << index << endl; ++numFound; // if the search values was found, // increment the variable by 1 } } return numFound; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output:
Note: The code was compiled 3 separate times to display the different outputs its able to produce
Please enter 5 integer values:
#1: 12
#2: 12
#3: 12
#4: 12
#5: 12
Please enter a search value: 1212 was found at array index #0
12 was found at array index #1
12 was found at array index #2
12 was found at array index #3
12 was found at array index #4The total occurrences of value 12 within the array is: 5
-------------------------------------------------------------------------Please enter 5 integer values:
#1: 12
#2: 87
#3: 45
#4: 87
#5: 33
Please enter a search value: 8787 was found at array index #1
87 was found at array index #3The total occurrences of value 87 within the array is: 2
-------------------------------------------------------------------------Please enter 5 interger values:
#1: 54
#2: 67
#3: 98
#4: 45
#5: 98
Please enter a search value: 123The total occurrences of value 123 within the array is: 0
C++ || Count The Total Number Of Characters, Vowels, & UPPERCASE Letters Contained In A Sentence Using A ‘While Loop’
This program will prompt the user to enter a sentence, then upon entering an “exit code,” will display the total number of uppercase letters, vowels and characters contained within that sentence. This program is very similar to an earlier project, this time, utalizing a while loop, the setw and setfill functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#include <iostream> #include <iomanip> using namespace std; int main() { // declare variables int numUpperCase = 0; int numVowel = 0; int numChars = 0; char character = ' '; cout << "Enter a sentence: "; // Get sentence from user utilizing while loop while(cin >> character && character != '.') { // Checks to see if inputted data is UPPERCASE if ((character >= 'A')&&(character <= 'Z')) { ++numUpperCase; // Increments Total number of uppercase by one } // Checks to see if inputted data is a vowel if ((character == 'a')||(character == 'A')||(character == 'e')|| (character == 'E')||(character == 'i')||(character == 'I')|| (character == 'o')||(character == 'O')||(character == 'u')|| (character == 'U')||(character == 'y')||(character == 'Y')) { ++numVowel; // Increments Total number of vowels by one } ++numChars; // Increments Total number of chars by one } // end loop // display data using setw and setfill cout << setfill('.'); // This will fill any excess white space with period within the program cout <<left<<setw(36)<<"ntTotal number of upper case letters:"<<right<<setw(10) <<numUpperCase<<endl; cout <<left<<setw(36)<<"tTotal number of vowels:"<<right<<setw(10) <<numVowel<<endl; cout <<left<<setw(36)<<"tTotal number of characters:"<<right<<setw(10) <<numChars<<endl; return 0; }// http://programmingnotes.freeweq.com |
QUICK NOTES:
The highlighted portions are areas of interest.
In order to use the setfill and setw functions, remember to #include iomanip, as noted on line 2.
Notice line 17 contains the while loop declaration. The loop will continually ask the user to input data, and will not stop doing so until the user enters an exit character, and the defined exit character in this program is a period (“.”). So, the program will not stop asking the user to enter data until they enter a period.
Once compiling the above code, you should receive this as your output
Enter a sentence: My Programming Notes Is Awesome.
Total number of upper case letters:.........5
Total number of vowels:....................11
Total number of characters:................27