• 0

[C++] Tutorial #1 Simple Sum/Average


Question

As I do on most forums that I join, I usually post a series of tutorials for programming, specifically C++. I'll be creating tutorials at random or by request, and usually cover most of the basics, advancing into intermediate programming and later scratching the surface of more advanced programs.

 

This tutorial assumes you have basic, minimal knowledge of C++.

 

What you will need:

  • Microsoft Visual Studio

And that's it! I currently use Visual Studio 2013 Professional, I got it for free via Dreamspark (if you're a college student like myself, go grab it now) or download the evaluation software.

 

http://www.visualstudio.com/downloads/download-visual-studio-vs

 

Now for the tutorial! This program is a simple program that asks the user to specify the amount of grades you want averaged and summed. It then asks for the actual grade of each, followed by the logic of average/sum of the user specified grades.

 

Step 1

 

Open Visual Studio, and click File > New Project. A pop up window will appear, and on the left hand tab, select Visual C++, and then Win32 Console Application.

 

7S8b1.png

 

A screen will appear, click next, but do not click finish on the next screen!

 

7S8J5.png

 

Before clicking Finish, make sure you check off the box that says "Empty Project"

 

7S8KY.png

 

Next, Click the tab Project > Add New Item

 

A screen will appear like this one, chose the .cpp and name it whatever you'd like. This file is the source code file for your program.

 

7S8Qb.png

 

You now have a blank workspace for your program, time to dive into the language.

 

Step 2

 

We're now going to add the file headers to the source. There are many functions and inputs in the language of C++, and these headers allow us access to them so we don't have to code them individually in each program. I.e the function "cout" , or command output, allows us to print whatever we want on screen. 

 

So go ahead and add these file headers.

#include <iostream>
#include <iomanip>
using namespace std;

And here's an image for the visual learners of what it should be so far.

 

7S8ZX.png

 

Step 3

 

After we add the headers, we need to initiate a start up function, and the default function that's called when a program is ran is int main(). Your entire source for your program, or the entire logic of the program, is within these parameters.

 

(I'll be adding code to previous code so it's chronological and makes more sense).

#include <iostream>
#include <iomanip>
using namespace std;

int main(){
	
}

Boom! This is our entire program. Within those brackets, you can do whatever, such as say hello..

#include <iostream>
#include <iomanip>
using namespace std;

int main(){
	cout << "Hello Neowin";
}

And if you ran this, it would create a program that says Hello Neowin. Simple, helloworld crap. 

 

Step 4

 

However, we want to create a program that does averages/sums of user specified input. So how do we do that?

 

First, we're going to need to init and double a few variables. 

#include <iostream>
#include <iomanip>
using namespace std;

int main(){
	int n_grades, grade;
	double sum_grades, average_grades;
}

The variables above are as follows:

  •  
  • n_grades = how many grades are going to be entered
  •  
  • grade = the grade of each test that was specified above
  •  
  • sum_grades / average_grades = sum and average of the grades, respectively
  •  

Step 5

 

We now need to have the program ask the user how many grades are going to be inputted.

#include <iostream>
#include <iomanip>
using namespace std;

int main(){
	int n_grades, grade;
	double sum_grades, average_grades;

	cout << "How many grades are you going to enter?: \n";
	cin >> n_grades;
}

Let's break this down a little if you're lost. Currently, the code above simply is going to print out on screen "How many grades are you going to enter?", and n_grades will record whatever number you input.

 

Step 6

 

Now for the hardest part of the program. How are we going to code something that gives the user infinite amount of options (how many grades he can input... 1- infinity)? This is where the for loop comes in handy. I'm going to post the code first, then explain.

#include <iostream>
#include <iomanip>
using namespace std;

int main(){
	int n_grades, grade;
	double sum_grades, average_grades;

	cout << "How many grades are you going to enter?: \n";
	cin >> n_grades;

	for (int count = 0; count <= n_grades; count++){
		cout << "Please enter grade: \n";
		cin >> grade;
		sum_grades += grade;
	}
}

As you can see, the for loop above does it all for us. If you can't see however, read on. The first line of the loop

for (int count = 0; count <= n_grades; count++)

Simply inits the variable count, which we use to determine how many times we ask the user to enter a grade, based on his input before. Then, if count is less than or equal to n_grades, then we increment count by one, or count++.

 

Within the loop, we also take care of the math part of figuring out the sum of the grades, using 

sum_grades += grade;

which is the same as 

sum_grades = grade + grade;

Step 7

The rest of the program is a cruise from this point on. We just need to to the math logic for the average, and output the results!! I'll post the full source below, as I've got to finish this up quickly. 

#include <iostream>
#include <iomanip>
using namespace std;

