Having trouble with a for loop for school - c++11

I'm currently taking a C/C++ programming class at my school. I am tasked with writing a piece of code that will ask the user how many numbers they would like averaged, then averages them. The program has to contain a for loop. The problem that I am having is that after the user has entered the "n" variable, if they type a character such as "a", the program will immediately spit out an answer as my average. I would like to find a way to prevent the user from entering characters so that my for loop can finish running and average the numbers properly. Here is my code:
{
int n, i = 1, x = 1;
double sum = 0, average, value;
cout << "\nHow many numbers do you want to average?: ";
cin >> n;
while (n < 1)
{
cout << "\nYou have entered an invalid number.\n";
cout << "\nHow many numbers do you want to average?: ";
cin.clear();
while (cin.get() != '\n');
cin >> n;
}
for (n; i <= n; i++)
{
cout << "\nEnter value: ";
cin >> value;
sum = sum + value;
}
average = sum / n;
cout << "\nThe average is: " << average << endl;
system("pause");
return 0;
}

Related

cin.fail() running an iteration too late?

I'm doing a relatively simple assignment asking us to intake integers and fail gracefully if it hits something that isn't an integer, written in C++. I'm fairly experienced with the language, and I knew it had functionality for checking reading errors in ios::failbit. As a result I'm using cin.fail() to check for errors here, but its running one loop too late--that is, its running the rest of the code first, and not realizing an error happened until the next time it checks the buffer. The obvious solution is to just check twice, but that just causes infinite loops (even if I flush or clear cin.) Is there any way to check more immediately?
Here's my code:
int min = 101; //One higher than the max.
int pile = 0;
int count = 0;
int temp = 0;
int fail;
std::cout << "Input a series of integers between 0 and 100. When you wish to"
" exit, enter -1.\n";
while (true){
std::cin >> temp;
if (std::cin.fail()){
std::cout << "FAILURE: Bad input. It probably wasn't an integer.\n";
std::cout << "Reading will stop.\n";
break;
}
std::cout << "\nTemp is " << temp << "\n";
if (temp > 100 || temp == -1){
break;
}
if (temp < min){
min = temp;
}
pile += temp;
std::cout << "Pile is " << pile << "\n";
count++;
std::cout << "Count " << count << "\n";
}
std::cout << "Your average was: " << (double)pile/count << ".\n";
std::cout << "Your minimum was: " << min << ".\n";
return 0;
}

Why this code is not working for sum of even integers?

I am trying to find the sum of even integers, but it is not working. It only works for sum of integers after removing the if condition.
main()
{
int number, sum, upperlimit;
number=1;
sum=0;
std :: cout << "Please enter the number of digits:";
std :: cin >> upperlimit;
while(number<=upperlimit)
{
if(number%2==0)
{
sum = sum + number;
number = number + 1;
}
}
std :: cout << "sum of 1st " << upperlimit <<" Even digits is:" << sum;
}
When I am entering the digits not going any where.
if(number%2==0)
{
sum = sum + number;
number = number + 1;
}
Having the number+=1condition inside that ifmeans that it will only move on if the number is even. So once you reach 1, for example, it will stay as a 1 for ever.
main()
{
int number, sum, upperlimit;
number=1;
sum=0;
std :: cout << "Please enter the number of digits:";
std :: cin >> upperlimit;
while(number<=upperlimit)
{
if(number%2==0)
{
sum = sum + number;
}
number = number + 1;
}
std :: cout << "sum of 1st " << upperlimit <<" Even digits is:" << sum;
}

Pairs x,y verify equation

