I am supposed to write a program that asks the user for a positive integer value. The program should use a loop to get the sum of
all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of
1, 2, 3, 4, ... 50.
But for some reason it is not working, i am having trouble with my for loops but this is what i have down so far.
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int startingNumber = 1;
int i = 0;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
for (int i=0; i < positiveInteger; i++)
{
i = startingNumber + 1;
cout << i;
}
return 0;
}
I am just at a loss right now why it isn't working properly.
The loop is great; it's what's inside the loop that's wrong. You need a variable named sum, and at each step, add i+1 to sum. At the end of the loop, sum will have the right value, so print it.
try this:
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int startingNumber = 1;
cout << "Please input an integer upto 100." << endl;
cin >> positiveInteger;
int result = 0;
for (int i=startingNumber; i <= positiveInteger; i++)
{
result += i;
cout << result;
}
cout << result;
return 0;
}
I have the following formula that works without loops. I discovered it while trying to find a formula for factorials:
#include <iostream>
using namespace std;
int main() {
unsigned int positiveInteger;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
cout << (positiveInteger * (positiveInteger + 1)) / 2;
return 0;
}
You can try:
int sum = startingNumber;
for (int i=0; i < positiveInteger; i++) {
sum += i;
}
cout << sum;
But much easier is to note that the sum 1+2+...+n = n*(n+1) / 2, so you do not need a loop at all, just use the formula n*(n+1)/2.
mystycs, you are using the variable i to control your loop, however you are editing the value of i within the loop:
for (int i=0; i < positiveInteger; i++)
{
i = startingNumber + 1;
cout << i;
}
Try this instead:
int sum = 0;
for (int i=0; i < positiveInteger; i++)
{
sum = sum + i;
cout << sum << " " << i;
}
int result = 0;
for (int i=0; i < positiveInteger; i++)
{
result = startingNumber + 1;
cout << result;
}
First, you have two variables of the same name i. This calls for confusion.
Second, you should declare a variable called sum, which is initially zero. Then, in a loop, you should add to it the numbers from 1 upto and including positiveInteger. After that, you should output the sum.
You are just updating the value of i in the loop. The value of i should also be added each time.
It is never a good idea to update the value of i inside the for loop. The for loop index should only be used as a counter. In your case, changing the value of i inside the loop will cause all sorts of confusion.
Create variable total that holds the sum of the numbers up to i.
So
for (int i = 0; i < positiveInteger; i++)
total += i;
Related
#include <iostream>
using namespace std;
int main()
{
int product;
int n;
int num1;
int num2;
cout << "Enter the number of numbers you'll input: ";
cin >> n;
int numbers[n];
for(int i = 0; i < n; i++){
cout << "";
cin >> numbers[i];
}
for(int i = 0; i < n; i++){
for(int m = 0; m < n; m++){
if(i != m){
product = numbers[m] * numbers[i];
if(product < numbers[m - 1] * numbers[i] && i != m - 1){
product = numbers[m - 1] * numbers[i];
num1 = numbers[m - 1];
num2 = numbers[i];
}
}
}
}
cout << "" << num1 << " " << num2 << "" << endl;
return 0;
}
This is what I've been able to do so far. Sometimes it works fine and sometimes it doesn't. It depends on the order of the numbers. I noticed that the product is the correct value but when I print the two numbers that get multiplied they aren't correct.
I want it to print the two numbers.
In your example you overwrite the product without checking and also you constantly calculate products regardless.
Just go through the Array once, on your way you compare for the smallest two negative numbers and same time for the largest positive numbers. In the end you are left with the factors forming the largest possible product from
either direction, this you only have to compare and automatically you held your factors too.
So in this program, I have to do multiplication in a very tedious fashion and for the second loop, the for loop, I'm multiplying one variable by 2 and the output is the product of that multiplication I am wondering how I could go about taking those output values and adding them together. The code and output of the code are below
#include <iostream>
using namespace std;
int main()
{
cout << "Time to do some Martian Math" << endl;
// variables for math
int righthandnum;
int lefthandnum;
cout << "Please enter two numbers" << endl;
// get values to do the martian math
cin >> lefthandnum;
cin >> righthandnum;
//while loop for right hand number
int i = 0;
while (righthandnum >= 1 ) {
//cout << righthandnum << endl;
//if to find out if any values are odd
if (righthandnum % 2 == 0) {
i -= 1;
}
righthandnum = righthandnum / 2;
i++;
}
int num;
for (num = 1; num <= i; num++) {
lefthandnum = lefthandnum * 2;
//lefthandnum + lefthandnum;
cout << lefthandnum << endl;
}
return 0;
}
The output is
Time to do some Martian Math
Please enter two numbers
50
30
100
200
400
800
Thank you so much for any help!
I don't know if this is what you are looking for but maybe a stack or an array might help you
with the array (the easy way), you make a list of N size for the data as an example:
int values[10];
for(int i = 0; i < 10; i++){
std::cin>>values[i];
}
for(int i = 0; i < 10; i++){
std::cout<<"List element "<<i<<": "<<values[i]<<std::endl;
}
while the stack as I've used it it's a bit more complex and requires pointers.
this is a video (sorry it's in Spanish): https://youtu.be/joAw2jWgZqA
here is my problem.The program needs to print out the number of numbers in the range between m and n which have different digits.For example:m=97,n=104;output:5.I seem to have problem with comparing the numbers and finding a way to check if there are 2 same digits.Here what I've written up till now:
enter code here
#include <iostream>
using namespace std;
int main()
{
int m, n;
cout << "m=";
cin >> m;
cout << "n=";
cin >> n;
for (int i = m; i <=n; ++i)
{
if (i >= m && i <= n)
{
while (i > 0)
{
m=i%=10;
i/= 10;
cout << m;
}
}
}
system("pause");
return 0;
}
If you can give me the easiest possible solution.Thanks in advance
The best way to do this is to break it down into two parts. The main part is responsible for incrementing the number set (which is easiest if the variables are integers) and the second part is to compare each part of the number to see if a number has been repeated (which is best done as a string).
So first I would define the method responsible for determining if the value has all distinct digits:
bool hasDistinctDigits(int m) {
string number = to_string(m);
for (string::size_type i = 0; i < number.size(); i++) {
for (string::size_type j = i + 1; j < number.size(); j++) {
if (number[i] == number[j]) return false;
}
}
return true;
}
This should be pretty easy to understand. First we need to convert the number to a string. Then we use 2 loops to determine if a character is repeated in a higher index. For example, with the number 102, it will compare the following sets: {1, 0}, {1,2}, {0, 2}
Then in the main function, I would call it like this:
int main()
{
int m, n, matched = 0;
cout << "m=";
cin >> m;
cout << "n=";
cin >> n;
for (int current = m; current <= n; ++current){
if (hasDistinctDigits(current)) {
cout << current << " is distinct" << endl;
matched++;
}
}
cout << "Total Matched: " << matched << endl;
system("pause");
return 0;
}
I am trying to write a program to count each number the program has encountered. by putting M as an input for the number of the array elements and Max is for the maximum amount of number like you shouldn't exceed this number when writing an input in the M[i]. for some reason the program works just fine when I enter a small input like
Data input:
10 3
1 2 3 2 3 1 1 1 1 3
Answer:
5 2 3
But when I put a big input like 364 for array elements and 15 for example for max. the output doesn't work as expected and I can't find a reason for that!
#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include<conio.h>
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int checker[1000];
int element_cntr = 0;
int cntr = 0;
int n = 0;
void main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue>> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
checker[i]= M[i] ;
element_cntr++;
if (M[i] > Max)
{
cout << "the element number " << element_cntr << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (M[n] == checker[j])
{
cntr+=1;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
n++;
}
}
You have general algorithm problem and several code issues which make code hardly maintainable, non-readable and confusing. That's why you don't understand why it is not working.
Let's review it step by step.
The actual reason of incorrect output is that you only iterate through the first Max items of array when you need to iterate through the first Max integers. For example, let we have the input:
7 3
1 1 1 1 1 2 3
While the correct answer is: 5 1 1, your program will output 5 5 5, because in output loop it will iterate through the first three items and make output for them:
for (int i = 0; i < Max; i++)
for (int j = 0; j < ArrayValue; j++)
if (M[n] == checker[j]) // M[0] is 1, M[1] is 1 and M[2] is 1
It will output answers for first three items of initial array. In your example, it worked fine because the first three items were 1 2 3.
In order to make it work, you need to change your condition to
if (n == checker[j]) // oh, why do you need variable "n"? you have an "i" loop!
{
cntr += 1;
}
It will work, but both your code and algorithm are absolutely incorrect...
Not that proper solution
You have an unnecessary variable element_cntr - loop variable i will provide the same values. You are duplicating it's value.
Also, in your output loop you create a variable n while you have a loop variable i which does the same. You can safely remove variable n and replace if (M[n] == checker[j]) to if (M[i] == checker[j]).
Moreover, your checker array is a full copy if variable M. Why do you like to duplicate all the values? :)
Your code should look, at least, like this:
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int cntr = 0;
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue >> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
if (M[i] > Max)
{
cout << "the element number " << i << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (i == M[j])
{
cntr ++;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
}
return 0;
}
Proper solution
Why do you need a nested loop at all? You take O(n*m) operations to count the occurences of items. It can be easily counted with O(n) operations.
Just count them while reading:
using namespace std;
int arraySize;
int maxValue;
int counts[1000];
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> arraySize >> maxValue;
int lastReadValue;
for (int i = 0; i < arraySize; i++)
{
cin >> lastReadValue;
if (lastReadValue > maxValue)
cout << "Number " << i << " is bigger than maxValue! Skipping it..." << endl;
else
counts[lastReadValue]++; // read and increase the occurence count
}
for (int i = 0; i <= maxValue; i++)
{
if (counts[i] > 0)
cout << i << " occurences: " << counts[i] << endl; // output existent numbers
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int howmany;
int i=0;
cout <<"How many integers you want to add,just enter the number.\n";
cin >> howmany;
while (i < howmany)
{
int sum = 0;
sum = sum +i;
i++;
cout << sum << endl;
}
system ("pause");
return 0;
}
what is the mistake? It gives me list of numbers rather than their sum.I have tried to change order of statements in loop body but still problem not solved.
Initialise sum=0 outside the loop. Because in your code every time you loop, the varaible sum is set to 0.
Change like this
int sum = 0;
while (i < howmany)
{
sum = sum +i;
i++;
cout << sum << endl;
}
Declare the sum variable out side the loop.
Or
you can declare a static variable inside loop (static variable will
be initialized once)
int main()
{
int howmany;
int i=0;
cout <<"How many integers you want to add,just enter the number.\n";
cin >> howmany;
int sum = 0; //Declare here
while (i < howmany)
{
sum = sum +i;
i++;
}
//Display the result after the while loop.
cout << sum << endl;
system ("pause");
return 0;
}