Daily c++ problems

Pages: 123... 5
I've always seen a lot of forum users asking for daily problems to help improve their coding skills and refreshing memory. This post will include one problem a day devoted to c++, it will include the subject and relative difficulty(according to me). I hope to keep this as a lasting thread that i will update daily for you guys, enjoy! Feel free to post your solutions on this thread(to be used in the answer thread), ill be sure to include your name before the code.


7/18/12 Subject: Strings Difficulty: Easy

Write a program that prompts the user to input a string. The program then uses the function substr to remove all the vowels from the string. For example, if str = "There", then after removing all the vowels, str = "Thr". After removing all the vowels, output the string. Your program must contain a function to remove all the vowels and a function to determine whether a character is a vowel.


7/19/12 Subject: Arrays and Strings Difficulty:Intermediate

The history teacher at your school needs help in grading a true/false test. The students' IDs and test answers are stored in a text file. The first entry in the file contains answers to the test in the form:


Every other entry in the file is the studentID, followed by a blank, followed by the student's responses. For example, the entry:


Indicated that the student ID is ABC 54301 and the answer to question 1 is true, the answer to question 2 is false, and so on. This student did not answer question 9. The exam has 20 questions, and the class has more than 150 students. Each correct answer is awarded two points, each wrong answer gets one point deducted and no answer gets zero points. Write a program that processes the test data. The output should be the student's ID, followed by the answers, followed by the test score, followed by the test grade. Assume the standard grade scale (90-100 -- a) (80-89 -- b) etc..etc..


7/20/12 Subject:Structs Difficulty: Intermediate

Write a program to help a local restaurant automate its breakfast billing system. The program should do the following:
a. Show the customer the different breakfast items offered by the restaurant
b. Allow the customer to select more than one item from the menu.
c. Calculate the bill

Assume the restaurant offers the following breakfast items:
Plain Egg.............1.45
Bacon and Egg....2.45
French Toast.......1.99
Fruit Basket.........2.49

Define a struct menuItemType with two components to hold the name and price of an item. Use an array, menuList, of the menuItemTypes. Your program must contain at least the following functions:
[] Function GetData: This function loads data into the array
[] Function ShowMenu: Displays items offered by restaurant and tells user how to select items.
[] Function printCheck: calculates and prints check(Note that the billing amount should include a 5% tax)

Format your output with 2 decimal places. The name of each item in the output must be left justified. You may assume that the user selects only one of a particular item.


7/21/12 Subject:Classes Difficulty:Easy

Write a program that converts a number entered in Roman numerals to decimal. Your program should consist of a class, say, romanType. An object of type romanType should do the following:

a store the number as a Roman numeral

b convert and store the number into decimal form

c print the number as a roman numeral or decimal number as requested by the user

The decimal values of the Roman numerals are:
M 1000
D 500
C 100
L 50
X 10
V 5
I 1

d test your program using the following Roman numerals: MCXIV, CCCLIX, MDCLXVI


7/22/12 Subject: Inheritance Difficulty: Hard

Part 1:
a point in the x-y plane is represented by its x-coordinate and y-coordinate. Design a class, pointType, that can store and process a point in the x-y plane. You should then perform operations on the point, such as setting the coordinates of the point, printing the coordinates and returns the x/y coordinate.

Part 2:
Every circle has a center and a radius. Given the radius, we can determine the circle's area and circumference. Given the center, we can determine its position in the x-y plane. The center of the circle is a point in the x-y plane. Design a class, circleType, that can store the radius and center of a circle. Because the center is in the x-y plane, you must derive the class circleType from pointType. You should be able to perform the usual operations on the circle, such as setting the radius, printing the radius, calculation and printing the area and circumference, and carrying out the usual operations on the center . Write a program to test various operations on a circle.


7/23/12 Subject: Overloading & Templates Difficulty: Hard
Recall that in C++ there is no check on an array index out of bounds. However, during program execution, an array index out of bounds can cause serious problems. Also, in c++ the array index starts at zero.