I have to build a program as bellow:
User enters 3 Integers: a, b, c
User enters one integer n, and then n integers (ascending, and different numbers)
Program checks all possible pairs (x,y) (with x!=y) of the numbers entered if verifies the equation ax^2 + by^2 = c and prints all pairs which verifies the equation.
I done the program as bellow:
#include<iostream>
using namespace std;
int main() {
int a,b,c,n,i,j;
cin >> a;
cin >> b;
cin >> c;
cin >> n;
int num[n];
for(i=0;i<n;i++) {
cin >> num[i];
}
for (i=0;i<n;i++)
for (j=i+1;j<n;j++) {
if(a*num[i]*num[i]+b*num[j]*num[j] == c) {
cout << "(" << num[i] << "," << num[j] << ")";
}
if(a*num[j]*num[j]+b*num[i]*num[i] == c) {
cout << "(" << num[j] << "," << num[i] << ")";
}
}
return 0;
}
I made it by O(nlogn) with two 'for' statements but i know it could be done by O(n).
NOTE THAT MY PROGRAM WORKS AND I DON'T NEED TO ADD EXPECTED OUTPUT AND MY CURRENT OUTPUT AS YOU SAID IN THE COMMENTS. I ONLY WANT IT TO BE O(N) not O(nlogn) -> I WANT AN OPTIMIZED VERSION OF THE CODE!
How can I do this?
Example of running program: a=1, b=1, c=20
Then n = 5
Then n numbers: 2 3 4 9 18
Program will show all pairs (x,y) which verifies the equation x^2 + y^2 = 20. In this case it shows (2,4)
and (4,2).
Thank you!
Assuming 0 based index...
Set i=0
Set j=n-1
While i<n or j>=0
Set sum=a(num[i]^2)+b(num[j^2)
If sum==c then found pair, and increase i
If sum<c increase i
If sum>c decrease j
I found exactly this problem solved here: http://lonews.ro/educatie-cultura/22899-rezolvare-admitere-universitatea-bucuresti-2015-pregatire-informatica.html and changed a bit to show the pairs (it originally shows the number of pairs).
#include <iostream>
using namespace std;
int main()
{
int a, b, c, n, i=0;
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "c = ";
cin >> c;
cout << "n = ";
cin >> n;
int s[n];
for(i=0; i<n; i++) {
cout << "s[" << i+1 << "] = ";
cin >> s[i];
}
int j=n-1;
i = 0;
while(j>=0 || i<n) {
if(a*s[i]*s[i] + b*s[j]*s[j] == c) {
cout << "(" << s[i] << "," << s[j] << ") ";
i++;
}
if(a*s[i]*s[i] + b*s[j]*s[j] < c) {
i++;
}
if(a*s[i]*s[i] + b*s[j]*s[j] > c) {
j--;
}
}
return 0;
}

Nested, dependant for loops: Summation formula and Big-O notation

Working under a time crunch here. Struggling to understand exactly what this problem is asking. Any help or pointers in the right direction would be greatly appreciated! Thanks in advanced.
The original problem is based on this given information:
for (int k = 0; k < 2*n; k++) {
cout << k << endl;
for (int i = k+1; i < n; i++)
{
m[i][j] = a[i][j] + b[i][j];
cout << m[i][j] << endl;
}
cout << i * k << endl;
}
For T(n) = http://www4c.wolframalpha.com/Calculate/MSP/MSP63941h503ff0a609230100002eieg6bhfe5gi70g?MSPStoreType=image/gif&s=23&w=167.&h=49.
And here is my problem:
Modify the code above to find the number of times the basic operation occurs (i.e. how many times does it go in the inner for loop?).
include
using namespace std;
int main()
{
int count = 0;
int n = 10;
for (int k = 0; k < 2*n; k++) {
cout << "outer: " << k << endl;
for (int i = k+1; i < n; i++) {
cout << "\tinner: " << i << endl;
count++;
}
}
cout << count << endl;
}
Write a summation based on the output of Step 1
Based on this, is T(n) equivalent to O(n) or O(n^2)
I'm confused about specifically what part 2 is asking for. But I found:
http://www4c.wolframalpha.com/Calculate/MSP/MSP4561hgb5f47a07e05g00000112a53ahh0670che?MSPStoreType=image/gif&s=30&w=109.&h=49.
To me this looks like O(N^2)?
I apologize for the formatting. I'm on mobile.
Let me see if I guide:
1. I think the count should be inside like this:
int main() {
int count = -1;
int n = 10;
for (int k = 0; k < 2*n; k++) {
count = 0;
cout << "outer: " << k << endl;
for (int i = k+1; i < n; i++) {
cout << "\tinner: " << i << endl;
count++;
}
cout << count << endl; //<<<here
}
}
Now collect the output (#here marker) and form a formula for the summation. I think this is Task#2.
Based on your formula (or summation) you will be able to generalize whether its o(n) or o(n^2).
This is definitely not linear.

knapsack program, slow running time

i modified some code from internet to meet my requirements, but unfortunately this program seems to run a bit slow. im not sure whether its my computer or the program itself is slow.
int max(int a, int b)
{
return (a > b) ? a : b;
}
int knapSack(int W, int wt[], int val[], int n)
{
if (n == 0 || W == 0)
return 0;
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);
else
return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}
int main()
{
char exeAgain='n';
do
{
cout << "Enter the number of items in a Knapsack : ";
int n, W;
cin >> n;
int val[n], wt[n];
for (int i = 0; i < n; i++)
{
val[i]=(rand()%100)+1;
wt[i]=(rand()%100)+1;
cout << "Item Number "<< i+1 << " value "<<val[i]<<" weight " << wt[i] << endl;
}
cout << "Enter the capacity of knapsack : ";
cin >> W;
cout << "The total profit is " << knapSack(W, wt, val, n)<< endl;
cout<<"Would you like to execute this program again? [Y/N] : ";
cin>>exeAgain;
}
while(exeAgain == 'y' || exeAgain == 'Y');
return 0;
}
is it normal for this program to run slow? (the input is 200 & 1500)
smaller input is fast, but when i use big number, the program slows down.
The Knapsack Problem is famously NP-Complete, which means in simple terms that as the size of your input increases, the time to solve it increases astronomically. So yes, it is completely normal for your program to run slowly at larger inputs.
If you research around, you'll find a lot of work done on the problem, including various strategies to run faster than a first attempt, or heuristics for a good-but-not-perfect solution, which will run faster than something looking for a perfect solution.

Resources