|< C & C++ Program Controls 3 | Main | C & C++ Arrays 1 >| Site Index | Download |


 

 

 

 

 

 

 

MODULE 6a_1

C/C++ PROGRAM CONTROLS/LOOPS FINAL PART 4

 

 

 

 

 

 

 

 

My Training Period: xx hours

 

This is a continuation from a previous Module. The source code for this Module is: C/C++ loops source codes. The lab worksheets for your practice are: C/C++ program control repetition 1, C/C++ program control repetition 2, C/C++ program control selection 1, C/C++ program control selection 2 and C/C++ program control selection 3.

  • The system() function, enables the execution of OS command in a running C / C++ program.

  • Can be quite useful, for example, enabling the program to read a disk’s directory listing or format a disk without exiting the program.

  • Must include the header file stdlib.h. The syntax is:

system("command");

  • The command can be either a string constant or a pointer to a string.

  • For example, using an argument with the system() function,

char *command = "dir";

system(command);

  • After the OS command is executed, the program continues at the location immediately following the system() call.

  • If the command passed to the system() function is not a valid OS command, a bad command or file name error message is displayed before returning to the program.

  • The command can also be any executable or batch file to be run.

  • A program example:

// demonstrates the system() function

#include <stdio.h>

#include <stdlib.h>

 

void main()

{

   // declare a buffer to hold input

   char input[40];

   while (1)

   {

          // get the user command

          puts("\nInput the desired DOS command, blank to exit");

          gets(input);

          // exit if a blank line was entered

          if(input[0] == '\0')

              exit(0);

          // execute the command

          system(input);

   }

}

 

Output when DOS command mem is typed:

 

C C++ program control system()

return expression;

// program showing function definition, declaration, call and

// the use of the return statement

#include <iostream>

using namespace std;

 

int main()

{

        // prototypes for the function avg() that main() is going to call

        float  y1, y2, avgy;

        float  avg(float, float);

        y1=5.0;

        y2=7.0;

        avgy = avg(y1, y2);

        // calling the function avg() i.e. control passes

        // to avg() and the return value is assigned to avgy

        cout<<"\ny1 = "<<y1<<"\ny2 = "<<y2;

        cout<<"\nThe average is= "<<avgy<<endl;

        return 0;

}

 

// definition of the function avg(), avg() is

// of type float main() calls this function

float avg(float x1, float x2)    

{

        // avgx is a local variable

        float avgx;

        // computes average and stores it in avgx.

        avgx = (x1+x2)/2;

        // returns the value in avgx to main() and

        // control reverts to main().

        return avgx;

}

 

Output:

 

C C++ program control return statement

// A program showing a function of type void. It has return statement

#include <iostream>

       using namespace std;

 

int main()

{

   float y1, y2, avgy;

   // function prototype...

   // display-avg() is declared to be of type void

   void display_avg(float);

   y1 = 5.0;

   y2 = 7.0;

   cout<<"\ny1 = "<<y1<<"\ny2 = "<<y2;

   // compute average

   avgy = (y1 + y2)/2;

   // call function display_avg()

   display_avg(avgy);

   cout<<endl;

   // return the value 0 to the environment

   return 0;

}

 

// display_avg() is of type void

void display_avg(float  avgx) 

{

    cout<<"\nThe average is = "<<avgx;

    // No value is returned to main() and control reverts to main().

    // or just excludes the return word…

    return;

}

 

Output:

 

C C++ program control return statement

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Working Program Examples

 

Example #1

 

// a pyramid of $ using nested loops

#include <iostream>

using namespace std;

// replace any occurrences of VIEW with character $

#define  VIEW '$'

 

int main()

{

       int i, j;

       cout<<"Let have money pyramid!\n"<<endl;

       // first for loop, set the rows...

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

       {

              // second for loop, set the space...

              for(j=1; j<=10-i; j++)

                  cout<<" ";

              // third for loop, print the $ characters...

              for(j=1; j<=2*i-1; j++)

                     // print character...

                     cout<<VIEW;

              // go to new line...

              cout<<"\n";

       }

       return 0;

}

 

Output:

 

C C++ Program control for loop example

 

Example #2

 

// using break statement in a for structure

#include  <stdio.h>

 

int main()

{

       int x;

       for(x = 1; x <= 10; x++)

       {

              // break loop only if x == 5

              if (x == 5)

                  break;

              printf("%d ", x);

       }

       printf("\nBroke out of loop at x == %d\n", x);

       getchar();

       return 0;

}

 

Output:

 

C C++ Program control for loop example

 

Example #3

 

// using the continue statement in a for structure

#include <stdio.h>

 

int main()

