Including multiple files with C++ - c++

This week my class took a spin and is teaching material not found in the book. I'm using Visual Studio 2010, the project is to take 5 numbers from the keyboard and get the average, but I have to use functions with a .h header file and corresponding .cpp file to receive credit. This is what I have so far
Main.cpp
#include <iostream>
#include "average.h"
using namespace std;
const int numbersinput=5;
int main ()
{
int numbers,sum,avg;
cout << "Hello, please enter 5 numbers you would like to see the average for." << endl;
for (int i = 0; i != numbersinput; ++i)
{
cin >> numbers;
sum += numbers;
}
int average(int sum);
cout << avg;
system ("PAUSE");
return 0;
}
The .h headerfile named average.h
#include <iostream>
using namespace std;
int average(int);
and the other .cpp file named average.cpp
#include <iostream>
#include "average.h"
using namespace std;
const int numbersinput=5;
int avg;
int average(int sum)
{
avg = sum /numbersinput;
return avg;
}
I can get a successful build, but I get this error after I enter the first number and press enter.
Run-Time Check Failure #3 - The variable 'sum' is being used without
being initialized.
What am I not getting here?

You might want to initialize sum to 0 before you start adding to it with +=:
So instead of int numbers,sum,avg;
You will have int sum = 0; etc.

Change this line:
int numbers,sum,avg;
To:
int numbers=0;
int sum=0;
int avg=0;
This gives the variables values- before they are initialized (given a value) they are undefined, which means that they could equal any value. By initializing them, you are giving them a number to add to when you make the sum.
Edit these lines:
int average(int sum);
cout << avg;
To:
cout << average(sum);
The function declaration for int average(int sum) is not called in the same way as it is declared. The ints are unnecessary. In my edited code, you can see that the returned value (average)is printed out, instead of being left without being used.
Also, as a general tip, try not to give variables the same name. Try to make the function variable sum be called sumToAverage or instead make the sum in main be called total. It is a good idea to pick variable names that are different, so you won't get confused.

You're saying :
sum += numbers
But you haven't initialized sum, so it will have some random value that's on the stack. Change your declaration of sum to:
int sum = 0;
Also, you're using global variables to pass information to functions, which isn't a good idea. Get rid of the avg variable and change average to:
int average(int sum, int numberofvalues)
{
int avg = sum / numberofvalues;
return avg;
}
You're also re-declared average in the body of main, which you don't need to do as it's in the header. Then, you can get the average in main by saying:
int avg = average(sum, numbersinput);
Now, main will look like this:
int main ()
{
int sum=0;
cout << "Hello, please enter 5 numbers you would like to see the average for." << endl;
for (int i = 0; i != numbersinput; ++i)
{
int number;
cin >> number;
sum += number;
}
int avg = average(sum, numbersinput);
cout << avg;
system ("PAUSE");
return 0;
}
Oh, and don't put using namespace std in header files!

Related

Hello, the program on Functions (pass by reference/pass by value) and I'm not entirely sure what is wrong with my program

