Issue with using multiple relational operators in C - c

I'm new to programming, but I searched for this topic before asking and still can't figure out what my program is doing wrong.
I have this:
int i;
do
{
i = get_int("Enter positive integer between 1-10: \n");
}
while(1>i && i<10)
I want to ask the user for a positive integer between one and ten. it doesn't accept anything less than one, which is good, but it will take anything positive. I understand how I can't do 1>i<10 since it reads it from left to right but I can't get it to recognize it has to follow both operators. What is my issue?

You probably want the loop to run the loop as long as user inputs a number between 1 to 10. Your condition in the while loop isn't correct. It should be as follows -
while(i>1 && i<10); # runs as long as i is in range 1 to 10
However, If you want to break the loop as soon as the user inputs any number inside the 1 to 10 range, then you should use the following -
while(!(i>1 && i<10)); # runs as long as i is outside the range 1 to 10

i can't get it to recognize it has to follow both operators.
Why would it be more applicable when the integer has to meet both criteria?
do {
....
} while(test);
When the test returns true, the input is re-tried as the loop iterates again. What is the criteria for re-trying, not what is the criteria for passing.
Input only needs to fail one of two tests to re-try: too low or too high. Hence the need for "or" (||).
} while(i < 1 || i > 10);

Your loop condition is incorrect. You should have used logical OR instead of logical AND.
This worked for me.
do
{
i= get_int ("Enter positive integer between 1-10: \n");
} while (i<1 || i>10);

you have been mistaken (syntax mistake) inside the while expression (2 mistakes their, the logic is not right and a syntnatx error with 1<i) - see fixes inline:
int i = 0; /*its better if you initialize the i here*/
do
{
i= get_int ("Enter positive integer between 1-10: \n");
}
while((i > 1) && (i < 10));

I want to ask the user for a positive integer between one and ten.
I think you want an integer in the range with inclusive 1 and 10.
When how will look such a condition of a valid positive integer?
It will look the following way
1 <= i && i <= 10
So the do while loop must continue its iterations while this condition is not true. So in the condition of the loop you should write a negation of the above condition
int i;
do
{
i= get_int ("Enter positive integer between 1-10: \n");
} while ( !( 1 <= i && i <= 10 ) );
If to remove the parentheses then the condition will look like
int i;
do
{
i= get_int ("Enter positive integer between 1-10: \n");
} while ( 1 > i || i > 10 ) );

Related

How will the value of i be incremented here? [duplicate]

This question already has answers here:
For vs. while in C programming?
(19 answers)
Closed 5 months ago.
This is a approach for Weather a number is prime or not
QUESTION:
int main()
{
int i, num, b;
printf("ENTER A NUMBER : \n");
scanf("%d", &num);
for (i = 2; i <= num - 1; i++)
{
if (num % i == 0)
break;
}
if (i == num)
printf("PRIME");
else
printf("NOT A PRIME");
return 0;
}
How will the value of i will be incremented if loop is completed..The condition for stopping is num-1 then how in next statement value of i will be == num
Ex: if i enter 5 loop will run till 4 and value of i will be 4 then how will it will be == num..
Hope question is understood.
The body of the for loop is executed as long as the test condition is true. That means, when the loop stops executing because of the test condition (rather than because of the break), the test condition is false.
Therefore, when the loop ends this way, i <= num - 1 is false. Since num is 5, that means i <= 4 is false, which occurs when i has become 5.
I got your point , Let's analyze it together
First let's be clear about prime numbers
A prime number is a number that is only divisible by itself and one
so , if we iterate from 2 till the number - 1 we are including all the numbers in range 2 & number-1 and in case any of those numbers are divisible by our variable
then it's not a prime and we break the loop before it reaches number-1
I see you're confused in the stopping condition
the stopping condition is number!
the loop is valid till number -1
then it increments
so i will be equal to the number and the condition of the loop is not satisfied
in this case we can say that we reached all numbers between 2 and number -1 and found nothing divisible by our variable
hence it's prime
else if the counter i didn't reach the number itself this means that the loop went into a break
and a break means we found a divisible integer
so it's not prime
Hope this helped!

Enforcing range in an array in C

