Code is printing only one multiple instead of 3 [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 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).

Related

My code is showing wrong output for a test case of leetcode [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Question:- https://leetcode.com/problems/intersection-of-two-arrays/
This is my code:-
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector <int> result;
for(int i=0;i<nums1.size(); i++){
for(int j=0;j<nums2.size();j++){
if(nums1[i] == nums2[j]){
result.push_back(nums1[i]);
break;
}
}
}
for(int i=0;i<result.size();i++){
for(int j=0;j<result.size();j++){
if(result[i] == result[j] and i!=j){
result.pop_back();
}
}
}
return result;
}
};
I am getting wrong output for this testcase:-
Input:-
nums1 = [61,24,20,58,95,53,17,32,45,85,70,20,83,62,35,89,5,95,12,86,58,77,30,64,46,13,5,92,67,40,20,38,31,18,89,85,7,30,67,34,62,35,47,98,3,41,53,26,66,40,54,44,57,46,70,60,4,63,82,42,65,59,17,98,29,72,1,96,82,66,98,6,92,31,43,81,88,60,10,55,66,82,0,79,11,81]
nums2 =[5,25,4,39,57,49,93,79,7,8,49,89,2,7,73,88,45,15,34,92,84,38,85,34,16,6,99,0,2,36,68,52,73,50,77,44,61,48]
Expected Output:-
[61,45,85,89,5,77,92,38,7,34,44,57,4,6,88,0,79]
My Output:-
[61,45,85,89,5,77,5,92,38,89,85,7,34,44,57]
Please tell where I am getting wrong
The problem is in the 2nd loop. You try to eliminate double elements, to get a unique result.
But, after having found a duplicate, you do not erase the duplicate, but use pop_back which deletes the last element of the vector that has nothing to do with the duplicate. This, you need to correct. But, be careful, then your loops would not work anymore.
So, best is to use a different approach. You could use the function std::set_intersection for that. Here you must sort theinput vectors at the beginning.
Also std::unique is available, also requires sorting.
And you could add you result elements to a container that can only hold unique values. Like a std::unordered_set and then later copy back the result to the vector.
Eaxmaple for set_intersetction:
int main() {
std::vector<int> nums1{ 61,24,20,58,95,53,17,32,45,85,70,20,83,62,35,89,5,95,12,86,58,77,30,64,46,13,5,92,67,40,20,38,31,18,89,85,7,30,67,34,62,35,47,98,3,41,53,26,66,40,54,44,57,46,70,60,4,63,82,42,65,59,17,98,29,72,1,96,82,66,98,6,92,31,43,81,88,60,10,55,66,82,0,79,11,81 };
std::vector<int> nums2{ 5,25,4,39,57,49,93,79,7,8,49,89,2,7,73,88,45,15,34,92,84,38,85,34,16,6,99,0,2,36,68,52,73,50,77,44,61,48 };
std::sort(nums1.begin(), nums1.end());
std::sort(nums2.begin(), nums2.end());
std::vector<int> v_intersection;
std::set_intersection(nums1.begin(), nums1.end(),nums2.begin(), nums2.end(), std::back_inserter(v_intersection));
for (int n : v_intersection)
std::cout << n << ' ';
}
Example for std::unordered_set:
#include <iostream>
#include <vector>
#include <unordered_set>
class Solution {
public:
std::vector<int> intersection(std::vector<int>& nums1, std::vector<int>& nums2) {
std::unordered_set<int> result{};
for (int i = 0; i < nums1.size(); i++) {
for (int j = 0; j < nums2.size(); j++) {
if (nums1[i] == nums2[j]) {
result.insert(nums1[i]);
break;
}
}
}
return { result.begin(),result.end() };
}
};
int main() {
std::vector nums1{ 61,24,20,58,95,53,17,32,45,85,70,20,83,62,35,89,5,95,12,86,58,77,30,64,46,13,5,92,67,40,20,38,31,18,89,85,7,30,67,34,62,35,47,98,3,41,53,26,66,40,54,44,57,46,70,60,4,63,82,42,65,59,17,98,29,72,1,96,82,66,98,6,92,31,43,81,88,60,10,55,66,82,0,79,11,81 };
std::vector nums2{ 5,25,4,39,57,49,93,79,7,8,49,89,2,7,73,88,45,15,34,92,84,38,85,34,16,6,99,0,2,36,68,52,73,50,77,44,61,48 };
std::vector result = Solution().intersection(nums1,nums2);
for (const int n : result)
std::cout << n << ' ';
}

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';

Return reference [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
My expected output of the following code is "1 -1 3 4 5 6".
(arr[1]=2 should change to arr[1]=-1). When I run this code,
nothing changes, and I can't understand why.
What would be the difference if parameter "seek" will be received by "find" function by value and not by reference?
When I declare that "seek" is a value, the program not running (0xC0000005)... but why does this happen?
#include <iostream>
int& find (int arr[], int size, int& seek)
{
for (int i; i<size; i++) {
if (arr[i]==seek) return arr[i];
}
return seek;
}
void print (int arr[], int size)
{
for (int i=0; i<size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
int main ()
{
int arr[]={1,2,3,4,5,6};
int size = sizeof arr / sizeof *arr;
int seek=2;
find (arr, size, seek) = -1;
print(arr, size);
return 0;
}
for (int i; i<size; i++) {
You need to initialise i here
for (int i = 0; i<size; i++) {
As for the second part - see #Some programmer dude's comment

the sum of the first five natural numbers [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
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;
}