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
Related
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
The goal of this code is to pass an array through a function (which I'm already having a difficult time understanding). I went through with a pen and paper and traced the code and I think I just don't know enough to understand what's going wrong. All the test scores I throw in just push back a ridiculously large negative number. I'm not asking for you guys to do my homework because I really want to try and understand what I'm doing, but any help would really be appreciated right now.
#include <iostream>
//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);
int main() {
do {
int studentScores[4], size = 4, result;
string score;
cout << "This program will calculate the average of four diffrent exam scores." << endl;
for (int i = 0; i < size; i++) {
studentScores[i] = 0;
cout << "Please Enter Exam Score " << i + 1 << ": ";
getline(cin, score);
}
for (int i = 0; i < size; i++) {
result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
studentScores[i]++;
}
cout << "The Average Exam score is " << result << endl;
} while (runAgain());
system("pause");
return 0;
}
//function implementation
double average(int studentScores[], int size) {
for (int i = 0; i < size; i++) {
return (studentScores[i]++ / size);
}
}
bool runAgain(void) {
char userResponse;
cout << "\nWould you like to run again (y or n): ";
cin >> userResponse;
if (userResponse == 'y' || userResponse == 'Y')
return(true);
return(false);
}
First obvious bug:
int studentScores[4]
studentScores has 4 elements, numbered studentScores[0] through studentScores[3].
But your code accesses studentScores[4] in
result = (... + studentScores[4]) / ...
which doesn't exist (and doesn't access studentScores[0], which does).
Glad to try to help ya out without giving you the answer.
I'm gonna sprinkle some questions throughout your code that you should be asking yourself in future programs whenever you get unexpected output.
#include <iostream>
//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);
int main() {
do {
int studentScores[4], size = 4, result;
string score;
/* Above, you declared a string to store the user's input in.
In C++, the string "4" DOES NOT equal the integer 4.
How will you handle the fact that the variable 'score' is of type
string, but you want to work with integers?
Is there an easy way to get rid of this issue? (hint: use cin)
*/
cout << "This program will calculate the average of four diffrent exam scores." << endl;
/* In the below for-loop, think about what the value of 'score' will be
after each iteration. (Hint, getline replaces the existing value of score).
Also, where is the code that saves the user's inputted numbers to an array?
Learn how to write values to an array http://www.cplusplus.com/doc/tutorial/arrays/
*/
for (int i = 0; i < size; i++) {
studentScores[i] = 0;
cout << "Please Enter Exam Score " << i + 1 << ": ";
getline(cin, score);
}
/* In the for-loop below, you already noticed that your array has random
values in it. The comment about the above for-loop should address that issue.
Equally important though is understanding what the heck is happening in this
loop below. After you fix the bug in the for-loop above (which will
get the values in the array to equal the user's inputs), you'll be faced
with issues in this loop below.
My advice is to understand what happens when the program
executes "studentScores[i]++". First, it gets the number in the array at
the ith+1 position, then it increments that number by 1. Cool, but what
are you doing with the result of that? It's not being put to use anywhere.
Also, note that because the array is never being updated,
the line above it just calculates the same number and stores it in 'result'
every iteration of the loop.
*/
for (int i = 0; i < size; i++) {
result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
studentScores[i]++;
}
cout << "The Average Exam score is " << result << endl;
} while (runAgain());
system("pause");
return 0;
}
// this function doesn't seem to be used, but understanding what
// is wrong with it will help you understand how to code.
// First, note that once a function hits 'return', it will
// never execute any more code in that function.
// So here, your return statement in the for-loop will prevent an
// actual loop from occuring (since the function will exit as soon as the first loop iteration is entered)
// Second, note that you are just getting the value in the array and adding 1 to it
// before dividing it by 'size', which is not the formula for an average.
double average(int studentScores[], int size) {
for (int i = 0; i < size; i++) {
return (studentScores[i]++ / size);
}
}
bool runAgain(void) {
char userResponse;
cout << "\nWould you like to run again (y or n): ";
cin >> userResponse;
if (userResponse == 'y' || userResponse == 'Y')
return(true);
return(false);
}
I hope these comments helped :) Keep at it!
Don't forget that arrays start at index 0. Trying to access studentScores[4]
will give you an unexpected number.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need help on something. The textbook I am reading that teaches c++ does not do a good job at teaching students the linear searching algorithm. As a result I have tried recreating the algorithm without using any functions. The problem is, the code I have written seems to have some bugs. Just to note I am using the Microsoft Visual Studios 2013 IDE. As a result, can anyone please tell me what is wrong with my code? Here is the algorithm I have written in English. The Algorithm will not show the variable and array definitions but the source code will.
P.S. This is not a homework assignment. It is just for fun :)
P.S. For some reason the code formatting was very glitchy.
Algorithm:
Ask the user to enter a number
Create a for loop
Inside the for loop traverse through each element in the array and compare
it with the number the user inputted
If the element in the array is EQUAL to the number the user inputted, display a message saying it was found
If the element in the array is NOT EQUAL to the number the user inputted, display a message saying it WASN'T found.
code:
#include <iostream>
using namespace std;
int main()
{
// Create the array
int array[6] = {1,2,3,4,5,6};
int number;
// Ask the user to enter a number
cout << "Enter a number: ";
cin >> number;
// Create a for loop to traverse through each number in the array
//to see if it equals the user inputted number
for (int i = 0; i < 6; i++)
{
if (number == array[i])
{
cout << "Number Found: " << array[i] << endl;
}
else if (number != array[i])
{
cout << "Number Not Found!" << endl;
}
}
return 0;
}
The output if I entered 3 would be the following:
Number Not Found!
Number Not Found!
Number Found: 3
Number Not Found!
Number Not Found!
Number Not Found!
your logic output decision for each iteration. But it seems you've to output your decision only once.
So, for this reason declare a boolean variable globally and set false as a value of this value.
For each iteration check it is found. if found then set the boolean value to TRUE.
for Final output check global boolean value either true or false and print output
Remove the cout from inside the loop. Use a flag, ie if the number is found, set it to true and then write the print statement outside using an if.
int flag=0;
for(int i=0;i<6;i++){
if(number==arr[i])
flag=i+1;
}
if(flag) cout<<"found at position"<<flag;
else cout<<"Not found";
PS: Buy a better textbook
Easier and more fun:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int number;
vector<int> nums{1,2,3,4,5,6};
cout << "Find a number: ";
cin >> number;
for_each(cbegin(nums), cend(nums),
[&](const int& x)
{
if(x == number)
cout << "found " << x << endl;
else
cout << "could not find " << endl;
});
}
But a good starting point for linear search would be:
template<typename I, typename T>
I find (I first, I last, const T& val)
{
while (first != last) {
if (*first == val) return first;
++first;
}
return last;
}
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
Good evening everyone, i am attempting to write code that will determine when a number is largest and smallest.. I have asked some tutors I know for help and they have been stumped on this as well. I can not use functions or arrays or breaks. :/ Which I understand makes the process more difficult.. My professor has stated
"The only decisions staments allowed inside the loop are to determine the largest and smallest value. This means you are not allowed to use a decision to determine if the first number was entered. This is going to require you to prime your loop. We cover priming the loop in the next section but for this assignment it means get the first number before the loop begins. We will also assume that at least one number is going to be input."
I don't understand how he expects us to do something we have not learned yet, but regardless.. This is how far I have gotten on the assignment..
We have to have the user input a value to determine how many values will be input...
I keep receiving an error message after I input how many values I would like to check,
"the variable "num" is being used without being initialized.." But num is in the int!!!
Then have the software basically identify the largest and smallest... Hopefully this makes sense to someone.. If you have any questions, or if I need to clarify anything please let me know, I will do so to the best of my ability..
#include <iostream>
using namespace std;
int main ()
{
int number;
int max=0;
int num;
int min=0;
{ cout << "How many numbers do you want to enter" ;
cin >> number;
for (int i=0; num!=number; i++)
{
cout<<"Enter a num "; /* This is where they are supposed to place in a number, press enter, another number, press enter, until their enter presses = number*/
cin>>num;
if (num>max)
max=num;
if (num<min)
min=num;
}
cout<<"largest number is: "<<max << endl;
cout<<"smallest number is: "<<min << endl;
}
}
This:
for (int i=0; num!=number; i++)
has undefined behavior, num doesn't have a value when this is first evaluated. You meant i != number (or, even better, i < number).
It would be better to use some other way of stopping, i.e. stop when a non-number is entered for instance.
Update: Just to clarify: there are other issues as well, such as min not being initialized in a way that make as many numbers as possible smaller than it. I would probably have gone for min = INT_MAX; or something like that. See <climits> for that constant.
int min=0;
you should change that to
int min=std::numeric_limits<int>::max();
Otherwise, the if the number you entered is greater than 0, it will not be assigned to min.
the variable "num" is being used without being initialized..
Give num a value, you have not given it a value before your loop starts. But that loop concept itself is wrong, try this.
for (int i=0; i < number; i++)
There is two problem in your code, first your min must be a great number like maximum integer, and the second is your for loop should loop on i. I commented lines that you need to change :)
#include <iostream>
#include <limits>
using namespace std;
int main ()
{
int number;
int max=0;
int num;
int min=std::numeric_limits<int>::max(); // change min to maximum integer possible in c++
{
cout << "How many numbers do you want to enter" ;
cin >> number;
//for (int i=0; num !=number; i++) change this line
for (int i=0; i<number; i++) //to this line
{
cout<<"Enter a num "; /* This is where they are supposed to place in a number, press enter, another number, press enter, until their enter presses = number*/
cin>>num;
if (num>max)
max=num;
if (num<min)
min=num;
}
cout<<"largest number is: "<<max << endl;
cout<<"smallest number is: "<<min << endl;
}
}
First off, I'll mark this as a homework problem I've been stuck on for a week as I can't seem to figure out what I'm doing wrong and I'm hoping the wonderful people at SO can come to my rescue yet again (I've searched SO and other C++ sites for the past week but the solutions offered didn't correct the issue - however it is possible I may have been setting the loop incorrectly.
The assignment: given a text file numbers.txt (which contains 9,999 numbers ranging from 1 to 10,000 randomly sorted with one number missing from the consecutive list) the assignment is to use a void function in order to determine what the missing integer is.
What I've tried: My last attempt of this contains the following code:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
void find_number();
int main()
{
...
find_number();
}
void find_number();
{
int sum = 0;
int sum1 = 0;
int num;
for (int i = 1; i <= 10000; i++)
sum += i;
cout << "The sum of all the numbers between 1 and 10,000 is: " << sum << endl;
ifstream numbers;
numbers.open("numbers.txt");
if (!numbers.good()) {
return;
cout << "Error! Unable to open file!";
}
if (numbers) {
numbers >> num;
sum1 += num;
}
numbers.close();
cout << "The sum of all the numbers contained in the text file \"numbers.txt\" is: " << sum1 << endl;
cout << "By subtracting the sum of the text file from the sum of 1 to 10,000 the consecutive number missing from the text file is: " << sum - sum1 << endl;
}
What am I doing wrong? Thank you for any assistance.
There are at least two mistakes:
The return statement is executed before the diagnostic output
if (!numbers.good()) {
return;
cout << "Error! Unable to open file!";
}
The following lines will execute once instead of reading the whole file:
if (numbers) {
numbers >> num;
sum1 += num;
}
You can improve your code with the following suggestions:
Extract a number and check the stream status at the same time:
while(numbers >> num) sum1 += num;
You don't need to close the file stream it will do it automatically in its destructor.
You can open the file at the file stream initialization time:
ifstream numbers("numbers.txt");
Hint: you are not reading the whole file