Quick, probably super basic question. If I declare an array of 10 doubles and prompt a user to input how many double they want in the index (between 1 and 10, obviously), how would I enforce that range? I assume with an if/else statement, but is there a more optimal way to enforce that range?
Again, probably really simple. I'm new so not yet familiar C++ or JavaScript.
Get that no. of elements from user till that no. is not within your range.
Say n is number that you want in range 1 to 10.
Solution:
int n = 0;
while(n<1 || n>10) {
printf("Enter Correct value on n i.e. within range 1 to 10:\t");
scanf("%d", &n);
}
Another solution maybe if you wrap the value within the required range using % (modulo) operator.
int n;
int arr[10];
printf("Enter a number : ");
scanf("%d",&n);
printf("%d",arr[n%10]);
The expression n%10 will always result in a value between 0 to 9.
Edit (for a better validation):
#include<stdio.h>
main()
{
int x, n;
int arr[]={0,1,2,3,4,5,6,7,8,9,10,11,12};
printf("Enter a number : ");
if( scanf("%d",&n)!=1 )
{
printf("Not a valid integer!!");
return;
}
n=(n<0)?-n:n;
printf("%d",arr[n%10]);
}
First you should read the documentation because this is a very basic example.
Second avoid requesting code here. You should always try to found solution then post your code and your error here to correct it.
You can try this:
#include<stdio.h>
int main(){
int n = 0;
while(!(n > 1 && n < 10)){
printf("Enter an integer between 1 and 10: \n");
scanf("%d", &n);
}
}

Why is my loop not going infinite