int main(){
	int n_grades, grade;
	double sum_grades, average_grades;
	cout << setprecision(2) << setiosflags(ios::fixed) << setiosflags(ios::showpoint);

	cout << "How many grades are you going to enter?: \n";
	cin >> n_grades;

	for (int count = 0; count <= n_grades; count++){
		cout << "Please enter grade: \n";
		cin >> grade;
		sum_grades += grade;
	}

	average_grades = sum_grades / n_grades;

	cout << "The total number of grades are: " << n_grades << endl;
	cout << "The sum of all grades are: " << sum_grades << endl;
	cout << "The average of all the grades are: " << average_grades << endl;

	system("PAUSE");
	return 0;
}

And voila! We have a simple program that allows us to find the average and the sum of a user specified number. Sorry for the shortness and briefness of the tutorial, gotta run out the door as we speak. Let me know any areas that could be improved, tutorial wise or code wise. Thank you!

 

7Sbq5.png

Link to comment
https://www.neowin.net/forum/topic/1207513-c-tutorial-1-simple-sumaverage/
Share on other sites

13 answers to this question

Recommended Posts

  • 0

Thanks for the tutorial.

But isn't your output wrong?

You enter 100 and 50

how can the sum be 100

and how can the average be 50

 

shouldn't the answers be 150 and 75?

 

Or am I missing something?

  • Like 3
  • 0
  On 01/04/2014 at 16:52, Stoffel said:

Thanks for the tutorial.

But isn't your output wrong?

You enter 100 and 50

how can the sum be 100

and how can the average be 50

 

shouldn't the answers be 150 and 75?

 

Or am I missing something?

Oi I messed up on the math, the average is correct but let me fix the sum really quick.

  • 0

You're not initializing your variables to 0, so the behavior of the program is undefined. It might work in debug and print out garbage in release, for instance.

 

Also, if you're just going to use standard library functions, you could create an empty project rather than a Win32 console application.

  • Like 2
  • 0

Welcome to the forum, and happy birthday!

 

Some comments:

  1. You don't initialize any of your variables. This means that the output could be literally anything. You should set all primitive types to a value before performing operations on them (i.e. zero).
  2. Your input loop will run one more time than required, since you're using "<=" instead of just "<" for the comparison in the for loop.
  3. Good C++ style dictates that you should declare your variables when you need them. Declaring all your variables at the top of the function is a C idiom and not necessary for C++.
  • 0
  On 01/04/2014 at 16:56, Andre S. said:

You're not initializing your variables to 0, so the behavior of the program is undefined. It might work in debug and print out garbage in release, for instance.

 

Also, if you're just going to use standard library functions, you could create an empty project rather than a Win32 console application.

 

 

  On 01/04/2014 at 17:02, Majesticmerc said:

 

Welcome to the forum, and happy birthday!

 

Some comments:

  1. You don't initialize any of your variables. This means that the output could be literally anything. You should set all primitive types to a value before performing operations on them (i.e. zero).
  2. Your input loop will run one more time than required, since you're using "<=" instead of just "<" for the comparison in the for loop.
  3. Good C++ style dictates that you should declare your variables when you need them. Declaring all your variables at the top of the function is a C idiom and not necessary for C++.

 

I didn't init anything to zero simply for the purpose of beginners, as I remember when I was learning, that we keep everything undefined for later purposes. 

 

As for the input loop running three times, it'll run as many times as user specified.

 

Either way, thank you both! I'm still relatively new to C++ as a whole, been programming a type of hybrid C++/C# for a few years but just recently started uniform C++. 

  • 0
  On 01/04/2014 at 17:13, coolbunny1234 said:

I didn't init anything to zero simply for the purpose of beginners, as I remember when I was learning, that we keep everything undefined for later purposes.  