Design the class myArray that solves the array index out of bound problem, and also allows the user to begin the array index starting at any integer, positive or negative. Every object of type myArray is an array of type int. During execution, when accessing an array component, if the index is out of bounds, the program must terminate with an appropriate error message. Consider the following statements:

myArray<int> list(5);
myArray<int> myList(2, 13);
myArray<int> yourList(-5,9);

the statement in line 1 declares a list to be an array of 5 elements, the element type is int, and the elements start from list[0] .... list [4]. Line 2 declares a list of 11 elements, starting at myList[2] ... myList[12]. Line 3 declares a list of 14 elements, starting at myList[-5] ... myList[8]. Write a program to test your class.

I had a difficulty rating this one, if you guys could leave a comment telling me what you thought this ones difficulty should be i would gladly take it into consideration.


7/24/12 Subject: Arrays Difficulty: Intermediate(thinking problem!)
Write a function reverseDiagonal that reverses both the diagonals of a two-dimensional array. For example, here is a two dimensional array:

96 26 31 81
41 71 66 56
61 51 46 76
36 86 91 21

what it should look like after the function:

21 26 31 36
41 46 51 56
61 66 71 76
81 86 91 96


7/25/12 Subject: 2D Arrays Difficulty: Intermediate

Write a program that can be used to assign seats for a commercial airplane. The airplane has 13 rows, with six seats in each row. Rows 1 & 2 are first class, rows 3 through 7 are business class, and rows 8 through 13 are economy class. Your program must prompt the user to enter the following information:

a Ticket type(first class, business, economy)
bDesired seat

Last edited on

Output the seating plan in the following form:


Here, * indicates that the seat is availible; X indicates that the seat is occupied. Make this a menu-driven program; show the user's choices and allow the user to make the appropriate choices.

7/27/12 Subject: Classes/files Difficulty: Hard

Write a program to help a local stock trading company automate its systems. The company invests only in the stock market. At the end of each trading day, the company would like to generate and post the listings of its stocks so that investors can see how their holdings performed that day. We assume that the company invests in, say 10 different stocks. The desired output is to produce two listings, one sorted by stock symbol and another sorted by percent gain from highest to lowest.

The input data is provided in a file in the following format:

symbol openingPrice closingPrice todayHigh todayLow prevClose volume

MSMT 112.50 115.75 116.50 111.75 113.50 6723823

The first line indicates that the stock symbol is MSMT, today's opening price was 112.50, the closing was 115.75, today's high was 116.50 and so on.

Text file needed for this program(data on stocks):

The listings sorted by stock symbols must be in the following form:

design and implement a stock object

a (Stock Object) Design and implement the stock object. Class the class that captures the various characteristics of the object stockType.

the main componenets of a stock are the stock symbol, price and number of shares. Moreover, we need to output the opening price closing price, high/low price, previous price and percent loss/gain for the day. These are also characteristics of a stock. The stock should store all of this information.

Perform the following operations on each stock object:

[]Set stock information
[] Print stock information
[]Show different prices
[]Calculate and price the percent gain/loss
[]Show number of shares
**The natual order of the stock list is by the stock symbol. Overload the relational operators to compare two stock objects by their symbols.
**Overload '<<' for easy output
**because the data is stored in a file, overload the stream operator '>>' for easy input

For example, suppose the infile is an ifstream object and the input file was opened using the object infile. Further suppose that myStock is a stock object. Then, the statement:

infile >> myStock;

reads the data from the input file and stores it in the object myStock.


