Count value resets every time the for loop reiterates - c++

#include<bits/stdc++.h>
using namespace std;
int check(){
int p,q;
int count=0;
cin>>p>>q;
if(q-p>=2){
count++;
}
cout<<count;
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
check();
}
}
How to carry forward the value of 'count' in multiple iterations of for loop. Everytime the loop reiterates the 'count' value sets to '0' again but I want it to store values from previous iterations. Since the loop reiterates 'n' but everytime the loop enters, the value of count sets back to 0.
Is there something I can do with the initialization of count (count=0) ??

Every time you enter the function check, you initialize the local variable count to zero. Since you need to keep track of the total number of items that satisfy your condition, you should either place it as global variable or, more correctly, initializing the variable inside the caller function and pass it to the callee as a reference.
Here is the code with the second solution, without the #include<bits/stdc++.h> directive (which is not suggested).
#include <iostream>
int check(int& count){
int p,q;
std::cin>>p>>q;
if(q-p>=2){
count++;
}
std::cout<<count;
}
int main(){
int count = 0;
int n;
std::cin>>n;
for(int i=0;i<n;i++){
check(count);
}
}

Related

Memoizing Vector not taking values in a recursive function's return statement

With this code I was trying to calculate unique ways to reach a certain sum by adding array elements with a dynamic programming approach, the program works correctly but takes more time than expected so I checked if it is storing calculated values in the my vector, but it not storing any values at all.
#include <iostream>
#include <vector>
using namespace std;
// recursive function to include/excluded every element in the sum.
long long solve(int N,int sum, int* coins, long long mysum, vector<vector<long long >> &my, long long j){
if (mysum == sum){
return 1;
}if (mysum>sum){
return 0;
}
if (my[mysum][j]!=-1){
return my[mysum][j];
}
long long ways = 0;
while (j<N){
ways+= solve (N,sum,coins,mysum+coins[j],my, j);
j++;
}
//Line in question
return my[mysum][j] = ways;
}
int main() {
// code here.
int N=3;
int coins[] = {1,2,3};
int sum =4;
int check = INT_MIN;
vector<vector<long long int>> my(sum+1,vector<long long int>(N+1,-1));
cout<< solve (N,sum,coins,0,my,0)<< " ";
// traversing to check if the memoizing vector stored the return values
for (int x=0; x<sum+1; x++){
for (int y=0; y<N; y++){
if (my[x][y]!=-1){
check = 0;
}
}
}
cout<< check;
return 0;
}
output: 4 -2147483648
It does store the values, your checking code is not correct.
Try this version in your check
for (int y=0; y<N+1; y++){ // N+1 not N
So, the problem is that j is incrementing because of the for loop. The function fills my[newsum][j] only after the for loop's scope is over. By that time j==N and only my[newsum][N] is filled, the preceding values of j are left empty. This can be solved by make another variable equal to j that isn't incremented.

Why does my function always return 0 instead of returning the sum result?

I just started learning C++, now I'm making a simple array sum function.
Why is my code output always 0? Does it mean that my function returns "0"?
If I put cout in the function, it shows the right sum result.
#include <iostream>
using namespace std;
int ArraySum(int arr[], int size){
int sum=0;
for(int i=0 ; i<size; i++){
cin >> arr[i];
sum +=arr[i];
}
return sum;
}
int main()
{
int n, sum;
cin >>n;
int arr[n];
ArraySum(arr, n);
cout << sum;
return 0;
}
You are not assigning the return value to the sum when it is returned.
You have 2 options:
pass a pointer to the sum, and dereference it inside ArraySum()
assign the value that is returned by ArraySum() to the sum int.
You forgot to assign ArraySum()'s return value to main()'s sum. As a result, main()'s sum is still uninitialized when you print it.
Change this:
ArraySum(arr, n);
to this:
sum = ArraySum(arr, n);
As a side note, you should know that this is not actually valid, standard C++:
int arr[n];
This is a "variable-length array" ("VLA" for short.) This works on some C++ compilers because they support VLAs as an extension. But relying on compiler-specific extensions is not recommended if you want your code to be portable to any other C++ compiler.
Use std::vector instead. This also has the benefit of not needing to manually keep track of the size. vector knows its own size.
So, use this instead:
#include <iostream>
#include <vector>
// Note the '&' here. That means a reference of the vector is passed,
// not a copy, so the original vector defined in main() is used when
// assigning the values we read with `cin`.
int ArraySum(std::vector<int>& arr)
{
int sum = 0;
for (int i = 0; i < arr.size(); i++) {
std::cin >> arr[i];
sum += arr[i];
}
return sum;
}
int main()
{
int n;
int sum;
std::cin >> n;
std::vector<int> arr(n);
sum = ArraySum(arr);
std::cout << sum;
}
(Also note that there is no need to return 0 at the end of main(). It happens automatically. Keep in mind that this is only true for main(). No other function that returns a value is allowed to omit the return statement. main() is a special case in this regard. But it doesn't hurt to return 0 anyway though. It's up to preference.)

Why this code doesn't allow me to receive the whole array?

#include <bits/stdc++.h>
using namespace std;
string bin(int n){
string x="";
while(n!=0)
{
int z=n%2;
x+=to_string(z);
n%=2;
}
return x;
}
int main(){
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
string x=bin(a[i]);
int u=x.size();
int cnt=0;
for(int g=0;g<u;g++)
{
if(x[g]=='1')
++cnt;
}
cout<<cnt<<' ';
}
cout<<'\n';
}
}
This code is given several test cases and each test case will have an array of n integers, for each element in the array I should count the number of ones in the binary representation of it. I wrote a function that expects an integer and returns a string containing the binary representation of it. But I wonder why my code does not end, and not allowing me to receive other numbers in array.
For instance, there's one test case and and only array of 2 integers if I inputted 1 and wait for ever to enter the second number, what's happening?
This is your bin function reduced to the bare minimum:
string bin(int n){
while(n!=0)
{
n%=2;
}
return {};
}
If n is even you will set it to 0 on the first iteration, otherwise you set it to 1 and never change it afterwards (1%2==1). Hence you have a endless loop. I won't spoil you the "fun" of completing the exercise, so I will just point you to using a debugger. If you step trough your code line by line you could have observed how n never changes and why the loop wont stop.
PS: (spoiler-alert) you might want to take a look at std::bitset (end of spoiler)