Can someone give advice or guidance on what is wrong with my program? I do have the program fully written out, I am not sure where to add the function definition and function prototype to my program. This program involves pass by value and pass by reference. Also, any helpful notices on small errors will be appreciated
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//Declare Variables
double amount = 22.66;
int num;
int dollars;
int quarters;
int dimes;
int nickels;
int pennies;
double x = 22.25;
double y = 55.55;
//Input
cout << "Please enter your dollar amount: ";
cin >> amount;
void showMenu() //function prototype
{
cout << "A. Money Exchange function" << endl;
cout << "B. Find Max Solution" << endl;
cout << "E. Exit" << endl;
cout <<"Please enter your choice:"<<endl;
}
void MoneyExchange(float amount, int& dollars, int& quarters, int& dimes,
int & nickels, int & pennies) // function prototype
{
int amount = 0, Remainder;
amount = amount * 100;
dollars = amount / 100;
Remainder = amount - (dollars * 100);
quarters = Remainder / 25;
Remainder = Remainder - (quarters * 25);
dimes = Remainder / 10;
Remainder = Remainder - (dimes * 10);
nickels = Remainder / 5;
Remainder = Remainder - (nickels * 5);
pennies = Remainder / 1;
}
double max(double x, double y) //function prototype
{
double max;
if (x >= y)
max = x;
else
max = y;
system("Pause");
return 0;
}
To use a function, you need to have a function method declaration (tell compiler/linker that this function exists) and implementation (stuff that function method does).
Here is a barebones example
void doStuff(); //im function declaration/prototype
void doMoreStuff(); //im function declaration/prototype
int main()
{
void doMoreStuff() //dont nest me in here!
{
cout << "doMoreStufff runs" << endl;
}
doStuff();
doMoreStuff();
return 1;
}
void doStuff() //im function implementation
{
cout << "doStuff runs" << endl;
}
Key take aways:
1) What you call a function prototype in your code is function implementation
2) No nesting implementation. for example: Dont do this
int main()
{
void doMoreStuff() //dont nest me in here!
{
cout << "doMoreStufff runs" << endl;
}
doStuff();
doMoreStuff();
return 1;
}
void doStuff() //im function implementation
{
cout << "doStuff runs" << endl;
}
(side note: one could nest anonymous/lambda functions inside)
3) In your case it doesnt matter if you stick method implementation above or below main{} implementation, just make sure you have your functions declared above main{} implementation (where these methods are used)
TLDR Poor naming conventions, not prototyping/declaring and defining properly, mismatched variable types, hiding value of amount (22.66, then cin, then int amount = 0 in MoneyExchange), unused code (max function), menu is not functional.
You are trying to define functions inside the main function like such:
int main() {
// ...
void showMenu() {
// code to do stuff
}
// ...
return 0;
}
It does not work like this. If you want to define and declare showMenu, so it can be used in main, try this. (See above)
void showMenu() {
// code to do stuff
}
int main() {
// ...
showMenu();
// ...
}
If you do not prototype the function, you must declare it above the main function. Otherwise it won't compile. (See above)
Try this (See below) if you want to prototype. You can have your prototypes in the main file or in a header file which you can include in main.
void showMenu(); // prototype
int main() {
// ...
showMenu();
// ...
}
void showMenu() {
// code to show the menu
}
If you want to define a function inside another, you should use a lambda expression.
Problems with your program:
-You define amount as a double of value 22.66 and then write over it when you cin >> amount. You only need to set the value once, so remove the cin or (preferably) change it to
double amount;
-Your functions and procedures, showMenu, MoneyExchange and max need to be moved outside of main, and prototyped or defined before main.
-You should find a naming convention which works for you and stick to it. You have procedure names starting with a capital MoneyExchange and then one starting with lower case, showMenu. Stick to the same, I'd use moneyExchange and showMenu.
You have done the same thing with variables, have a look here https://code.tutsplus.com/articles/9-confusing-naming-conventions-for-beginners--net-15584 this explains some naming conventions.
-Max function does not return anything. It must return a double, as you've declared. E.G.
double max(double x, double y) {
// ...
return 0.0;
}
-In MoneyExchange you declare a new int called amount, which you have declared locally in main as a double. You also set the value to 0, not the amount you inputted using cin.
-When you declare MoneyExchange, amount is taken as a float. So you pass a double, receive it as a float and then make a new int called amount... Stick to one data type. You also don't pass it by reference.
-You don't use the max function anywhere in this code.
-You don't get input from the menu, so the user does not have an option. I would use a switch statement. See this link http://www.cplusplus.com/forum/general/156582/ .

C++ Beginner Array Program