#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n;
printf("Please give me an integer greater than zero!\n");
n=GetInt();
if(n<0)
{
printf("You are giving me a bad value!\n");
return 1;
}
for(int i=n-1;i<n;n--)
printf("%d\n",n);
return 0;
}
I would like to know why the loop is not going to infinity if the user enters in a number for n. Lets say that the user puts in 40 for n; wouldn't i always be n-1, so 39 and n being 40, then i becomes 38 when n becomes 39 and so on — so wouldn't that make an infinite loop?
for(int i=n-1;i<n;n--)
Lets draw a (really short) table for n = 40:
i | n
-----+-----
39 | 40 i < n ? true
39 | 39 i < n ? false
Thus, we'll exit the loop after the 1st iteration.
Clarification:
I guess you're confused because you think that i is updated in each iteration, but that's the point - it doesn't, its value is fixed and only n is changing.
This loop only runs once. Consider:
for(int i=n-1;i<n;n--)
With n == 40, on the first iteration, i = 39.
The condition i < n is true (39 < 40 == true), so we go in to the loop for the first time.
At the end of the first loop, n gets decremented to 39
The condition i < n is false (39 < 39 == false), so we don't get a second time through the loop.
Now, what happens if we make n increase instead of decrease? Will that run forever?
for(int i=n-1;i<n;n++)
The answer is "maybe, but probably not":
Eventually, n will reach the largest value that can be stored in an integer, INT_MAX (defined in limits.h, and on my system it is 2,147,483,647).
Making an integer larger than INT_MAX causes integer overflow.
The result of integer overflow on a signed integer is undefined, which means the result could be anything (and indeed, your program could crash).
On most systems, however, the value will probably wrap around to INT_MIN, or -2,147,483,648.
If this happens, i < n will be false, and your loop will terminate.
But, since integer overflow on signed integers is undefined behaviour, you can't be sure that this will happen. It is better to write your program to avoid this situation.
If you really want it to run forever - just write:
while(1) { ... }
or
for(;;) { ... }
These two loops have the advantage that they are common ways to write an infinite loop, and so they are easy for other programmers to read.
The reason is that i is never decremented, so it does only 1 loop:
i=39 n=40
i=39 n=39 -> stop
In order to decrement also i you should write:
for(int i = n-1;i<n;n--,i--)
i is only ever set once at the start of the loop. For example if the user enters 10 then i is 9 for the 1st iteration. By the 2nd iteration n is decremented by 1 and i is still 9.
n will underflow somewhen because int is signed and has a value range of -2147483648 to 2147483647 for example (x86).
Somewhen n will get more positive than i.
Edit:
The loop has at most 1 iteration.
Edit 2:
The loop would have no iterations if n would have the value -2147483648 for example because -2147483648 - 1 will make the value positive (two complement integer arithmetic). But this could never the case because the pre condition is that n may not be negative.
Your for loop:
for(int i=n-1;i<n;n--) {
printf("%d\n",n);
}
Translates into the following while loop:
{
int i = n - 1;
while (i < n) {
printf(%d\n", n);
n--;
}
}
The first clause of the for statement performs initialization. It is not repeated at each iteration, but only once. Thus, i never changes value, and so the loop ends after a single iteration.
This happens because you are decrementing n. At the second iteration i < n is false, you are exiting from the loop.
What will happen is:
//Example n = 100
for (int i = 100 - 1; 99 < 100; 100--)
//We now have 99 < 99 on the next loop
//After that you will have 99 < 98 etc.. it will only run once
To make the loop you want use:
for(int i = n-1; i > n ; n--)
To make an endless loop use:
for(;;) //or while(true)
your condition is wrong in the for loop..in your loop i is not changing only n is changing
try this
for(i=n-1;i<n;i--)
{
printf("%d\n",i);
}
you written perfect for loop...
for(int i=n-1;i
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
for(i=0;;)
{
printf("%d",i);
}
return 0;
}
or you can do anything else....
to put in infinite simply make ;; in the other two condition in loop.

Compound conditions using while loop in C.

The program is ignoring Stop when amt is 0 until after 10 numbers have been entered. The program also doesn't stop after 10 numbers have been entered. Where is my error?
main() {
int amt;
int tot = 0; /* running total */
int i = 0; /* counts number of times in loop */
while (amt!=0 || i < 10)
{
printf("Enter a number (enter 0 to stop): ");
scanf("%d", &amt);
tot = tot + amt;
i++;
}
printf("The sum of those %d number is %d.\n", i, tot);
}
Your test is happening before amt is assigned. Thus its results are undefined. This test should be moved to the end of the iteration, i.e. a do/while. Whilst you could assign amt to some non-zero value this feels slightly untidy to me.
And surely you mean to use logical AND rather than logical OR? You only want to continue iterating if both amt is non-zero AND i<10.
Of course, if you did move the test to the end of the iteration then you would have to account for the fact that i had been incremented inside the loop.
In order to stop after 10 numbers or amt=0 (whichever first is met) you'll have to change the loop condition to while (amt!=0 && i < 10)
int amt;
Since you do not initialize it. It has some random value and that causes the Undefined Behavior in your program.
You should always initialize local variables with values.

Decrementing while loop in c

Is it possible to decrement the array size in a while loop in C by more than x--. For example, can you decrement an array by a third of the array size with each iteration?
int n = 10;
while (n < 0)
// do something
(round(n/3))-- // this doesn't work, but can this idea be expressed in C?
Thank you for the help!
You can use any expression:
int n = 10;
while (n > 0) // Note change compared with original!
{
// Do something
n = round(n/3.0) - 1; // Note assignment and floating point
}
Note that you can only decrement variables, not expressions.
You could also use a for loop:
for (int n = 10; n > 0; n = round(n/3.0) - 1)
{
// Do something
}
In this case, the sequence of values for n will be the same (n = 10, 2) whether you round using floating point or not, so you could write:
n = n / 3 - 1;
and you'd see the same results. For other upper limits, the sequence would change (n = 11, 3). Both techniques are fine, but you need to be sure you know what you want, that's all.
Yes, it is possible to add or subtract any number to your variable n.
Usually, if you want to do something a very predictable number of times, you would use a for loop; when you aren't sure how many times something will happen, but rather you are testing some sort of condition, you use a while loop.
The rarest loop is a do / while loop, which is only used when you want to execute a loop one time for certain before the first time the while check occurs.
Examples:
// do something ten times
for (i = 0; i < 10; ++i)
do_something();
// do something as long as user holds down button
while (button_is_pressed())
do_something();
// play a game, then find out if user wants to play again
do
{
char answer;
play_game();
printf("Do you want to play again? Answer 'y' to play again, anything else to exit. ");
answer = getchar();
} while (answer == 'y' || answer == 'Y');
There is no array in your code. If you wan't n to have a third of its value on each iteration, you can do n /= 3;. Note that since n is integral then the integral division is applied.
Just like K-Ballo said there is no array in your example code but here is an example with an integer array.
int n = 10;
int array[10];
int result;
// Fill up the array with some values
for (i=0;i<n;i++)
array[i] = i+n;
while(n > 0)
{
// Do something with array
n -= sizeof(array)/3;
}
But be careful in the example code you gave the while loop is checking if n is less than zero. As n is intialised to 10 the while loop will never be executed. I have changed it in my example.

Resources