Basic C++ Intro (Conditional Statements & Loops)

if statement:

if (conditional) //&&, ||, >=, <=, !=, ==
{
   //code to execute
}
else if (conditional)
{
   //code to execute if condition is 
}
else
{
   //code to execute in default
}

/* ---- */

int x;
if (conditional)
{
   x = 5;
}
else
{
   x = 6;
}

//same as:
int x = (conditional) ? 5 : 6;

while, do-while and switch:

/* -- while -- */
while (true)
{
   //code to execute   
}

/* -- do-while-- */
do
{
   //code to execute at least once
}
while ( )

/* -- switch -- */
int x = get_int("enter a number: ");
switch(x)
{
   case 1:
      //code to execute;
      break;
   case 2:
      //code to execute;
      break;
   case 3:
      //code to execute;
      break;
   default:
      //code to execute;
}

for loop:

for (int i = 0; x < i; i++)
{
   //code
} 

examples:

#include <stdio.h>
#include <cs50.h>

//this is how functions are created
void meow(void)
{
   printf("meow\n");
}

int main(void)
{
   for (int i = 0; i < 3; i++)
   {
      meow();
   }
}
#include <stdio.h>
#include <cs50.h>

void meow(int n);//function prototype

int main(void)
{
   meow(3);//the function meow is call with a 3 parameter
}

//function
void meow(int n)
{
   for (int i = 0; i < n; i++)
   {
      printf("meow\n");
   }
}
#include <stdio.h>
#include <cs50.h>
#include <cs50.h>

float discount(float price, float percentage);

int main(void)
{
    float regular = get_float("Regular Price: ");
    float saleDiscount = get_float("Enter Discount: ");
    float sale = discount(regular, saleDiscount);
    printf("Sale Price: %.2f\n", sale);
}

//function
float discount(float price, float percentage)
{
    return price * (100 - percentage) / 100;
}


//to round a number there is a function called round(parameter)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *