D
D
dima4512zaz2018-10-28 12:23:46
C++ / C#
dima4512zaz, 2018-10-28 12:23:46

How to implement a cyclic computing process?

I wrote a program, but it is not correct. I don't really understand cycles, I'm just learning. Can you explain what I should do next. The program was written in C++
Assignment.
Given two integers A and B (A < B). Find the sum of all integers from A to B inclusive.
#include "pch.h"
#include < iostream >
using namespace std;
int main()
{
setlocale(0, "");
int A, B;
cout << "Enter A : ";
cin >>A;
cout << "Enter B : ";
cin >> B;
int sum = 0;
for (int i = A; A <= B; i++)
{
sum = sum + i;
cout << "Sum of numbers from a to b = " << sum << endl;

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vasily Melnikov, 2018-10-29
@dima4512zaz

As already mentioned, change the loop condition to i <= B
and
cout << "Sum of numbers from a to b = " << sum << endl;
move out of the loop

D
dsadso, 2018-10-28
@dsadso

If you are learning a language, then you need a good book, not this one.
C++ is not something you can learn without a good book.
Nobody has surpassed Stephen Prat yet.
Now on the question: in the second line you need to add. And in the loop you find the number of elements, not their sum.
sum = sum + i;

P
Pavel, 2018-10-29
Yazovskikh @unepic

for (int i = A; A <= B; i++)
{
sum = sum + i;
cout << "Сума чисел от а до b = " << sum << endl;
}

There is an error in the loop exit condition. Should be i <= B. Also, just in case, it's better to make sum of type . long long

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question