7/30/12 Subject: Control structures Difficulty: Easy

Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (for division, if the denominator is zero, output the appropriate message.


7/31/12 Subject: Arrays and Strings Difficulty: Easy

Write a c++ program that declares an array alpha of 50 components of type double. Initialize the array so that the first 25 components are equal to the square of the index variable, and the last 25 components are equal to three times the index variable. Output the array so that 10 elements per line are printed.


8/2/12 Subject: Exceptions Difficulty: Easy

Write a program that prompts the user to enter a length in feet and inches and outputs the equivalent length in centimeters. If the user enters a negative number or non digit number, throw and handle an exception and prompt the user to enter another set.


8/30/12 Subject: Arrays and stringsDifficulty: Intermediate

Write a program that allows the user to enter the last names of five candidates in a local election and the number of votes received by each candidate. The program should then output each candidate's name, the number of votes received, and the percentage of the total votes received by the candidate. Your program should also output the winner of the election. A sample output is:

Candidate Votes Received % of Total Votes

The Winner of the Election is Duffy.


9/6/12 Subject: Recursion Difficulty:Hard
Write a recursive function to generate the following pattern of stars:
(Underscores mean WHITESPACES, only used to create picture for this page)


Also, write a program that prompts the user to enter the number of lines in the pattern and uses the recursive function to generate the pattern. For example, specifying 4 as the number of lines generates the above pattern.

Last edited on
Last edited on
2 sounds easier than 1, IMO. I think you should provide a sample file for people to use though.
Also, wouldn't it be easier if you actually did a new post every day rather than putting everything into one post?

Would seem much more convenient - no more need to type dates or do bump posts.

Don't get me wrong - I applaud your efforts :)

All the best,
I chose intermediate because the problem uses multiple subjects, the first problem only required knowledge of the string class library. I base the problem difficulty on both the difficulty of the program and the level of c++ required, so anyone that decides to take these challenges will be able to progress with relative ease. Thanks for the opinions, ill include a text file for problem two to make it easier to get started on.
Ah I get it. I guess some of the newer programmers probably won't see the trick behind it.
I love this! Great idea. I'm about to finish my C++ class (thank you, God) and I wondered what on earth I'll have to do at work starting next week...but I'll at least now have this to do. Great. Thanks, Need4Sleep.
This is plain amazing! This will speed up the progress of me learning c++ for sure (together with projekt euler). I'm used to programming in Ada but changing language (don't get me wrong, I'm still a rookie programmer). Cudos Need4Sleep, I really admire your efforts!

What is the 'trick behind it' new programmers won't see that you speak of?

Best regars
Thanks for the effort! I did the first exercise, and my code compiles well, but doesn't work well :( For example, when I enter Hallo, it returns Hll: OK. But when I try paard, it gives pard.

#include <iostream>
#include <string>

using namespace std;

bool isVowel(char character);
string substr(string line);

int main()
    string line;
    cout << "Enter a string: ";
    getline(cin, line);
    cout << "The string without vowels: " << substr(line) << endl; 

bool isVowel(char character)
     if(character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u')
         return true;
     else return false;

string substr(string line)
    for(int i = 0; i < line.length(); i++)
        if(isVowel(line.at(i)) == true)
            line.erase(i, 1);
    return line;

Can anybody tell me what's wrong with it?

EDIT: I changed the code, and now it works perfectly well.
Last edited on
baexie wrote:
What is the 'trick behind it' new programmers won't see that you speak of?

He was referring to the fact that Need4Sleep determines the difficulty of a problem by the amount of different aspects of the language have to be understood before being able to solve it.

All the best,
Fransje: Follow the loop and you will find the problem:

(i = 1)check 'p', not a vowel - moving to next position
(i = 2)check 'a', vowel - erase and move to next position
(i = 3) Now you are at position 3 but since you removed the first a, at line(3) there is no longer the second 'a' but the letter 'r'

I guess this could be solved with a loop that only increasing I when nothing is removed for each lap in the loop.

Edit: Is there any need to resize the string or is that built into erase? So the loop is not checking out of the strings length.
Last edited on
What is the 'trick behind it' new programmers won't see that you speak of?

Hint, bitwise.
Thanks, baexie! I wasn't familiar with the erase function, but I got it now.
nice work dude.. keep it up..
i am thinking about making a simple tutorial for beginners..
ResidentBiscuit wrote:
Hint, bitwise.
I'm not seeing how using a bitwise operation would work here (I assume you are referring to problem 2). AFAIK you cant use bitwise operators on string objects. I guess you could use them on the individual chars, but if your iterating over the string anyway I cant really see it saving much time.
Well, I was thinking about just using bitsets.
I assume you mean to hold both the answer key and student answers in bitsets. Problem I'm seeing with that is it cant take into consideration when no answer is given by the student.
Pages: 123... 5