| Main |< C & C++ 2D Array 3 | C & C++ Functions Part 1 >| Site Index | Download |


 

C PROGRAMMING:

THE IF, WHILE, DO-WHILE, FOR AND ARRAY

WORKING PROGRAM EXAMPLES (with some flowcharts)

 

  1. Compiler: VC++ Express Edition 2005

  2. Project: Win32 > Win32 Console Application

  3. Setting: No Common Language Runtime support, Use Unicode Character Set and Compile as C Code (/TC) (others are default).

  4. OS: Win Xp Pro SP2 + updates + patches…, 2GB RAM, Intel Core 2 Duo…

 

 

 

  1. Write a program that reads an integer and checks whether it is odd or even.  For example:

 

Enter a number: 25

25 is an odd number.

Answer:

 

The following is an algorithm for this program using a flow chart. We can use a modulus operator to solve this problem. There will be no remainder for even number when we modulus the number by 2.

 

The source code:

 

#include <stdio.h>

 

int main()

{

      int num = 0, remainder = 0;

   

      // while -1 not entered...

      while(num != -1)

      {

            // prompt user for input

            printf("Enter an integer (-1 to stop): ");

            // read and store input, then modulus by 2

            scanf_s("%d", &num, sizeof(int));

            // ready to stop if -1 else...

            if(num != -1)

            {

                  remainder = num % 2;

                  // test for even/odd. If the modulus yields 0, it is even

                  if(remainder == 0)

                        printf("%d is an even number.\n", num);

                  else

                        printf("%d is an odd number.\n", num);

            }

      }

      // -1 was entered

      printf("%d is an odd number.\n", num);

      printf("You ask to stop! Thank you.\n");

      return 0;

}

 

A sample output:

 

 

The do-while version.

 

#include <stdio.h>

 

int main()

{

      int num = 0, remainder = 0;

     

      do

      {

            // prompt user for input

            printf("Enter an integer (-1 to stop): ");

            // read and store input, then modulus by 2

            scanf_s("%d", &num, sizeof(int));

            // ready to stop if -1 else...

            if(num != -1)

            {

                  remainder = num % 2;

                  // test for even/odd. If the modulus yields 0, it is even

                  if(remainder == 0)

                        printf("%d is an even number.\n", num);

                  else

                        printf("%d is an odd number.\n", num);

            }

      }// while -1 not entered...

      while(num != -1);

      // -1 was entered

      printf("%d is an odd number.\n", num);

      printf("You ask to stop! Thank you.\n");

      return 0;

}

  1. The wind chill index (WCI) is calculated from the wind speed v in miles per hour and the temperature t in Fahrenheit. Three formulas are used, depending on the wind speed:

if (0 <= v <= 4) then WCI = t

 

if (v >=45) then WCI = 1.6t - 55

 

otherwise, WCI = 91.4 + (91.4 - t)(0.0203v - 0.304(v)1/2 - 0.474). Write a program that can calculate the wind chill index.

 

Answer:

 

The if-else is suitable for this solution, choosing from three conditional expressions. We need to prompt user for v and t in order to calculate and show the wci. The following is an algorithm for this program using a flow chart.

 

 

 

The source code:

 

#include <stdio.h>

// for pow(x,y)

#include <math.h>

 

int main()

{

      // v is wind speed in mph, t is temperature in Fahrenheit

      // and wci is wind chill index

      double v = 0.0, t = 0.0, wci = 0.0;

     

      // let provide a loop for continuous input until stopped by user

      while(v != -1)

      {

            // read and store v from user inputs

            printf("Enter wind speed in mph (-1 to stop): ");

            // the 3rd parameter of scanf_s() is not required for numerical, int and float

            // the lf is for double or long int, the l (el) is microsoft extension...

            scanf_s("%lf", &v, sizeof(double));

            // if user don't want to stop then repeat...

            if(v != -1)

            {

                  // read and store t from user inputs

                  // the 3rd parameter of scanf_s() is not required for numerical, int and float

                  printf("Enter temperature in Fahrenheit: ");

                  scanf_s("%lf", &t, sizeof(double));

                  // if (0 <= v <= 4)

                  if((v >= 0.0) && (v <=4.0))

                        wci = t;

                  // if (v >= 45)

                  else if (v >= 45)

                        wci = ((1.6*t) - 55);

                  // others...

                  else

                        wci = 91.4 + ((91.4 - t)*((0.0203*v) - (0.304*(pow(v,0.5))) - 0.474));

                  // print one of the result

                  printf("\nFor wind speed =  %.2f and temperature = %.2f\n", v, t);

                  printf("Wind Chill Index is: %.2f\n", wci);

                  printf("\n");

            }

            // check the while loop condition

      }

      // if user press -1 for wind speed then stop...

      printf("This program was stopped by you. thank you!\n");

      return 0;  

}

 

A sample output:

 

  1. Write a program that asks the user to enter an integer and determines whether it is divisible by 5 and 6, whether it is divisible by 5 or 6, and whether it is divisible by 5 or 6 but not both. For example, if your input is 10, the output should be:

Is 10 divisible by 5 and 6? false

Is 10 divisible by 5 or 6? true

Is 10 divisible by 5 or 6, but not both? true

 

Answer:

 

We can use the logical AND (&&), OR (||), NOT (!) and modulus (%) to solve this problem. If the modulus yields a 0, the number is divisible otherwise it is not divisible. Then we use the logical operators to provide the desired outputs. The following is an algorithm for this program using a flow chart.

 

The source code:

 

#include <stdio.h>

 

int main()

{

      int num1 = 0, num2 = 0, num3 = 0;

    

      while(num1 != -1)

      {

            // read and store an integer from user

            printf("Enter an integer, -1 to stop: ");

            scanf_s("%d", &num1);

            // check whether user want to stop or not

            if(num1 != -1)

            {

                  // Let determine the divisibility of 5 and 6

                  num2 = num1 % 5; // num2 = 0, divisible

                  num3 = num1 % 6; // num3 = 0, divisible

                 

                  // in this example, all three conditions must be tested

                  // do the equality comparison

                  // Divisible by 5 AND 6?

                  if((num2 == 0) && (num3 == 0))

                        printf("Is %d divisible by 5 and 6? true\n", num1);

                  else

                        printf("Is %d divisible by 5 and 6? false\n", num1);

                 

                  // Divisible by 5 OR 6?

                  if((num2 == 0) ||(num3 == 0))

                        printf("Is %d divisible by 5 or 6? true\n", num1);

                  else

                        printf("Is %d divisible by 5 or 6? false\n", num1);

                 

                  // Divisible by 5 OR 6 but NOT both?

                  if(((num2 == 0) ||(num3 == 0)) && !((num2 == 0) && (num3 == 0)))

                        printf("Is %d divisible by 5 or 6 but not both? true\n", num1);

                  else

                        printf("Is %d divisible by 5 or 6 but not both? false\n", num1);

            }

            // clean up

            // num1 = 0;

            printf("\n");

            // check the while condition

      }

      // exit message

      printf("You asked to stop. Thank you!\n");

      return 0;

}

 

A sample output:

 

  1. MyJava Café wants you to write a program to take orders from the Internet. Your program asks for the item, its price, and if overnight shipping is wanted. Regular shipping for items under $10 is $2.00; for items $10 or more shipping is $3.00. For overnight delivery add $5.00.  For example, the output might be:

 

Enter the item:
Tuna Salad
Enter the price:
450
Overnight delivery (0==no, 1==yes):
1
 
Invoice:
  Tuna Salad    4.50
  shipping      7.00
  total         11.50

Answer:

 

Using the nested if-else, we test the overnight delivery condition that chosen by user. After confirming the overnight delivery, on the true path, we test the amount of price whether it is less than $10 or not. On the false side, we also test the price whether less than $10 or not and finally print the total price for the respective condition. The following is an algorithm for this program using a flow chart.

 

The source code:

 

#include <stdio.h>

// for strcmp()

#include <string.h>

 

int main()

{

      char item[20]= "";

      double price = 0.0, shipping = 0.0, total = 0.0;

      int over_delivery, stop = 1;

     

      while(stop != -1)

      {     // if stop != 1, continue...

            // prompt for user input

            printf("Enter the item name or description: ");

            // the 3rd parameter is required for character and string

            // store item

            scanf_s("%s", item, sizeof(item));

            // prompt user for price

            printf("Enter the price ($): ");

            // store price

            scanf_s("%lf", &price);

            // prompt user for overnight delivery choice

            printf("Overnight delivery (0 = No, 1 =Yes)?: ");

            // store the choice

            scanf_s("%d", &over_delivery);

           

            // if the overnight delivery is needed...

            if(over_delivery == 1)

            {

                  if(price < 10)

                        shipping = 2.00 + 5.00;

                  else

                        shipping = 3.00 + 5.00;

            }

            // if no overnight delivery

            if (over_delivery == 0)

            {

                  if(price < 10)

                        shipping = 2.00;

                  else

                        shipping = 3.00;

            }

            // print all the results

            printf("Invoice (in $):\n");

            printf("%-23s %15.2f\n", item, price);

            printf("shipping %30.2f\n", shipping);

            total = price + shipping;

            printf("total %33.2f\n", total);

            // prompt user for continuation....

            // need to clean up for next calculation

            total = 0.0;

            printf("More item? -1 to stop, other to continue: ");

            scanf_s("%d", &stop, sizeof(int));

      }

      return 0;

}

 

A sample output:

 
  1. Write a program that reads an integer between 0 – 999 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digit is 14. Hint: Use the % operator to extract digits and use the / operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 / 10  = 93.

Answer:

 

The sum of integer digits is the sum of the remainder when the integer is repeatedly modulus’ed by 10 and then divided by 10 until the integer becomes 0. For repetition we can use the while loop. The following is an algorithm for this program using a flow chart.

 

The source code:

 

#include <stdio.h>

 

int main()