How to call a vector function and return a vector from a function

I am writing a program to shift the elements of a vector to the side by k number of times. I have the code ready, however, I have problems calling and returning the function which is of type vector. Please take a look at my code and give me the correct guidance as to what to put where I have commented with question marks.
#include <iostream>
#include<vector>
using namespace std;
vector<int> solution(vector<int> &A, int k);//function to shift the vector elements to the right k times
int main()
{
int no;// number of times to shift the vector
vector<int> arr;// array to be shifted
//initializing vectors
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
cout<<"write the no of times to rotate elements: "<<endl;
cin>>no;
solution(arr, no)//?????? dont know how to call the function
return 0;
}
vector<int> solution(vector<int> &A, int k){
int times=(k%A.size());// number of times to be shifted
int count=0;
//while loop to shift times number of TIMES
while(count<=times){
for(int i=0; i<A.size();i++)// FOR LOOP TO SHIFT EACH ELEMENT TO THE SIDE ONCE
{
if(A[i]!=A[(A.size()-1)])
A[i]=A[i+1];
else
A[i]=A[i-(A.size()-1)];
count++;
}
return A; // ??? how do I return the value of the vector to the main program?
}
}

Reversing an Array Results In SegFault

#include <iostream>
using namespace std;
/*
*
*/
int main() {
int k, in[k],reversea[k],i,m,n;
cin>>k;
for (i=0;i<k;i++){
cin>>in[i];
}
for (m=k-1;m>=0;m--){
for (n=0;n<k;n++){
in[m]=reversea[n];
}
}
for(i=0;i<k;i++){
cout<<reversea[i];
}
return 0;
}
I have no idea why it says segmentation fault even before i start debugging it. I compile another one on calculating the frequency of 1, 5, and 10 in an array of k numbers, and it says the same thing...
Here is the other one:
#include <iostream>
using namespace std;
int main() {
int k,i,m,n,count5,count1,count10;
int input[k];
cin>>k;
for (i=0;i<k;i++){
cin>>input[i];
}//input all the numbers
for(i=0;i<k;i++){
if (input[i]=1){
count1++;
}
if (input[i]=5){
count5++;
}
if (input[i]=10){
count10++;
}
}
cout<<count1<<"\n"<<count5<<"\n"<<count10<<"\n";
return 0;
}
Please help me. Thanks.
On this line
int k, in[k],reversea[k]
How are you supposed to initialize an array with k elements if k isn't initialized? The size of an array must be known at compile time not run time. If k isn't know until run time, use a std::vector
int k;
std::cin >> k;
std::vector<int> in(k);
std::vector<int> reversea(k);
Both your programs have two major faults.
You need to know the size of an array while creating it. In your code, k is still uninitialized and you are using this value as the size of your array. Instead, change it to
int k,i,m,n;
cin >> k;
int in[k];
int reversea[k];
While reversing the array, you should be filling reversea using values from in, and not the other way round. Also, you don't need 2 for loops, just use 1 for loop.
for (m=k-1; m>=0; m--){
reversea[m] = in[k-1-m];
}
In the second program, you again need to get the value of k before creating the array input[k].
You are testing for equality with a = instead of == . Change your code from
if (input[i]=1){
to
if (input[i] == 1) {