|
| 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 andC/C++ program control selection 3.
system("command");
char *command = "dir"; system(command);
// 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:
|
You should notice that in the program examples used throughout this tutorial, we have used the system("pause"), to pause the program execution temporarily for Borland C++ compiled through IDE. It is used to snapshot the output screen. It is automatically invoked for Microsoft Visual C++ console mode applications.
The return statement has a form:
return expression;
The action is to terminate execution of the current function and pass the value contained in the expression (if any) to the function that invoked it.
The value returned must be of the same type or convertible to the same type as the function (type casting).
More than one return statement may be placed in a function. The execution of the first return statement in the function automatically terminates the function.
If a function calls another function before it is defined, then a prototype for it must be included in the calling function. This gives information to the compiler to look for the called function (callee).
The main() function has a default type int since it returns the value 0 (an integer) to the environment.
A function of type void will not have the expression part following the keyword return. Instead, in this case, we may drop the entire return statement altogether.
Study the following program example and the output.
// 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;
}

Compare with the following program example:
// 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;
}

// 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;
}

// 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;
}

// 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;
}

// 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;
}

// 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;
}

Here we use EOF (acronym, stands forEnd OfFile), normally has the value–1, as the sentinel value. The user types a system-dependent keystroke combination to mean end of file that means ‘I have no more data to enter’.
EOF is a symbolic integer constant defined in the <stdio.h> header file. If the value assigned to grade is equal to EOF, the program terminates.
The keystroke combinations for entering EOF are system dependent.
On UNIX systems and many others, the EOF is <Return key> or ctrl-z or ctrl-d.
On other system such as old DEC VAX VMS® or Microsoft Corp MS-DOS®, the EOF is ctrl-z.
// 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;
}

And program examples compiled usinggcc.
#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 ~]$