DEV Community

Frey
Frey

Posted on

C Conditional & Loops {}

Hi, I'm Frey! also Known as Fr3yc0d3

So i have put my hands again in cpp after a long time and what i mean after a long time is ? well i started coding in c while i was in 9th grade and said goodbye when i was in 11th grade but as now i'm in college and C is one of the important subject of mine, then it seems like it's the best thing to start making projects with it, and guess what i am already on it making vpn servers and working in Linux kernel [looks awesome right) ?

Now back to the point i am going to share my exprience on this middle level language

Conditions

so here it is let me ask you a quick question what you think of conditions if somebody ask you to define a word condition ?
well whatever your answer is i am pretty sure you all are right in your way xD
but let me explain this with a real life example shall i ?
now here is a example let's see me (frey) want to buy a new laptop (a gaming one) so here is the conversation of me with dealer :

well as i am going to buy a laptop with my own money then i must have to put some pre conditions in my mind about it looks speed design and lot's of space in it.

now i will just put my conditions there to the dealer and he will show me models according to my need :) pretty easy Right ?

well but what if that dealer ask you to talk him in codes (well that's impossible he will say that but what if he did ?)

if he said that you have 2 options to use here:

  1. By using else if (statement)
  2. my fav one using Switch

now let's see a small example of both of them
but first what is switch you asked ?
A. its noting just a long else if condition in a short way Note:- this is not a official definition of switch i just created this right away !!

example of if else

int x = 2;
if (x==1)
printf("x is 1");
else if (x==2)
printf("x is 2");
else if (x==3)
printf("x is 3");
else
printf("Go home");

Now lets replace this code with switch

it will be like that

int x = 2;
switch(x)
{
case 1 : printf("x is 1");
break;
case 2 : printf("x is 2");
break;
case 3 : printf("x is 3");
break;

default : printf("Go home");
}

all done pretty easy ha well i know now you will also use switch more often

and if you want more you can see my 100daysofcode in c repo

Here https://github.com/Fr3y/100Daysofcode

But wait before we go there are few things you have to keep in mind while dealing with switch

1 you can't duplicate the cases

2 only those expressions are allowed in switch which results in an integer ( for this one i recommend you to read my data type article)

3 float value is not allowed

4 variable expressions are not allowed but you can use micros freely (now what is micro its just defining things like #default y 2)

i want to talk more about this all but i also have to take my college classes :(

well see yaa keep Hacking :)

Follow me :

Twitter: Fr3yc0d3
Linkedin: Cybity
GitHub Fr3y

Top comments (0)