PART 1
Write a program that will:
1.Call a function to input temperatures for consecutive days in an array. The temperatures are to be integer numbers.
2.The user will input the number of temperatures. There will be no more than 10 temperatures.
3.Call a function to sort the array by ascending order. You can use any sorting algorithm you wish as long as you can explain it.
4.Call a function that will return the average of the temperatures. The average should be displayed to two decimal places.
Below is my source code, am I on the right track?
What algorithm should i use for this question?
For the number 4, I could just use the average function right?
Also is there any youtube channels or other learning sources that you would recommend for a beginner to study C++? I have tried reading the books but I did not feel that really helps me.
I am a beginner and I have tried searching it online but I did not find any solution.
#include <iostream>
using namespace std;
int main()
{
int numtemp;
cout<<"Please input the number of temperatures to be read"<<endl;
cin>>numtemp;
int temp[numtemp];
for (int i=0;i<numtemp;i++)
{
cout<<"Please input temperatures for day "<<(i+1)<<endl;
cin>>temp[i];
}
return 0;
}
Lets see if I can help... When it says "call a function" that may very well mean call a function that you wrote if the perfect solution doesn't already exist. The below code will show you my implementation of #4.
#include <iostream>
double AvgFunction(int numTemp, int* temp);
int main()
{
int numTemp;
std::cout << "Please input the number of temperatures to be read" << std::endl;
std::cin >> numTemp;
int temp[numTemp];
for (int i = 0;i < numTemp; i++)
{
std::cout << "Please input temperatures for day "<< (i+1) << std::endl;
std::cin >> temp[i];
}
std::cout << AvgFunction(numTemp, temp) << std::endl;
return 0;
}
double AvgFunction(int numTemp, int* temp)
{
double returnVal = 0;
for(int i = 0; i < numTemp; i++)
{
returnVal += temp[i];
}
returnVal /= numTemp;
return returnVal;
}
The function I call, AvgFunction, is written below main. This link explains functions and may be the most useful in learning how to be successful in problems like this:
http://www.cplusplus.com/doc/tutorial/functions/
To complete #3 you will have to write another function. Use the same structure, but different content within to solve the problem. An explanation of the simplest sorting algorithm:
http://www.geeksforgeeks.org/selection-sort/
The operators I use in the function are called compound operators. More info on that if you search "compound operators."
The line I added before main is a function prototype. More info on that if you search "function prototype."
Hope this helps

Array Issue & Returning Functions

So I'm new to C++ and am writing a program to calculate the mean, median, standard deviation, min, and max of a program. The issues I'm having are that I don't know how to correctly call functions from other files in the project, and when I try to print(c out <<) my array, it returns a weird value like 0 x 0017 c 530 (disregard the spaces). If anyone could help me correctly return these functions, and print the list correctly, I would be very grateful! Here's my code (not including the .h file):
#include <iostream>
using namespace std;
#include "stats.h"
int main()
{
double nums[10000] = {};
int n;
cout << "Enter number of values: ";
cin >> n;
for (int i = 1; i <=n; i++) {
cout << "Enter number " << i << ": ";
cin >> nums[i-1];
}
// me trying to print the nu ms list
cout << nums << endl;
// me trying to call the function
double mean(double nums[], int n);
return 0;
}
stats. cpp
#include "stats.h"
double mean(double nums[], int n)
{
double sum = 0;
double average;
for (int i = 0; i > n; i++) {
sum += nums[i];
}
average = sum / n;
return average;
}
Instead of
cout << nums << endl;
Just like you have a loop to enter one value at a time in an array, you also need a similar loop to print one value at a time from the array.
To call a function from another translation unit, you would typically declare the function in a header file, your stats.h would be an excellent candidate:
double mean(double nums[], int n);
And then just invoke it from your main:
std::cout << mean(nums, n) << std::endl;
That's it.
Also:
using namespace std;
You need to have someone help you to get an amnesia, and completely forget that C++ has anything like this. This is bad programming practice.
double mean(double nums[], int n); is declaration of function, not invoking of function. You should
double mean_value = mean(nums, n);
cout << mean_value << endl;
And cout << nums << endl; won't print out the elements of the array, just the address of the array. You need to loop the array to print out all the elements.

C++ "While" Loop

I'm struggling to apply a "While" loop to the following problem: Design the logic for a program that allows a user to enter a number. Display the sum of every number from one through the entered number.
Start
int userNumber;
Declarations
int number = 1
while number <= userNumber
++number
endwhile
output number
Stop
I know my code isn't correct as it is just adding one to the initial value until the user's number is reached, thus making the output the user's number. How would I go about adding each subsequent value without writing them out e.g. user's number is 10, so the program would add 1+2+3+4+5+6+7+8+9+10 and output the total of 55?
Thank you!
Here's a tip. You'll want to start at the users number and count down to 0. Like this:
int finalNum = 0;
int userNum;
//This is where you need to get the user's number....
while(userNum > 0)
{
finalNum += userNum;
userNum--;
}
//Do whatever you need to finalNum....
EDIT: It appears you've posted pseudocode; usually a big no-no here unless stated otherwise. It's better to post the actual code as it's easier to tell what exactly is going on.
The function you need could look like this for c++:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
unsigned t = 0; // Assume the result to be 0 (zero)
for (i = 1; i <= x; i++) // Continue until i is greater than x
{
t += i; // Accumulate, i.e. t = t +i
}
cout << "sum=" << t << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
An alternative is:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
cout << "sum=" << (x*(x+1)/2) << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
This works because the sum of all integers from 1 to n is n*(n+1)/2

C++ Calling - search function

I was wondering how I could finish up this program. It's to perform a linear search on a list "ll" (which length is 31) for the user inputted item it, returning the user inputted numbers and their locations if they're found.
Problem: I'm not sure how to call the functions in this specific scenario, I don't really need to use pointers or pass a value, so the lack of these actually makes it more confusing for me, as those are fairly common scenarios.
#include <iostream> //enables usage of cin and cout
#include <cstring>
using namespace std;
int search (int i, int it, int ll, int z);
int printit (int i, int it, int ll, int z);
int main ()
{
int i,it,z;
int ll[] = {2,3,4,5,6,2,3,44,5,3,5,3,4,7,8,99,6,5,7,56,5,66,44,34,23,11,32,54,664,432,111}; //array hardwired with numbers
//call to search
return 0;
}
int search (int i, int it, int ll, int z)
{
cout << "Enter the item you want to find: "; //user query
cin >> it; //"scan"
for(i=0;i<31;i++) //search
{
if(it==ll[i])
{
//call to printit
}
}
return 0;
}
int printit (int i, int it, int ll, int z)
{
cout << "Item is found at location " << i+1 << endl;
return 0;
}
There is a problem with each of the parameters to search:
i's passed value gets overwritten before it gets used, and thus should be a local variable
Same thing for it
ll should be an array of ints
z isn't used at all
Things are even worse for printit: 3 of the 4 parameters are ignored.
Search and print don't need to return int, if you have already print out the results. Also some declared variables are useless. The following code would work:
#include <iostream> //enables usage of cin and cout
#include <cstring>
using namespace std;
void search (int ll[]);
void printit (int n);
int main ()
{
// int i,it,z;
int ll[] = {2,3,4,5,6,2,3,44,5,3,5,3,4,7,8,99,6,5,7,56,5,66,44,34,23,11,32,54,664,432,111}; //array hardwired with numbers
//call to search
search(ll);
return 0;
}
void search (int ll[])
{
cout << "Enter the item you want to find: "; //user query
cin >> it; //"scan"
for(i=0;i<31;i++) //search
{
if(it==ll[i])
{
//call to printit
printit(i);
}
}
// return 0;
}
void printit (int n)
{
cout << "Item is found at location " << n+1 << endl;
// return 0;
}