{

      int count = 0, num = 0, remainder = 0, sum = 0, stop = 0;

     

      while(stop != -1)

      {

            printf("Enter an integer: ");

            scanf_s("%d", &num);

            // test the num == 0?

            printf("\nAfter operation:\n");

            printf("remainder num\n");

            printf("--------- ---\n");

            while(num != 0)

            {

                  // get the remainder (digits) by dividing by 10

                  remainder = num % 10;

                  // sum up the remainder

                  sum = sum + remainder;

                  // divide the number by 10, next integer part

                  // ...10000, 1000, 100, 10, 0

                  num = num / 10;

                  // let see current value of num and remainder...

                  printf("%d        %d\n", remainder, num);

            }

            printf("\n");

            // print the sum of the digits...

            printf("The sum of digits is %d\n", sum);

            // reset sum to 0, for next test

            sum = 0;

            printf("More? -1 to stop, other to continue: ");

            scanf_s("%d",&stop);

      }

      return 0;

}

 

A sample output:

 

  1. Write a program that can read three integers from the user and then determines the smallest value among the three integers.

Answer:

 

The using of if statement is not the efficient way for the solution. It is better to use an array with loop, mainly when there is a list of integer. The following is an algorithm for this program using a flow chart.

 

The source code:

 

#include <stdio.h>

 

int main()

{

      int i, num[5], smallest = 0, stop = 0;

 

      while( stop != -1)

      {

            // prompt input from user

            printf("Enter 5 integers separated by a space: ");

            // store those integers in an array

            for(i=0;i <=4;i++)

                  scanf_s("%d", &num[i]);

           

            // assign the 1st element to smallest

            smallest = num[0];

            // compare the others and keep storing the smallest

            for(i=1;i<=4;i++)

                  if(num[i] < smallest)

                        smallest = num[i];

            // print some text...

            printf("The smallest number among ");

            // print the element

            for(i=0;i <=4;i++)

                  printf("%d ", num[i]);

            // print the smallest

            printf("is %d\n", smallest);

            // clean up for next calculation

            smallest = 0;

            // may also need to clean up the array content, set all to 0

            // using for loop...not shown here

            printf("\nMore data? -1 to stop, others to continue: ");

            scanf_s("%d", &stop);

      }

      return 0;

}

 

A sample output:

 

 

-----------------------------------------------------------------

By changing the if statement:

 

if(num[i] < smallest)

      smallest = num[i];

 

To

 

if(num[i] > smallest)

      smallest = num[i];

 

Will scan the largest number as shown in the following example.

 

#include <stdio.h>

 

int main()

{

      int i, num[5], largest = 0, stop = 0;

 

      while( stop != -1)

      {

            // prompt input from user

            printf("Enter 5 integers separated by a space: ");

            // store those integers in an array

            for(i=0;i <=4;i++)

                  scanf_s("%d", &num[i]);

           

            // assign the 1st element to largest

            largest = num[0];

            // compare the others and keep storing the largest

            for(i=1;i<=4;i++)

                  if(num[i] > largest)

                        largest = num[i];

            // print some text...

            printf("The largest number among ");

            // print the element

            for(i=0;i <=4;i++)

                  printf("%d ", num[i]);

            // print the largest

            printf("is %d\n", largest);

            // clean up for next calculation

            largest = 0;

            // may also need to clean the array, set all to 0

            printf("\nMore data? -1 to stop, others to continue: ");

            scanf_s("%d", &stop);

      }

      return 0;

}

 

A Sample output:

 

  1. Write a program that asks the user to input an integer and then outputs the individual digits of the number.

Answer: Using the division (/) and modulus (%).

#include <stdio.h>

// for pow(x,y)

#include <math.h>

 

int main()

{

   //-------------------------------------------------------------------------

   // Separating an integer to individual digits

   // The x % y computes the remainder obtained when x is divided by y.

   //-------------------------------------------------------------------------

     

      // can try long for bigger range, int range is the limit

      int intnumber = 0, condition = 0, remainder = 0;

      // counter to store the number of digit entered by user

      int counter = 0;

           

      // prompt user for input

      printf("Enter an integer number: ");

      // read and store input in intnumber

      scanf_s("%d", &intnumber);

      // set the condition sentinel value to intnumber

      condition = intnumber;

     

      // we need to determine the number of digit

      // entered by user, we don't know this and store it in counter

      while (condition > 0)

      {

         condition  = condition / 10;

         counter = counter + 1;

      }

     

      // well, we already know the number of digit entered by user,

      // start with number of digits less 1, because we need to discard

      // the last one...

      counter = counter - 1;

      printf("The individual digits: ");

      while (counter >= 0)

      {

         // extract each of the decimal digits, need to cast to int

         // to discard the fraction part

         // pow(10, counter) used to determine the ...,10000, 1000, 100, 10, 1

         // because initially we don't know how many digits user entered...

         remainder = intnumber % (int) pow(10, counter);

         intnumber = intnumber/(int) pow(10,counter);

         printf("%d  ", intnumber);

         intnumber = remainder;

         counter = counter - 1;

      }

        printf("\n");

   return 0;

}

 

A sample output:

 

  1. Write a program that ask