Why am I getting two outputs in place of a single one? - c++

I'm writing a simple program and I am getting 2 outputs of the same data with a single cout statement. I think something went wrong with my loop, but I am not able to find where the problem is. If possible, please show me what I need to change; otherwise, I'd at least like to know why my logic is wrong.
My code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n ;
cin >> n;
vector<int> arr(n);
vector<int> a(n);
for(int arr_i = 0;arr_i < n;arr_i++){
cin >> arr[arr_i];
a[arr_i]=1;
}
int i,least,flag,count=n;
do{
cout<<count<<endl;
count=0;
flag=1;
for(i=0;i<n;i++){ //for getting least number
if(a[i]){
if(flag){
least=arr[i];
flag=0;
}
if(arr[i]<least){
least=arr[i];
}
}
}
for(i=0;i<n;i++){ // for actual logic
if(arr[i]<=0||!a[i]){
a[i]=0;
//continue;
}
else{
arr[i]-=least;
count++;
}
}
}while(count);
return 0;
}
Sample input:
6
5 4 4 2 2 8
Expected output
6
4
2
1
Actual output:
6
6
4
4
2
2
1
1
Problem statement
You are given N sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick.
Suppose we have six sticks of the following lengths:
5 4 4 2 2 8
Then, in one cut operation we make a cut of length 2 from each of the six sticks. For the next cut operation four sticks are left (of non-zero length), whose lengths are the following:
3 2 2 6
The above step is repeated until no sticks are left.
Given the length of N sticks, print the number of sticks that are left before each subsequent cut operations.
Note: For each cut operation, you have to recalculate the length of the smallest sticks (excluding zero-length sticks).

One noticed error: when substracting least from arr[i] and arr[i] becoming <=0 a[i] still stays non-zero, and at next iteration you getting least number the same as at previous iteration.
Other problem: your count is count of previous turn. At first iteration it equals 6, because condition if(arr[i]<=0||!a[i]) dont fulfill for any number from input.
After fixing this part:
// for actual logic
if (a[i]) {
arr[i] -= least;
if (arr[i] <= 0)
a[i] = 0;
else
count++;
}
it looks working nice.

Related

How should I fix this code wherein I need to print the first n numbers in the Fibonacci Series?(C++)

This particular Code was made on Dcoder on Android...
My question is,How am I still able to execute it if my input for n is less than 6..(Condition i>=6 is not fulfilled for the for loop right..)Also using this code I always get the answer as 1,2,3,5,8... and the number of terms printed is always more than the input of n..
Also I tried putting i<=0 but I get the same results...
#include <iostream>
using namespace std;
int a=0,b=1,x,i,n;
int main()
{
cout<<"This Program Gives You The List Of First 'n' Fibonacci Numbers:"<<endl
<<"Enter The Value Of 'n':"<<endl;
cin>>n;
if(n<1)
{
cout<<"Invalid Input"<<endl<<"Please Restart This Program And Enter A Natural Number."<<endl;
}
else
{
cout<<"The First "<<n<<" Fibonacci Numbers Are:"<<endl;
for(i;i>=6,i<=n;i++)
{
x=a+b;
a=b;
b=x;
cout<<x<<endl;
}
}
return 0;
}
But surprisingly the code below works..Why? And What is the fundamental difference between the two except that I intentionally print 0 and 1 in the second code...?Also I didn't find any difference when I used post increment and pre increment in my For Loop..Why?Also It would be really helpful to get some examples which behave differently with post and pre increment...
#include <iostream>
using namespace std;
int a=0,b=1,x,i,n;
int main()
{
cout<<"This Program Gives You The List Of First 'n' Fibonacci Numbers:"<<endl
<<"Enter The Value Of 'n':"<<endl;
cin>>n;
if(n<1)
{
cout<<"Invalid Input"<<endl<<"Please Restart This Program And Enter A Natural Number."<<endl;
}
else
{
cout<<"The First "<<n<<" Fibonacci Numbers Are:"<<endl;
cout<<"0"<<endl<<"1"<<endl;
for(i;i>=0,i<=n-2;i++)
{
x=a+b;
a=b;
b=x;
cout<<x<<endl;
}
}
return 0;
}
Your use of the comma operator is a problem and is leading you to believe that the condition is actually enforced.
This statement
i>=6,i<=n;
ignores the result (false if n==6) from i>=6, despite evaluating it and then proceeds to check if i<=n because that's how the comma(,) operator works in this context. Thus your loop still prints values when n is <=6. What you are looking for is
i>=6 && i<=n;
The && is the Logical AND operator which means that both the conditions need to be true for the statement to be true (and doesn't discard the Left Hand Side condition obviously).
As for why that loop runs for 7 times (one more than n if n is 6) that's because your loop essentially becomes:
for(i = 0; i <= 6; i++)
which shall run 7 times, starting from 0.
The same thing happens with your second piece of code, only this time that loop is essentially
for(i = 0; i<= n- 2;i++)
So, for a value of n as 6, you would have 5 iterations, which is what you see, i.e. the 5 terms after 0 and 1
This Program Gives You The List Of First 'n' Fibonacci Numbers:
Enter The Value Of 'n':
The First 6 Fibonacci Numbers Are:
0
1
1
2
3
5
8

I keep getting SIGTSTP error for my code but I am not able to figure out where is my code going out of bounds

I am trying to find the largest sum for the difference between 3 numbers in a given list inputed by the user but I keep getting SIGTSTP and I am not able to understand where my code in going out of bounds.
Here is my code:
#include <iostream>
#include<vector>
#include <algorithm>
using namespace std;
int main() {
// your code goes here
int t,n,z;
vector<long long int> a;
long long int max,min,k,x,sum;
cin>>t;
while(t--){
cin>>n;
while(n--){
cin>>x;
a.push_back(x);
}
max = *max_element(a.begin(),a.end());
min = *min_element(a.begin(),a.end());
int i=0,k=0;
//to find a element other than minimum or maximum element and assign it to k
while(i<3){
if(a[i]==max || a[i]==min)
continue;
else
k=a[i];
i++;
}
if(k==0)
k=a[0];
//sum
sum = abs(max-min) + abs(k-min) + abs(max-k);
cout<<sum;
}
return 0;
}
Input given:
3
3
2 7 5
3
3 3 3
5
2 2 2 2 5
int i=0,k=0;
while(i<3){
if(a[i]==max || a[i]==min)
continue;
else
k=a[i];
}
You set i to zero when you enter the loop. The loop will not exit so long as i is less than 3. But nothing in the loop changes the value of i. So i will always be less than 3 and the loop will never exit.
Learn to do some basic troubleshooting such as using a debugger or adding logging.
Also, there are no comments in this code. I have no idea what this loop is supposed to do, so can't give you specific suggestions on how to fix it.

I need better understanding on for loops

can someone explain me how this for loop works (Line 9 in code below), and also if you can show me a simple example with it can be very helpfull, thank you anyways!
1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5 int main(){
6 int n, a , b , ma=0,mb=1000000001;
7 cin >> n ;
8 cin >> a;
9 for( n--; n ; --n ){
10 cin >> b;
11 if(abs(a-b) < abs(ma-mb))
12 ma=a , mb=b;
13 else
14 if(abs(a-b) == abs(ma-mb) && ma+mb > a+b)
15 ma=a , mb=b;
16 a = b;
17 }
18 cout << ma << " " << mb;
19 return 0;
20 }
A for loop is simply another way to write a while loop. So this:
for( n--; n ; --n ){
...
}
is the same as this:
n--;
while(n) {
...
--n;
}
Which, in this specific case, is easier to read. First it decrements n, then does the loop, decrementing n again at the end of each loop, until that decrement causes n to evaluate to false by becoming 0.
This code smells a lot. If you give to n the value 10,it gives
9 (first time into loop, exectues n--)
every other iteration it executes --n till when n!=0 (which is the condition n
A for loop works the following way:
It runs for a certain number of times. We signify this with a condition. It has a start and an increment:
for (start ; condition ; increment )
{
// loop body
}
For loops and all loops are very useful when you want to perform repetitive tasks.
Lets say that you want to make a game and this game will have 3 rounds. Each one of those rounds can be implemented as an iteration of a for loop. It will look like this:
for(int round = 0; round < 3; ++round) {
// game round logic
}
In the above loop we start at 0. Once we reach 3, we would have already executed the for-loop 3 times. After each iteration of the for loop ++round gets executed, this increments the variable round by 1. We can increment it by a different value by doing: round+=2 or round*=2 etc.

When I tried to run the code I was getting the 2nd output as garbage value. Can anyone tell fault in that code

#include <iostream>
using namespace std;
int main()
{
int T,i,j,N,K;
cin >> T;
int n[T],x;
for(i=1; i<=T; i++)
{
cin >> N >> K;
for(int j=1; j<=N; j++)
{
cin >> x;
n[i]+=x/K;
x=0;
}N=0;K=0;
}
for(i=1; i<=T; i++)
cout << n[i] << endl;
return 0;
}
question is "Your program will be tested on one or more test cases.The first line of the input will be a single integer T, the number of test cases (1 ≤ T ≤ 100). Followed by the test cases, each test case is on two lines. The first line of each test case contains two integers N, the number of different candies (1 ≤ N ≤ 100), and K, the minimum number of candies which will make a kid happy as described above (1 ≤ K ≤ 100). The second line of each test case contains N integers, separated by a single space, which are the available number of candies of each type. There will be at least 1 candy and at most 100 candies of each type."
sample input: 2
3 2
4 5 7
3 8
4 5 7
sample output:
7
0
when the i tried the above code the answer that i got like:
input:2
3 2
5 6 8
2 2
9 1
output:
9
-880625041
When i tried to run the code i was getting the 2nd output as garbage value. Can anyone tell me the fault in that code
Here is the problem:
n[i]+=x/K;
this is equivalent to n[i]=n[i]+x/K; So it uses a prior value of n[i]. However, you haven't set any prior value to elements of the array n. So, initialise the array to 0 first.
for(i=0;i<T;i++)
n[i] = 0;
Also, in this code:
for(int j=1; j<=N; j++)
are you sure that N will always be less than T, the size of array? (take care of 0-based indexing as well).
Arrays in C and C++ are zero-based. Run your loops from 0 to N - 1 and T - 1.
You don't initialise your array values before using them. Formally your program behaviour is undefined. (I think you mean n[i]= rather than n[i]+=.)
Variable length arrays like int n[T] are compiler extensions. Do bear this in mind as it could affect portability.

Missing element in values entered in C++

The code takes an integer n and takes in n-1 elements. The elements entered are all the numbers from 1 to n, except one of them. We are supposed to find the missing element.
This solution is the fastest. However, I don't understand it.
Can anyone explain it ?
#include <iostream>
int main(){
int g,n,i,k;
std::cin>>n;
for(i=1; i<n; i++){
std::cin>>g;
k^=i^g;
}
std::cout<<(k^n);
}
Input:
10
3 8 10 1 7 9 6 5 2
Output:
4
This uses the fact that XOR is commutative and associative (so order doesn't matter), and that x^x == 0 for all x.
It takes the XOR of all numbers between 1 and n, and also xors it with all the input numbers. Any number that was input will be XORed twice into the final result, and therefore will be cancelled out. The only number remaining will be the number that wasn't input. This number was only XORed once, and therefore this will be the value of the result of all the XORs.
For the example you gave:
The input numbers are: 3 8 10 1 7 9 6 5 2
1^2^3^4^5^6^7^8^9^10 ^ 3^8^10^1^7^9^6^5^2 =
(1^1)^(2^2)^(3^3)^4^(5^5)^(6^6)^(7^7)^(8^8)^(9^9)^(10^10) =
4
Note that the code is written somewhat confusingly, because the order of XORs is not straightforward: it alternates between XORing an input and XORing the next number between 1 and n. This is only done to keep the code short. It would be clearer as:
k = 0;
for (i=1; i<=n; i++)
k ^= i;
for (i=0; i<n-1; i++) {
std::cin >> g;
k ^= g;
}
std::cout << k;