Jump to content
 Share

Joshy

Conditional Statements

Recommended Posts

Posted  Edited by Joshy - Edit Reason: Added links to previous and next thread

This is a follow up for those of you who are more advanced than my first tutorial:

 

 

We will cover conditions and looping here. I will post a lot such that you can copy and try to massage the code again, and so don't worry if this is a little bit confusing. Just try running and see what happens.

 

A condition is exactly as it sounds: A part of the program will only run if it satisfies a condition. Lets do an example: If you give me $5, then I will do your homework. If you don't give me $5, then I wont do your homework.

 

Jd0kKsA.png

 

The programming equivalent to this is the following:

 

#include <stdio.h>

int main()
{

  // Declaration
  char userSelection;

  // Here is where the user can choose whether or not to give $5
  printf("Give Joshy $5 to do your homework? [y/n]: ");
  scanf("%c", &userSelection);

  if(userSelection == 'y')
  {

    // The user selected 'y' for yes, and so this will run
    printf("Joshy will do your homework.");

  }
  else
  {
    
    // This will run if the user types in anything other than 'y'
    printf("Joshy will NOT do your homework.");

  }
 
  return 0;
 
}

 

You should be noticing in the above the conditional statement is inside of the if() piece.

 

if(condition)
{
 
  // Runs if the condition is true
 
}
else
{
 
  // Runs if the condition is not true
 
}

 

There are many other types of "logical" conditions such as the following:

  • != is NOT EQUAL.
  • == EQUAL TO
  • > Greater than
  • >= Greater than or equal to
  • < Less than
  • <= Less than or equal to
  • && AND (both conditions must be true)
  • || OR (one of the conditions must be true)

 

This is just logic, which I am assuming you would know. Here are some examples:

 

// AND example
if(someCondition == 1 && anotherCondition == 1)
{
 
  //.. both conditions must be true to run
 
}

// OR example
if(someCondition == 1 || anotherCondition == 0)
{
 
  //.. only one of these conditions needs to be true to run
 
}

 

// Is 5 "less than or equal to 10"?
int test = 5;

if(test <= 10)
{
 
  // This one WILL run because 5 <= 10
  printf("Yes.");
 
}
else
{
 
  // This one will NOT run
  printf("No.");

}

 

Some common PITFALLS to take note of:

  • It is common for beginners to accidentally use a single equal sign "=" instead of two of them "==", which will not work for checking conditions. A single equal sign "=" will literally set the variable to equal that value. DO NOT USE THE FOLLOWING:

 

if(test = 5)  //<-- This is a MISTAKE!  Used "=" instead of "==".
{

        //..

}

 

  • It is a mistake to put a semicolon at the end of a condition or loop. DO NOT USE THE FOLLOWING:

 

if(condition);  // <-- this is a MISTAKE!  You do not want a semicolon here
{
 
  // Nothing in here will run... ever...
 
}

 

You CAN use the condition as a bypass without the else statement if you would like.

 

lnYTVzc.png

 

#include <stdio.h>
 
int main()
{
 
  char bypass;
 
  printf("Would you like to skip the next part of this program? [y/n]: ");
  scanf("%c", &bypass);
 
  // if the bypass does not equal to 'y' (yes), then run this code
  if(bypass != 'y')
  {
    
    printf("You did not skip this part of the program.\n");
    
  }
 
  printf("This always runs unconditionally.");
 
  return 0;
 
}  

 

You might use this in parts of development such as checking if someone has a certain amount of HP, if the player is on a certain team, if the player is in a group like Admin or VIP, or if the targeted player is even online.

 

One of the benefits to programming is taking care of repetitive tasks really quickly. A way for us to take advantage of this is through using loops. The two prominent loops are "for" and "while" loops. For loops run for a set number of times, and its format is along the lines of:

 

int firstNumber = 0, lastNumber = 10;

// Counting up from zero to 9.
for(int i=firstNumber; i<lastNumber; i++)
{
 
  // Example of a repetive task
  printf("%i\n", i);
 
}

// This can be done equivalently with for(int i=0; i<10; i++){..
// The above loop will only run from 0 to 9, which is 10 times or 10 "iterations"

 

While loops run until its condition is broken.

 

ageJoshy = 1;

// my age will be the condition
while(ageJoshy < 18)
{
 
  printf("Joshy is just a child.\n");
 
  // This increments my age
  ageJoshy = ageJoshy + 1;
 
  // You could also use ageJoshy++;
 
}

printf("Joshy is no longer a child.");      

 

Some people use "do while" loops, which only guarantees the while loop will run the first time (regardless of the condition) and runs like a regular while loop afterwards; however: I do not plan to confuse you further by talking more about it, and it is not used often- just know that it's available if there is ever a time you may need something like that. You can read about it if you're interested (reference).

 

Another confusing but commonly used strategy is "nested loops." It's much like the movie inception except you've got a loop within a loop, and sometimes (multiple) loops within a loop. I recommend running this one below just to see what it does.

 

#include <stdio.h>

int main()
{

  for(int row = 0; row<10; row++)
  {

    // This will run through all the columns before going to the next row
    for(int column = 0; column<10; column++)
    {

      printf("Row: %i, Column: %i\n", row, column);
      
      // You could make it count by replacing the above with the following line
      printf("%i\n", column + 10*row);

    }

  }
 
  return 0;
 
}

// This will print out elements of a 10 by 10 array or "matrix."

 

A nested loop conceptually:

 

 

U10aD97.png

 

 

Let us see what we can make of all this using our earlier program from the first thread. The original program only allowed the user to enter a set amount of numbers to add. Lets make it such that the user can choose how many numbers to add! We'll also give the user an option to exit out of the program if they did not want to add numbers. You can copy and paste this just to get a feel for it.

 

#include <stdio.h>

int main()
{

        // Declaration and initial values
        int count = 0, numX = 0, numY = 0;
        char userSelection;

        printf("Would you like to add numbers?  [y/n]: ");
        scanf("%c", &userSelection);

        if (userSelection == 'y')
        {

                printf("How many numbers would you like to add?: ");
                scanf("%i", &count);

                for(int i = 0; i < count; i++)
                {

                        // User interface
                        printf("Input number to add: ");
                        scanf("%i", &numX);

                        numY = numY + numX;

                }

                // Output
                printf("The sum is: %i", numY);

        }
        else
        {

                printf("Exiting program.");

        }


        return 0;

}

 

Q2SbrjH.png

 

9vfJPnw.png

 

Here's what I recommend trying next:

 

  • Give the user the option to try other operations such as multiplication ie.

 

printf("1. Add");
printf("\n2. Subtract");
printf("\n3. Multiply");
printf("\nSelect an operation: ");
scanf("%i", &userSelection);

if(userSelection == 1)
{
 
  // The user picked option 1. Add
  numZ = numX + numY;
 
}

if(userSelection == 2)
{
 
  // The user picked option 2. Subtract
  numZ = numX - numY;
 
}

//..

 

  • Try having that "nested for loop" print even numbers only, or make it count down instead of up.
  • Try a "nested while loop" counter. If you get stuck in a run time error, then an easy way to exit is to use "CTRL+C" just like the copy shortcut.
  • Make a guessing game where the user wins if they guess the correct number.
  • Try copying any of the code above using for loops and remake an equivalent code using while loops instead

 

Example for loop version:

 

for(int i=0; i<10; i++)
{
 
  printf("My name is Joshy.\n");
 
}

 

Example while loop version:

 

//Equivalent version using while loop below
int i = 0;
while(i < 10)
{
 
  printf("My name is still Joshy.\n");
 
  i++;
 
}

 

  • Use different conditions

 

Example condition:

 

if(joshyIsCool == 1)
{

        printf("Joshy is cool.");

}

 

Its equivalent condition:

 

if(joshyIsCool != 0)
{

        printf("Joshy is cool.");

}

 

Follow up in the next thread to learn more:

 

 

Edited by Joshy
Added links to previous and next thread

PoorWDm.png?width=360&height=152

Share this post


Link to post
Share on other sites




×
×
  • Create New...