{

       int x;

       for(x = 1; x <= 10; x++)

       {

              // skip remaining code in loop only if x == 5

              if(x == 5)

                  continue;

              printf("%d ", x);

       }

       printf("\nUsed continue to skip printing the value 5\n");

       return 0;

}             

               

Output:

 

C C++ Program control for and if example

 

Example #4

 

// using for statement to calculate compound interest

#include <stdio.h>

// for pow() function

#include <math.h>

 

int main()

{

   int year;

   double amount, principal = 1000.0, rate = 0.05;

   printf("%4s%21s\n", "Year", "Amount on deposit");

   for(year = 1; year <= 10; year++)

   {

          amount = principal * pow(1.0 + rate, year);

          printf("%4d%21.2f\n", year, amount);

   }

   return 0;

}

 

Output:

 

C C++ Program control for example

 

Example #5

 

// counting letter grades using while, switch and multiple cases

#include <stdio.h>

 

int main()

{

       int grade;

       int aCount=0,bCount=0,cCount=0,dCount=0,eCount=0,fCount = 0;

       printf("Enter the letter grades. \n");

       printf("Enter the EOF character, ctrl-c or\n");

       printf("ctrl-z, etc to end input.\n");

       while((grade = getchar()) != EOF)

       {

              // switch nested in while

              switch(grade)

              {

                     // grade was uppercase A or lowercase a

                     case 'A': case 'a':

                     ++aCount;

                     break;

                     // grade was uppercase B or lowercase b

                     case 'B': case 'b':

                     ++bCount;

                     break;

                     // grade was uppercase C or lowercase c

                     case 'C': case 'c':

                     ++cCount;

                     break;

                     // grade was uppercase D or lowercase d

                     case 'D': case 'd':

                     ++dCount;

                     break;

                     // grade was uppercase E or lowercase e

                     case 'E': case 'e':

                     ++eCount;

                     break;

                     // grade was uppercase F or lowercase f

                     case 'F': case 'f':

                     ++fCount;

                     break;

                     // ignore these input

                     case '\n': case ' ':

                     break;

                     // catch all other characters

                     default:

                     {printf("Incorrect letter grade entered.\n");

                           printf("Enter a new grade.\n");}

                     break;

                     }

              }

       // do the counting...

       printf("\nTotals for each letter grade are:\n");

       printf("\A:  %d\n", aCount);

       printf("\B:  %d\n", bCount);

       printf("\C:  %d\n", cCount);

       printf("\D:  %d\n", dCount);

       printf("\E:  %d\n", eCount);

       printf("\F:  %d\n", fCount);

       return 0;

}

 

Output:

 

C C++ Program control switch-case-break example

 

// using for statement to calculate compound interest

#include <cstdio>

// for pow() function

#include <cmath>

 

int main()

