if (num1 == (1,2,3,4,5,6,7,8,9)){
*some command*
}
does this sequence work, if not can you guide me masters. I'm a beginner
Try this:
if(num1 >= 1 && num1 <= 9) {
// Some code
}
&& operator will make sure num1 should be between 1 to 9 including it (i.e. 1, 9). It will execute some code only if both the conditions are true.
If the numbers you're testing for are in a continuous range, you can bound the value with greater than and less than (or equals):
For example, if you're testing if an int n is one of 1, 2, 3, 4, 5, 6, 7, 8, 9, you can do this:
if(n >= 1 && n <= 9)
{
// Code
}
If, however, the numbers are not a continuous range you have no choice but to explicitly test every value. So, if you were checking if n was one of 13, 57, -3, 11, -66, 100, you could have to write it out completely (or use a switch statement or lookup table):
if(13 == n || 57 == n || -3 == n || 11 == n || -66 == n || 100 == n)
{
// Code
}
Alternatively (only for integral types):
switch (n)
{
case 13:
case 57:
case -3:
case 11:
case -66:
case 100:
// Code
break;
}
You may want to write a helper method in the latter case to make it more clear what you're testing for. e.g.:
if(IsAcceptableValueForTask(n))
Where IsAcceptableValueForTask returns an int representing the truth (1|0) of 13 == n || 57 == n || -3 == n || 11 == n || -66 == n || 100 == n
You can use
if (num1 == 1 || num1 == 2 || num1 == 3 || num1 == 4 || num1 == 5 || num1 == 6 || num1 == 7 || num1 == 8 || num1 == 9 ){
//code
}
If you want to check between a range of numbers you can use
if(num1 >= 1 && num1 <= 9) {
//code
}
You can also use switch statement for more convenience if the numbers are random and there are many conditions
Related
I am trying to create a date identifier using only if statements and a switch statement that can determine whether an inputted date is valid, what season the date is in and finally whether it is a leap year. I tried to get the component parts working independently first and got two of them working then tried them all together but I still can't get my switch statement working. I want my switch statement to show the season by checking both the day and month to see what season we are in but I'm not sure how to do that. Here is my code:
/* Switch statement to determine season for day and month */
// Using it with a "m" on it's own works, how do I get it working for specific days?
switch (m)
{
case 12:
case 1:
case 2:
if ((m == 12 && d >=21) || (m == 1) || (m == 2) || (m == 3 && m < 21))
printf("The season is Winter.\n");
break;
case 3:
case 4:
case 5:
if ((m == 3 && d >= 21) || (m == 4) || (m == 5) || (m == 6 && d < 21))
printf("The season is Spring.\n");
break;
case 6:
case 7:
case 8:
if ((m == 6 && d >= 21) || (m == 7) || (m == 8) | (m == 9 && d < 21))
printf("The season is Summer.\n");
break;
case 9:
case 10:
case 11:
if ((m == 9 && d >= 21) || (m == 10) || (m == 11) || (m == 12 && d < 21))
printf("The season is Autumn.\n");
default:
break;
}
}
I tried getting the code working for each part independently, but I'm still unsure about my switch statement. How can I get it working for days as well as months? Is there a way to do it still with a switch statement?
Example Output:
20/06/2022 = Spring
21/06/2022 = Summer
You example will fail for March 1 (and other dates) since there is no case for 3 listed in the Winter case. You don't need a switch statement at all:
if ((m == 12 && d >=21) || (m == 1) || (m == 2) || (m == 3 && d < 21))
printf("The season is Winter.\n");
else if ((m == 3 && d >= 21) || (m == 4) || (m == 5) || (m == 6 && d < 21))
printf("The season is Spring.\n");
else if ((m == 6 && d >= 21) || (m == 7) || (m == 8) | (m == 9 && d < 21))
printf("The season is Summer.\n");
else
printf("The season is Autumn.\n");
If you must use a switch, then you have to put the boundary months (March, June, September, December) into their own cases:
const char *season = NULL;
switch (m)
{
case 1:
case 2:
season = "Winter";
break;
case 3:
season = (d < 21) ? "Winter" : "Spring";
break;
case 4:
case 5:
season = "Spring";
break;
case 6:
season = (d < 21) ? "Spring" : "Summer";
break;
case 7:
case 8:
season = "Summer";
break;
case 9:
season = (d < 21) ? "Summer" : "Autumn";
case 10:
case 11:
season = "Autumn";
break;
case 12:
season = (d < 21) ? "Autumn" : "Winter";
break;
default:
assert("month out of control" == NULL);
season = "Unknown - invalid month";
break;
}
printf("The season is %s.\n", season);
"Is there a way to do it still with a switch statement?
This question indicates a flawed perspective. Algorithms should be written to clearly and cleanly achieve the objective of the task; not written to conform to a favourite scheme. As shown in other answers, switch() is either cumbersome or unnecessary to solve this problem.
It's worth noting/learning that "branching" can be expensive in terms of processing time. While a ladder of if/else conditionals may be easy for a human to read and understand, finding a superior algorithm that does not involve branching will likely process much faster.
If you want to calculate the name of the season instead of using a lot of magic numbers in conditionals, then this seems to work.
void season( uint16_t m, uint16_t d ) {
char *seasons[] = { "Winter", "Spring", "Summer", "Autumn", "Winter" };
char *p = seasons[ ((m-1) / 3) + (!(m%3)*( d >= 22 )) ];
printf( "mon %d day %d = %s\n", m, d, p );
}
int main() {
season( 1, 1 );
season( 1, 22 );
season( 2, 22 );
season( 3, 21 );
season( 3, 22 );
season( 9, 21 );
season( 9, 22 );
season( 12, 21 );
season( 12, 22 );
return 0;
}
mon 1 day 1 = Winter
mon 1 day 22 = Winter
mon 2 day 22 = Winter
mon 3 day 21 = Winter
mon 3 day 22 = Spring
mon 9 day 21 = Summer
mon 9 day 22 = Autumn
mon 12 day 21 = Autumn
mon 12 day 22 = Winter
And, with only "month and day", the only indication of "leap year" would be if you had the pair "02/29". Not sure what you wanted there...
EDIT:
Not to forget those who live south of the equator, here is the trivial modification to the above function that takes a 3rd parameter (true for the southern hemisphere.)
void season( bool SthHemi, uint16_t m, uint16_t d ) {
char *seasons[] = { "Winter", "Spring", "Summer", "Autumn", "Winter", "Spring", "Summer", };
char *p = seasons[ (SthHemi*2) + ((m-1) / 3) + (!(m%3)*( d >= 22 )) ];
printf( "mon %d day %d = %s\n", m, d, p );
}
EDIT2:
Not really happy with the extra instances of the names of the seasons, here is an improved calculation that determines which string to use.
char *season( int SthHemi, uint16_t m, uint16_t d ) {
char *seasons[] = { "Winter", "Spring", "Summer", "Autumn" };
return seasons[ (((m+(SthHemi*6)-1) / 3) + (!(m%3)*( d >= 22 )))%4 ];
}
SthHemi - being 0 (north) or 1 (south) - is multiplied by 6 as the hemispheres' seasons are 6 months out of phase. Adding this to the month index (1-12), subtracting 1, then dividing by 3 gives either 0,1,2,3 or 2,3,4,5 towards the index of the string to use. Now, if the month modulo 3 is 0 (ie: Mar, Jun, Sep, or Dec), use !0 (ie: 1) to multiply the truth value that the day-of-month is >= 22. This operation may add 1 to the index value calculated so far for the final days of those 'transitional' months. Finally, use modulo 4 to "wrap" larger index values into the range of 0-3 and return the appropriate string from the array of strings that are season names. Simple!
Is there a way for me to write below code in lesser characters?
if (num == 1 || num == 2 || num == 3 || num == 4|| num == 5)
{
printf("Enter number you want to convert:\n");
scanf("%d", &a);
}
else
{
goto quit;
}
Like in SQL we use:
if (num in 1,2,3,4,5)
or like in some imaginary language if we could use something like:
if num in [1-5]
If the num can be compared in a range like 1 to 5 can simply write
if (num >= 1 && num <= 5)
{
///.....
}
This is mentioned in other comments and answers. But if the numbers you need to compare are not in a range then the code can be complicated. For me, the simpler way is :
if (num == 1 || num == -2 || num == 3 || num == 10 || num == 5)
{
//......
}
But there is another way to write code like SQL(mentioned in the question). Using variable argument can implement a function :
is_equal(total number of arguments with num variable, num , list of numbers need to compare ..))
This can provide similar code to if (num in 1,2,3,4,5)
#include <stdio.h>
#include <stdarg.h>
int is_equal(int count,...) {
va_list valist;
int ret = 0 ;
int num ;
/* initialize valist for num number of arguments */
va_start(valist, count);
/* access all the arguments assigned to valist */
for (int i = 0; i < count; i++) {
if(i == 0) num = va_arg(valist, int) ;
else{
if(num == va_arg(valist, int))
ret = 1 ;
}
}
/* clean memory reserved for valist */
va_end(valist);
return ret;
}
int main() {
int num = 12 ;
printf("%d\n" , is_equal(5 ,num , 1, 2, 3, 4)) ;
printf("%d\n" , is_equal(4 ,num, 1, 2, 3)) ;
printf("%d\n" , is_equal(6 ,num, 1, 2, 3, 4, 12)) ;
printf("%d\n" , is_equal(8 ,num, 1, 2, 3, 4, 7, -14, 12)) ;
printf("%d\n" , is_equal(9 ,num, 1, 2, 3, 4, 7, -14, -12 , 120)) ;
}
Output :
0
0
1
1
0
Use relational comparison operators to check if a number is within the lower and upper bounds of a range:
if (num >= 1 && num <= 5)
{
printf("Enter number you want to convert:\n");
scanf("%d", &a);
}
else
{
goto quit;
}
or use switch:
switch (num)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf("Enter number you want to convert:\n");
scanf("%d", &a);
break;
default:
goto quit;
}
I want to be able to request the entry of 4 digits between 0 and 1 but when I do the test it still asks me to enter the screen despite entering 1001 or others.
#include <stdio.h>
int main(void) {
int n,n1,n2,n3,mod0,mod1,mod2,mod3;
do {//1025
printf("Ingresar un numero de 4 digitos: "); scanf("%d",&n);
n1 = n/10; //<- 102
mod0 = n%10; // <- mod 5
n2 = n1/10; // <- 10
mod1 = n1%10; // <- mod 2
n3 = n2/10; // <- 1
mod2 = n2%10; // <- 0
mod3 = n3%10; // 1
if ((mod3 != 1 || mod3 != 0) && ( mod2 !=1 || mod2 != 0) && (mod1 != 1 || mod1 != 0) && (mod0 !=1 || mod0 != 0)){
printf("Ingresar digitos binarios\n");
}
}while((mod3 != 1 || mod3 != 0) && ( mod2 !=1 || mod2 != 0) && (mod1 != 1 || mod1 != 0) && (mod0 !=1 || mod0 != 0));
return 0;
}
It keeps asking for digits, since you have the scanf inside the loop. Placing printf("Ingresar un numero de 4 digitos: "); scanf("%d",&n); above your do-while loop will solve your problem.
Also, you should look at the conditions of your loop. Isn’t it easier to loop until n == 0?
Example:
n = 1025, mod = 0
while n != 0:
mod = n % 10 (makes 5)
n = n / 10 (makes 102)
Check if mod is 0 or 1
repeat for next digits
In the example you will seperate each last digit from n and check whether it is a 0 or 1.
EDIT: This link explains what I want to show with the example. Instead of printing the digits, you should check if it is a 0 or 1.
I am working on a problem that finds 'count' odd numbers below the int value 'bound' and adds up to an int value sum. It is suggested that I use recursion to solve.
I have completed the recursion and have made it solve 7 / 8 cases in mimir. There is one case that is showing a fail but I cannot figure out what is wrong even when stepping through with gdb.
Problem case:
Input: 10 54 108
EDIT:
So it turns out that my code is correct and is finding the correct answer for this case ( AKA - No solution exists ) but my problem is that I only have 3 sec of run time to find this solution and currently my code takes longer than that.
Not looking for a straight answer necessarily, more of a point in the right direction. Trying to learn from this :)
https://ibb.co/4138WBw
int odd_sum(int count, int bound, int sum)
{
if (bound % 2 == 0)
return odd_sum(count, bound -1, sum);
else if ( sum == 0 && count == 0 && bound >= -1)
return 1;
else if ( sum - bound < 0)
return odd_sum(count, bound - 2, sum);
else if (count == 0 && sum != 0)
return 0;
else if (bound < 1 && sum != 0)
return 0;
else
{
int value = (odd_sum(count - 1, bound - 2, sum - bound));
if ( value )
{
return printf("%d ", bound);
}
else
return (odd_sum(count - 1, bound - 2, sum - bound));
}
/* Do not change the main() function */
int main(void)
{
int value;
int c, b, s;
printf("Please enter 3 positive integers: count, bound, and sum:\n");
if (scanf("%d%d%d", &c, &b, &s) != 3) {
printf("Please enter 3 integers.\n");
return 1;
}
if (c <= 0 || b <= 0 || s <= 0) {
printf("Integers must be positive.\n");
return 1;
}
value = odd_sum(c, b, s);
if (value)
printf("\n");
else
printf("There are no solutions.\n");
return 0;
}
The final result needs to look like this for the two cases, ( pass or fail )
$./odd_sum
Please enter 3 positive integers: count, bound, and sum:
10 20 100
1 3 5 7 9 11 13 15 17 19
$./odd_sum
Please enter 3 positive integers: count, bound, and sum:
10 18 100
There are no solutions.
$./odd_sum
Please enter 3 positive integers: count, bound, and sum:
12 30 200
5 7 9 11 13 15 17 19 23 25 27 29
Thank you guys in advance
This code seems to return the correct result for input, (10, 54, 108): 1 3 5 7 9 11 13 15 17 27
int odd_sum(int count, int bound, int sum){
if (count == 0 && sum == 0)
return 1;
if (count == 0 || bound <= 0)
return 0;
if (bound % 2 == 0)
return odd_sum(count, bound - 1, sum);
if (odd_sum(count - 1, bound - 2, sum - bound))
return printf("%d ", bound);
else
return odd_sum(count, bound - 2, sum);
return 0;
}
I wanted to make a function with structs to simplify rational numbers , one member is the numerator(int) and the other is the denominator(int) but the program stucks at input!!
I am aware that scanf() is a bit risky but I thought its just a couple of integers!
#include <stdio.h>
#include <stdlib.h>
typedef struct rational{
int num;
int den;
}rational;
rational makerational(int num,int den);
void printrational(rational r);
int main()
{
int a,b;
printf("\n\n Input integers for fraction:");
scanf(" %d%d",&a,&b);
printrational(makerational(a,b));
}
rational makerational(int a,int b){
int live=1;
rational r;
r.num=a;
r.den=b;
while(live){
if(!(r.num%2 && r.den%2)){
r.num/=2;
r.den/=2;
}else if(!(r.num%3 && r.den%3)){
r.num/=3;
r.den/=3;
}else if(!(r.num%5 && r.den%5)){
r.num/=5;
r.den/=5;
}else if(!(r.num%7 && r.den%7)){
r.num/=7;
r.den/=7;
}else live--;
}
return r;
}
void printrational(rational r){
printf("\nFRACTION -> %d/%d\n",r.num,r.den);
}
You getting stuck in an infinite loop here:
while(live){
if(!(r.num%2 && r.den%2)){
r.num/=2;
r.den/=2;
}
…
}
For example, when r.num == 1 and r.den == 2, consider what's happening:
Iteration 1
r.num % 2 == 1 % 2 == 1
r.den % 2 == 2 % 2 == 0
!(1 && 0) == 1
r.num / 2 == 1 / 2 == 0
r.den / 2 == 2 / 2 == 1
Iteration 2
r.num % 2 == 0 % 2 == 0
r.den % 2 == 1 % 2 == 1
!(0 && 1) == 1
r.num / 2 == 0 / 2 == 0
r.den / 2 == 1 / 2 == 0
Iteration 3 to infinity and beyond…
r.num % 2 == 0 % 2 == 0
r.den % 2 == 0 % 2 == 0
!(0 && 0) == 1
r.num / 2 == 0 / 2 == 0
r.den / 2 == 0 / 2 == 0
Change the expressions in the branching statements to something like this to correct your logic:
while(live)
{
if((r.num % 2 == 0) && (r.den % 2 == 0))
{
r.num /= 2;
r.den /= 2;
}
…
}
Problem is, when you enter 8 20, numbers change like fallowing;
4 10
2 5
1 2
0 1
0 0 <--- here is the infinite loop
reason is, integer rounds down the number, you should add a control statement for the case that numbers reach 0