the sum of the first five natural numbers [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I wanna get the sum of the first five natural numbers, but there in this this code something is wrong, need to find the misstake ? Help
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int i = 1, thesum;
while(i <= 5)
{
thesum += i;
i++;
}
cout << thesum;
return 0;
}

You haven't initialized thesum variable. Initialize it to 0.
int i = 1, thesum = 0;
Otherwise it will invoke undefined behavior.

As it was already pointed out you did not initialize local variable thesum. So it has some arbitrary value.
Also there is no any need to include header <cstdlib> because no one declaration from it is used.
As variable i is not used outside the loop it is better to make it a local variable of the loop.
So I would rewrite the program the following way
#include <iostream>
using namespace std;
int main()
{
const int N = 5;
int theSum = 0;
for ( int i = 0; i < N; i++ ) theSum += i + 1;
cout << "The sum of first " << N << " natural numbers is " << theSum << endl;
return 0;
}

Related

what will bw the output of this code? c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
#include <iostream>
using namespace std;
int f(int i){
int k=0;
if(i>0)
{
int k=i*10;
}
else {
int k= i++;
}
cout <<k;
return i;
}
int main()
{
cout << f(1);
cout << ".";
cout << f(0);
return 0;
}
This is the code, compiler shows "01.01" which i quite don't understand, any help will be very much welcomed!
int k = i * 10; and int k = i++; are declarations of k that shadow the outer k. The statement std::cout << k; in the outer scope therefore always outputs zero.
The only effect of the if body is to increase i by 1. And it only does that if i is zero (or less). That value of i is returned printed.
Thus the output is 01.01. Armed with a line by line debugger, the shadowing effect will be obvious.

Code is printing only one multiple instead of 3 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I was writing a code which displayed first three multiples of an integer using functions. But here when I run this it shows only the first multiple.
#include <iostream>
#include <vector>
// Defined first_three_multiples() here:
std::vector <int> first_three_multiples(int num) {
std::vector <int> output;
for (int i=1; i<4; i++) {
output.push_back(num*i);
return output;
}
}
int main() {
for (int element : first_three_multiples(8)) {
std::cout << element << "\n";
}
}
Expected Output: 8 16 24
Actual Output: 8
You have put the return statement inside the for loop. It is advised to follow proper code indentations in order to avoid these kind of errors from happening again.
#include <iostream>
#include <vector>
std::vector<int> first_three_multiples(int num)
{
std::vector<int> output;
for (int i = 1; i < 4; i++) {
output.push_back(num * i);
# you put a return statement here, which returns only 8
}
return output; # this would return all three values
}
int main()
{
for (int element : first_three_multiples(8)) {
std::cout << element << "\n";
}
}
Simple error
for (int i=1; i<4; i++) {
output.push_back(num*i);
return output;
}
should be
for (int i=1; i<4; i++) {
output.push_back(num*i);
}
return output;
It pays to get your indentation right as it makes errors like this much easier to spot (and avoid in the first place).

Problem with calculating Primes within a given Range in C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Im trying to create a program that does various math operations, and i wanted to start with calculating prime numbers within a given range. However, when i try to execute the code, it just returns exit status -1. What is wrong with the program and how do i fix it?
#include <iostream>
#include <vector>
using namespace std;
void getPrimes(int min, int max) {
int range = max - min;
std::vector< int > possible_values;
for (int q = 0; q < range; q++) {
possible_values.push_back(min + q);
}
for (int i = 0; i < range; i++) {
int num_of_factors = 0;
int num = possible_values.at(i);
for (int c = 0; c < num; c++) {
if (num % c == 0) {
num_of_factors++;
}
}
if (num_of_factors == 0) {
std::cout << num << endl;
}
}
}
int main() {
int min, max;
std::cout << "min: ";
std::cin >> min;
std::cout << "max: ";
std::cin >> max;
getPrimes(min, max);
}
this loop should start from 2 because :
c%0 is undefined behavior
every number %1 is 0 so you can see why num_of_factors is never 0
for (int c = 2; c < num; c++) {
if (num % c == 0) {
num_of_factors++;
}
}

I have to calculate difference of sum of diagonal elements of a square matrix [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
In the following program:
#include <iostream>
#include <cmath>
using namespace std;
int diagonalDifference(int x[][],int n)
{
int sum1=0,sum2=0,y;
for(int i=0;i<n;i++)
{
sum1+=x[i][i];
sum2+=x[i][n-1-i];
}
y=abs(sum1-sum2);
return y;
}
int main()
{
int n,**z;
cin>>n;
int arr[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>arr[i][j];
}
}
z=diagonalDifference(arr,n);
cout<<x;
return 0;
}
I get a compilation error I don't understand.
error:declaration of 'x' as multidimensional array must have bounds for all dimensions except the first
Could you help me fix it?
int[][] is not a valid type:
int diagonalDifference(int x[][],int n)
You declare z as an int**:
int n,**z;
But you assign it an int:
int diagonalDifference(int x[][],int n);
z=diagonalDifference(arr,n);
And finally you print x which does not exist:
cout<<x;
As rules of thumb:
declare only one variable per line, and give it a meaningful name;
declare what possibly can as const;
Don't use C-style arrays unless you have to; prefer std::vector for instance;
don't use using namespace std;
much more you need to learn.
.
int diagonalDifference(int x**,int n) { /* .... */ }
int matrix_size = 0;
std::cin >> matrix_size;
std::vector<std::vector<int>> matrix{matrix_size, std::vector<int>{matrix_size}};
/* fill the matrix */
const int diag_diff = diagonalDifference(matrix, matrix_size);
std::cout << diag_diff << '\n';

how to initialize an array without any error? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
My code is following for finding maximum in an array
#include <iostream>
using namespace std;
int main(){
int i;
int array[i]={1,2,3,4,5}
int temp;
for(int i=0;i<6;i++)
{
if(array[i]>temp)
temp=A[i];
}
cout<<"the maximum number is "<<temp<<endl;
return 0;
}
but im getting error in line of initializing array why is that so? how do we initialize array?
You can't define the size of an array with a runtime variable.
To fix this you can use constexpr:
constexpr int i = 5;
int array[i]={1,2,3,4,5};
or:
int array[]={1,2,3,4,5};
In the latter the size is deduced by the compiler.
Otherwise, if you need a runtime size, you'll have to use std::vector or any other "dynamic" container from the standard library:
int i = ...;
std::vector<int> array(i); // reserve `i` cells
try this :
int array[]={1,2,3,4,5};
First of all variable i was not initialized
int i;
So it has some arbitrary value.
Secondly the size of a defined array shall be a constant exprssion. So even if i would be initialized this definition
int array[i]={1,2,3,4,5}
is also invalid. Moreover you forgot to place a semicolon after the closing brace.
Also you did not initialized variable temp
int temp;
And at last this control statement of the loop
for(int i=0;i<6;i++)
is also incorrect because the array has only 5 elements.
And one more identifier A was not declared
temp=A[i];
The correct code could look as
#include <iostream>
using namespace std;
int main()
{
const int N = 5;
int array[N] = { 1, 2, 3, 4, 5 };
int max = array[0];
for ( int i = 1; i < N; i++ )
{
if ( max < array[i] ) max = array[i];
}
cout << "the maximum number is " << max << endl;
return 0;
}