{

   int  year;

   double  amount, principal = 1000.0, rate = 0.05;

   printf("%4s%21s\n", "Year", "Amount on deposit");

   for(year = 1; year <= 10; year++)

   {

          amount = principal * pow(1.0 + rate, year);

          printf("%4d%21.2f\n", year, amount);

   }

   return 0;

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

C C++ program controls loops

 

#include <stdio.h>

 

int main()

{

    char     job_title;

    int     years_served, no_of_pub;

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

    printf("Your current job (Tutor-T, Lecturer-L or Assoc. Prof-A): ");

    scanf("%s", &job_title);

    printf("Years served: ");

    scanf("%d", &years_served);

    printf("No of publication: ");

    scanf("%d", &no_of_pub);

    if(job_title == 'A')

      if(years_served > 5)

        if(no_of_pub > 7)

           printf("\nCan be promoted to Professor\n");

        else

           printf("\nMore publications required lol! \n");

      else

           printf("\nMore service required lol\n");

    else

        printf("\nMust become Associate Professor first\n");

    return 0;

}

 

[bodo@bakawali ~]$ gcc ifelse.c -o ifelse

[bodo@bakawali ~]$ ./ifelse

 

               ---Enter data---

Your current job (Tutor-T, Lecturer-L or Assoc. Prof-A): A

Years served: 12

No of publication: 14

 

Can be promoted to Professor

 

 

/*-----forloop.c----------- */

/*-----First triangle------- */

#include <stdio.h>

 

int main()

{

    int i, j, k, l;

    printf("Triangle lol!\n");

    /* first for loop, set the rows... */

    for(i=15; i>=0; i--)

    {

      /* second for loop, set the space... */

      for(j=15; j>=1+i; j--)

        printf(" ");

        /* third for loop, print the characters... */

        for(j=1; j<=2*i+1; j++)

           /* print the character... */

            printf("H");

          /* go to new line... */

          printf("\n");

}

 

/* another inverse triangle*/

for(k=1; k <= 16; k++)

{

    for(l=1; l<=16-k; l++)

        printf(" ");

    for(l=1; l<=2*k-1; l++)

        printf("T");

    printf("\n");

}

    return 0;

}

 

[bodo@bakawali ~]$ gcc forloop.c -o forloop

[bodo@bakawali ~]$ ./forloop

 

Triangle lol!

HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH

 HHHHHHHHHHHHHHHHHHHHHHHHHHHHH

  HHHHHHHHHHHHHHHHHHHHHHHHHHH

   HHHHHHHHHHHHHHHHHHHHHHHHH

    HHHHHHHHHHHHHHHHHHHHHHH

     HHHHHHHHHHHHHHHHHHHHH

      HHHHHHHHHHHHHHHHHHH

       HHHHHHHHHHHHHHHHH

        HHHHHHHHHHHHHHH

         HHHHHHHHHHHHH

          HHHHHHHHHHH

           HHHHHHHHH

            HHHHHHH

             HHHHH

              HHH

               H

               T

              TTT

             TTTTT

            TTTTTTT

           TTTTTTTTT

          TTTTTTTTTTT

         TTTTTTTTTTTTT

        TTTTTTTTTTTTTTT

       TTTTTTTTTTTTTTTTT

      TTTTTTTTTTTTTTTTTTT

     TTTTTTTTTTTTTTTTTTTTT

    TTTTTTTTTTTTTTTTTTTTTTT

   TTTTTTTTTTTTTTTTTTTTTTTTT

  TTTTTTTTTTTTTTTTTTTTTTTTTTT

 TTTTTTTTTTTTTTTTTTTTTTTTTTTTT

TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT

 

/* -----------whilelol.c--------------- */

/* demonstrates a simple while statement */

#include <stdio.h>

 

int main()

{

    int calculate, sum = 0;

    /* print the numbers 1 through 12 */

    /* set the initial value... */

    calculate = 1;

    /* set the while condition... */

    while(calculate <= 10)

    {

        /* display... */

        printf("%d -->Sum = %d\n", calculate, sum);

        sum = sum + calculate;

        /* increment by 1...repeats */

        calculate++;

    }

    printf("\n");

    return 0;

}

 

[bodo@bakawali ~]$ gcc whilelol.c -o whilelol

[bodo@bakawali ~]$ ./whilelol

 

1 -->Sum = 0

2 -->Sum = 1

3 -->Sum = 3

4 -->Sum = 6

5 -->Sum = 10

6 -->Sum = 15

7 -->Sum = 21

8 -->Sum = 28

9 -->Sum = 36

10 -->Sum = 45

 

/* ----- systemcall.c -------*/

/* demonstrates the system() function */

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

        // declare a buffer to hold input

        char input[40];

        while (1)

        {

                // get the user command

                puts("\nInput the command, blank to exit");

                // read the user input

                gets(input);

                // exit if a blank line was entered

                if(input[0] == '\0')

                exit(0);

        // execute the command

        system(input);

        }

return 0;

}

 

[bodo@bakawali ~]$ gcc systemcall.c -o hehehe

/tmp/cc23DhgK.o(.text+0x34): In function `main':

: warning: the `gets' function is dangerous and should not be used.

[bodo@bakawali ~]$ ./hehehe

 

Input the command, blank to exit

ls -F -l

total 1908

-rwxrwxr-x  1 bodo bodo  34243 Apr 23 10:49 algo*

-rwxrwxr-x  1 bodo bodo  17566 Apr 23 10:53 algocopy*

-rw-rw-r--  1 bodo bodo   1014 Apr 23 10:53 algocopy.cpp

-rw-rw-r--  1 bodo bodo   1191 Apr 23 10:48 algo.cpp

-rwxrwxr-x  1 bodo bodo  23033 Apr 23 11:23 algofindfirstof*

-rw-rw-r--  1 bodo bodo   1751 Apr 23 11:22 algofindfirstof.cpp

-rwxrwxr-x  1 bodo bodo  37395 Apr 23 11:28 algoiterswap*

...

 

Input the command, blank to exit

 

[bodo@bakawali ~]$

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

 

Further C/C++ related reading:

 

  1. Check the best selling C / C++ books at Amazon.com.
  2. The source code for this Module is: C/C++ loops source codes.
  3. The lab worksheets for your practice are: C/C++ program control repetition 1, C/C++ program control repetition 2, C/C++ program control selection 1, C/C++ program control selection 2 and C/C++ program control selection 3.

 

 

 

 

 

 

|< C & C++ Program Controls 3 | Main | C & C++ Arrays 1 >| Site Index | Download |


C Formatted Input/Output:  Part 1 | Part 2 | Part 3 | Part 4 |