I want to apply a while loop and have written that while (a!=-1); it should exit but it's printing "0" always and I don't know why. Can you explain?
#include <stdio.h>
int main()
{
long num;
int a,i,j;
int arr[10000];
float x;
while( a != -1)
{
scanf("%d",&a);
int sum=0;
for(i=0;i<a;i++)
{
scanf("%d",&arr[i]);
sum = sum + arr[i];
}
x = sum%a;
if (x == 0)
{
int z = sum/a;
int y=0;
for(j=0;j<a;j++)
{
if (arr[j]>z)
{
y = (arr[j] - z) + y ;
}
}
printf("%d",y);
}
else
printf("-1");
}
}
I think it is printing y; how to avoid so that it only exits?
First of all, you failed to initialize a before running the while loop, so the behavior of your program will be undefined and it could just terminate right away.
Second, you said "while(a!=0)" in your question but your code says "while(a != -1)". Which one is correct: 0 or -1? Maybe if you just changed the -1 to a 0 the program would behave as expected.
You want to write while( a != 0) but you actually have written while( a != -1).
Fix that. Then the loop will exit when you enter 0.
I got my answer actually i have to take my scanf("%d",&a); outside while loop ;
Related
#include<iostream>
using namespace std;
int main(){
int i = 1;
int sum;
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
cout << sum;
}
This is to print the sum of all even numbers till 1 to N.
As I try to run the code, I am being asked the value of N but nothing is being printed ahead.
For starters the variable sum is not initialized.
Secondly you need to increase the variable i also when it is an even number. So the loop should look at least like
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1;
}
In general it is always better to declare variables in minimum scopes where they are used.
So instead of the while loop it is better to use a for loop as for example
for ( int i = 1; i++ < N; ++i )
{
if ( i % 2 == 0 ) sum += i;
}
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
Let's step through this. Imagine we're on the loop where i = 2 and you've entered N = 5. In that case...
while(i <= N)
2 <= 5 is true, so we loop
if(i%2 == 0)
2 % 2 == 0 is true, so we enter this branch
sum = sum + i;
Update sum, then head back to the top of the loop
while(i <= N)
Neither i nor N have changed, so 2 <= 5 is still true. We still loop
if(i%2 == 0)
2 % 2 == 0 is still true, so we enter this branch again...
Do you see what's happening here? Since neither i nor N are updated, you'll continue entering the same branch and looping indefinitely. Can you think of a way to prevent this? What would need to change?
Also note that int sum; means that sum will have a garbage value (it's uninitialized). If you want it to start at 0, you'll need to change that to
int sum = 0;
You're looping infinitly when i is even because you don't increase it.
Better option would be this if you want to use that while loop :
while(i<=N)
{
if(i%2 == 0)
sum = sum + i;
i=i+1;
}
cout << sum;
If you don't need to do anything when the condition is false, just don't use an else.
No loops are necessary and sum can be evaluated at compile time if needed too
// use unsigned, the whole excercise is pointless for negative numbers
// use const parameter, is not intended to be changed
// constexpr is not needed, but allows for compile time evaluation (constexpr all the things)
// return type can be automatically deduced
constexpr auto sum_of_even_numbers_smaller_then(const unsigned int n)
{
unsigned int m = (n / 2);
return m * (m + 1);
}
int main()
{
// compile time checking of the function
static_assert(sum_of_even_numbers_smaller_then(0) == 0);
static_assert(sum_of_even_numbers_smaller_then(1) == 0);
static_assert(sum_of_even_numbers_smaller_then(2) == 2);
static_assert(sum_of_even_numbers_smaller_then(3) == 2);
static_assert(sum_of_even_numbers_smaller_then(7) == 12);
static_assert(sum_of_even_numbers_smaller_then(8) == 20);
return 0;
}
int main(){
int input; //stores the user entered number
int sum=0; //stroes the sum of all even numbers
repeat:
cout<<"Please enter any integer bigger than one: ";
cin>>input;
if(input<1) //this check the number to be bigger than one means must be positive integer.
goto repeat; // if the user enter the number less than one it is repeating the entry.
for(int i=input; i>0; i--){ // find all even number from your number till one and than totals it.
if(i%2==0){
sum=sum+i;
int j=0;
j=j+1;
cout<<"Number is: "<<i<<endl;
}
}
cout<<endl<<"The sum of all even numbers is: "<<sum<<endl;}
Copy this C++ code and run it, it will solve your problem.
There are 2 problems with your program.
Mistake 1
The variable sum has not been initialized. This means that it has(holds) an indeterminate value. And using this uninitialized variable like you did when you wrote sum = sum + i; is undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has undefined behavior.
This is why it is advised that:
always initialize built in types in local/block scope.
Mistake 2
The second problem is that you're not updating the value of variable i.
Solution
You can solve these problems as shown below:
int main(){
int i = 1;
int sum = 0; //INITIALIZE variable sum to 0
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1; //update(increase i)
}
cout << sum;
}
1For more reading(technical definition of) on undefined behavior you can refer to undefined behavior's documentation which mentions that: there are no restrictions on the behavior of the program.
I want to know why the value of i is not updating to i=0 when i == n-1, as I have written in the code. The bool flag is just there to check if the if statement was rendering at all or not (It is).
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int n, ans = 0;
scanf("%d", &n);
int s[n];
bool flag = false;
for (int i = 0; i < n; i++)
{
scanf("%d", &s[i]);
}
for (int i = 0; i < n; i++)
{
s[i] -= 1;
if (s[i] < 0)
break;
ans++;
if (i == (n - 1))
{
i=0;
flag = true;
}
}
printf("\n%d\n", ans);
printf("%d", flag);
}
return 0;
}
How do you know it's not doing what you want. I ran it and got this:
$ ./foo
1
2 3 4
5
1
$
The final value (1) is true. So it looks like it's doing it to me.
However, this is pretty terrible code. It's a really bad practice to muck with your iterator variable inside your loop like that. That's GOING to bite you. Furthermore, you're not going to go back to 0 -- you're going to go back to 1, because the next thing it does is increment the variable with your i++. So your if-statement sets i to 0 and your for-loop turns it into 1.
But this is just weird. If you need to run the loop multiple times, then wrap it in a larger loop.
Others have commented on printf. Personally, I disagree with them. There are times printf is completely valid. HOWEVER -- the way you're using it for such simple, unformatted stuff, isn't really one of them.
I changed the last printf to this:
cout << "Flag (raw): " << flag << ". Which means: " << (flag ? "True" : "False") << endl;
Output is this:
Flag (raw): 1. Which means: True
As you can see -- it's 1, which is not 0, so it's true.
Whenever I try to recurse in the function prime, my program crashes at that step. I think the problem is passing the function small as a recursion. What am I doing wrong?
#include <iostream>
using namespace std;
int smallest(int n) {
for( int x = 2 ; x <= n/2 ; x++){
if (n%x==0) {
return x;
}
else {
return 0;
}
}
}
int prime(int n, int(*small)(int)) {
int factor;
if (n == 1){
return 0;
}
else {
factor = n % small(n);
cout << small(n) << endl;
return prime(factor , small);
}
}
int main() {
prime(50 , &smallest);
return 0;
}
As the comments point out, when small returns 0, you continue recursing when you shouldn't. This can be solved with a small update to your base case:
if (n <= 1){
return 0 ;
}
Furthermore, it's worth pointing out that as it stands, your prime function will never call itself more than once. When you call smallest, you are guaranteed to get a prime number!
Hello I am trying to do a programming assignment that converts a binary number to a decimal. The problem states that I have to get the users input as a sting and if there is anything other than a 1 or a 0 in the users input it should give an error message then prompt them to give a new input. I have been trying for a while now and I cant seem to get it right can anyone help me?
so far this is my best attempt it will run every input of the string into a if statement but it only seems to care about the last digit i cant think of a way to make it so if there is a single error it will keep while loop statement as true to keep going.
#include <iostream>
#include <string>
using namespace std;
string a;
int input();
int main()
{
input();
int stop;
cin >> stop;
return 0;
}
int input()
{
int x, count, repeat = 0;
while (repeat == 0)
{
cout << "Enter a string representing a binary number => ";
cin >> a;
count = a.length();
for (x = 0; x < count; x++)
{
if (a[x] >= '0' &&a[x] <= '1')
{
repeat = 1;
}
else
repeat = 0;
}
}
return 0;
}
return 0;
}
Change your for loop as this:
count = a.length();
repeat = 1;
for (x = 0; x < count; x++)
{
if (a[x] != '0' && a[x] != '1')
{
repeat = 0;
break;
}
}
The idea is that repeat is assumed to be 1 at first (so you assume that your input is valid). Later on, if any of your input characters is not a 0 or 1, then you set repeat to 0 and exit the loop (there's no need to keep looking for another character)
look the below program. When compiled it, the loop is not terminating. That is not an expected behaviour. Anyone please explain this reason?
#include<iostream.h>
int main()
{
int nIntValue = 0;
int nTempVal = 100;
for( int nLoop = 1; nLoop <= 25; nLoop++ )
{
nTempVal = nTempVal / nLoop;
}
// Print the value of nIntVal
while( nIntVal == 0 )
{
nIntVal += nTempVal;
cout<<nIntVal;
}
return 0;
}
First of all, what is nIntVal?
Second, assuming its really nIntValue, when you enter the following loop:
while( nIntVal == 0 )
{
nIntVal += nTempVal;
cout<<nIntVal;
}
it is 0.
As for nTempVal, you are dividing 100 by (1*2*3*...*25). You are using int type which means all values are rounded. But even if you didn't, the exact result of the first loop would be 0.000000000000000000000006447 which is pretty close to zero.
So both nIntVal and nTempVal are 0, and you are stuck here (0+0 = 0 and the loop never ends).
nTempVal = 0. So the loop is not terminated.
You can easily find such error with debugger