You use the initial value of sum_grades, therefore you have to define it. If sum_grades is initially -177463 or some random value (it could be anything if you don't define it), then obviously the total sum will not be correct.

 

Perhaps you're used to C# where everything is zero-initialized for you by default, but this is not the case in C++. If your program works in its current form, it's by pure chance and not by design.

  • Like 1
  • 0
  On 01/04/2014 at 17:16, Andre S. said:

You use the initial value of sum_grades, therefore you have to define it. If sum_grades is initially -177463 or some random value (it could be anything if you don't define it), then obviously the total sum will not be correct.

 

Perhaps you're used to C# where everything is zero-initialized for you by default, but this is not the case in C++. If your program works in its current form, it's by pure chance and not by design.

Yes I see what you mean, thank you. Kind of a pain, there isn't a way to default an initial value to zero?

  • 0

This is good. We should have more tutorials like this, perhaps a weekly thread, and maybe not C++ but something more current like XAML for Windows Phone and Windows 8 app development? Especially some of the new features available in the new Windows Phone 8.1 SDK. I have some great ideas for apps but sadly the extent my programming knowledge goes as far as programming Microcontrollers in C and Assembly Language.

  • 0
  On 01/04/2014 at 17:13, coolbunny1234 said:

I didn't init anything to zero simply for the purpose of beginners, as I remember when I was learning, that we keep everything undefined for later purposes.

As for the input loop running three times, it'll run as many times as user specified.

Initializing to zero is EVEN MORE important for beginners, as undefined behaviour is one of the hardest things to debug. The problem is that with the variable's being undefined, sum_grades could be zero, or it could be 23840947835. You just don't know. To quote Herb Sutter and/or Andrei Alexandrescu:

 

  Quote

Start with a clean slate. Uninitialized bugs are a common source of bugs in C and C++ programs. Avoid such bugs by being disciplined about cleaning memory before you use it; initialize variables upon definition.

The only time you don't want to initialize a variable is for optimization, but it's a MASSIVE micro-optimization, and in the real world you're unlikely to see any difference.

This is my console output from running in the Visual Studio debugger:

 

How many grades are you going to enter?:
2
Please enter grade:
100
Please enter grade:
50
Please enter grade:
25
The total number of grades are: 2
The sum of all grades are: -92559631349317830000000000000000000000000000000000000000000000.00
The average of all the grades are: -46279815674658915000000000000000000000000000000000000000000000.00
Press any key to continue . . .
  • Like 1
  • 0
  On 01/04/2014 at 17:19, coolbunny1234 said:

Yes I see what you mean, thank you. Kind of a pain, there isn't a way to default an initial value to zero?

If you don't want pain, don't use C++ :P

  • Like 3
  • 0
  On 01/04/2014 at 17:19, coolbunny1234 said:

Yes I see what you mean, thank you. Kind of a pain, there isn't a way to default an initial value to zero?

Not as such. In container classes (lists, that kind of thing), C++ will usually "default construct" which for an integer will set it to zero, but when declaring a regular variable, the onus is on the programmer to initialize the variable.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Now I may not quite understand this, so someone tell me if I'm off the mark here, but does this mean they'll be potentially removing drivers for now unsupported systems, such as old processors and chipsets? In the past 15 years, Windows has been amazing at just installing on any device, and often having zero, or just a few unessential drivers missing on first install. It would be a shame for that experience to go, though I understand the reasoning, or at least their financial reasoning for it!
    • Microsoft is removing legacy drivers from Windows Update by Usama Jawad Last month, we learned that Microsoft is making major changes to the development of hardware drivers in Windows. This included the retirement of Windows Metadata and Internet Services (WMIS), along with the process for pre-production driver signing. Now, the Redmond tech firm has informed partners that it will be getting rid of old drivers in Windows Update. In what is being described as a "strategic" move to improve the security posture and compatibility of Windows, Microsoft has announced that it will be performing a cleanup of legacy drivers that are still being delivered through Windows Update. Right now, the first phase only targets drivers that already have modern replacements present in Windows Update. As a part of its cleanup process, Microsoft will expire legacy drivers so that it is not offered to any system. This expiration involves removing audience segments in the Hardware Development Center. Partners can still republish a driver that was deemed as legacy by Microsoft, but the firm may require a justification. Once the Redmond tech giant completes its first phase of this cleanup, it will give partners a six-month grace period to share any concerns. However, if no concerns are brought forward, the drivers will be permanently eradicated from Windows Update. Microsoft has emphasized that this will be a regular activity moving forward and while the current phase only targets legacy drivers with newer replacements, the next phases may expand the scope of this cleanup and remove other drivers too. That said, each time the company takes a step in this direction, it will inform partners so that there is transparency between both parties. Microsoft believes that this move will help improve the security posture of Windows and ensure that an optimized set of drivers is offered to end-users. The firm has asked partners to review their drivers in Hardware Program so that there are no unexpected surprises during this cleanup process.
    • No idea, but I had a client the other week that lost the entire drive to it. I suggested relying on the Samsung T7's instead. The Sandisk Extreme's had reliability issues too.
    • I use it every day so personally yes I need it, or rather I want it. I use OpenShell though, not the garbage modern Start Menu. I just counted and at the moment I have a total of 92 program shortcuts organized into six folders almost exactly the way I did back in Windows 95. I can get to any program I want to run very quickly. I never use Search to find or run programs.
    • I do miss the Apps view from Windows 8.1 Update.
  • Recent Achievements

    • One Month Later
      KynanSEIT earned a badge
      One Month Later
    • One Month Later
      gowtham07 earned a badge
      One Month Later
    • Collaborator
      lethalman went up a rank
      Collaborator
    • Week One Done
      Wayne Robinson earned a badge
      Week One Done
    • One Month Later
      Karan Khanna earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      682
    2. 2
      ATLien_0
      274
    3. 3
      Michael Scrip
      220
    4. 4
      +FloatingFatMan
      171
    5. 5
      Steven P.
      160
  • Tell a friend

    Love Neowin? Tell a friend!