0% found this document useful (0 votes)
116 views

CL103 - Computer Programming - Lab # 01 (Introduction & Functions)

This document provides an introduction to functions in C/C++ programming. It discusses various types of functions including predefined functions, user-defined value-returning functions, and void functions. It provides examples of using value-returning functions that return a single value or multiple expressions. The document also demonstrates passing parameters to functions, including value and reference parameters, and using functions to return grades based on test scores. The overall objectives are to explain the concept of functions, different types of functions, and how to define, call and pass parameters to functions in C/C++.

Uploaded by

Mohsan Naqi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views

CL103 - Computer Programming - Lab # 01 (Introduction & Functions)

This document provides an introduction to functions in C/C++ programming. It discusses various types of functions including predefined functions, user-defined value-returning functions, and void functions. It provides examples of using value-returning functions that return a single value or multiple expressions. The document also demonstrates passing parameters to functions, including value and reference parameters, and using functions to return grades based on test scores. The overall objectives are to explain the concept of functions, different types of functions, and how to define, call and pass parameters to functions in C/C++.

Uploaded by

Mohsan Naqi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Lab # 01: Introduction to Lab & Functions I Page 1 of 22

CL103: Computer Programming


Lab # 01: Introduction to Lab & Functions I
Objectives:

Level of C/C++ Programming in Computer Science Context


What are the Functions
Predefined Functions
User-Defined Functions
Value-returning functions
Multiple Expressions in a return statement
Void Functions
Parameters
Value Parameters
Reference Variables as Parameters
Value and Reference Parameters and Memory Allocation
Global Variables
Static and Automatic Variables

Instructions:

1. You are allowed to use your own laptops.


2. You can consult the books, manuals and class lectures.
3. You should have stationary like register and ballpoint to analyze the tasks first.
4. Ensure that your environment is working properly.
5. In practice session, consultation is allowed.
6. No discussion is allowed during tasks solution.
7. Attempt all questions yourself.
8. Submission of all tasks solutions is necessary in any way.
9. Tasks completed in specified time will be graded.
10. Cheating is strictly prohibited otherwise rules as per university will be applied as a result
of F-Grade in lab.

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 2 of 22

Getting Started

Below mentioned things should be in mind on figure tips.

1. System Login to Domain


a. User Name: user
b. Password : abc321
2. Accessing to Lectures Server
a. User Name: [Student Roll Number]
b. Password: ****
3. Accessing Software Folder (192.168.1.3)
a. User Name: As to access Lectures Server
4. Installation of any software
a. Needs Administrators Rights
b. Consult to Lab Assistant for any installation
5. Trouble Shooting of PSs and Internet Access
a. Do it as you can do and learnt till now
b. Consult lab assistant for more proceedings
c. Consult your class fellows as they are good coordinators
6. Operating System for Lab
a. Windows
b. If you have any other operating system then search and install compatibleIDEs
7. How to prepare lab manuals for Programming Labs
a. Computer Programming
b. Sample Lab Manual will available soon on lectures server
8. Windows Command Prompt (CMD)
a. You should be familiar how to use Command Prompt (CMD)
b. Ask to instructor
i. How to open a directory/folder
ii. Listing of directory
iii. Leaving a directory/folder
iv. Executing any executable file

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 3 of 22

Level of C/C++ Programming in Computer Science Context


There is a proper hierarchy of languages as shown in the figures.

Figure 1: Higher Level Programming Languages & Dependencies

What are the Functions


Functions are like building blocks. They let you divide complicated programs into manageable pieces.
They have other advantages, too:

1. While working on one function, you can focus on just that part of the program and construct it,
debug it, and perfect it.
2. Different people can work on different functions simultaneously.
3. If a function is needed in more than one place in a program or in different programs, you can
write it once and use it many times.
4. Using functions greatly enhances the programs readability because it reduces the complexity of
the function main

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 4 of 22

Predefined Functions

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 5 of 22

#include <iostream>
#include <cmath>
#include <cctype>
#include <conio.h>

using namespace std;

void main()
{
int x;
double u, v;
cout<<"Line 1: Uppercase a is "<<(char)(toupper('a'))<<endl;

u = 4.2;
v = 3.0;

cout<<"Line 4: "<<u<<" to the power of "<< v <<" = "<<pow(u, v)<<endl;


cout <<"Line 5: 5.0 to the power of 4 = "<<pow(5.0, 4)<< endl;

u = u + pow(3.0, 3);

cout <<"Line 7: u = "<<u<<endl;

x = -15;

cout <<"Line 9: Absolute value of "<<x<<" = "<<abs(x)<<endl;

_getch();
}

Output
Line 1: Uppercase a is A
Line 4: 4.2 to the power of 3 = 74.088
Line 5: 5.0 to the power of 4 = 625
Line 7: u = 31.2
Line 9: Absolute value of -15 = 15

User-Defined Functions
User-defined functions are classified into two categories:
1. Value-returning functions - Functions that have a return type. These functions return a value of
a specific data type using the return statement, which we will explain shortly.
2. Void functions - Functions that do not have a return type. These functions do not use a return
statement to return a value.

Value-returning functions
Syntax of a Value-returning function
functionType functionName(formal parameter list)
{
statements
}

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 6 of 22

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 7 of 22

#include <iostream>
#include <conio.h>

using namespace std;

double larger(double x, double y); //Function Prototype


double compareThree(double x, double y, double z); //Function Prototype

void main()
{
double one, two;

cout << "Line 2: The larger of 5 and 10 is "<< larger(5, 10) << endl;
cout << "Line 3: Enter two numbers: ";
cin >> one >> two;
cout << endl;
cout << "Line 6: The larger of " << one<< " and " << two << " is "<<
larger(one, two) << endl; //Function call
cout << "Line 7: The largest of 43.48, 34.00, "<< "and 12.65 is "<<
compareThree(43.48, 34.00, 12.65)<< endl; //Function call

_getch();
}

double larger(double x, double y) //Function Definition


{
double max;

if (x >= y)
max = x;
else
max = y;

return max;
}

double compareThree (double x, double y, double z) //Function Definition


{
return larger(x, larger(y, z));
}

Sample Output
Line 2: The larger of 5 and 10 is 10
Line 3: Enter two numbers: 25.6 73.85
Line 6: The larger of 25.6 and 73.85 is 73.85
Line 7: The largest of 43.48, 34.00, and 12.65 is 43.48

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 8 of 22

Multiple Expressions in a return statement

#include <iostream>
#include <conio.h>

using namespace std;

int funcRet1();
int funcRet2(int z);

void main()
{
int num = 4;

cout<<"Line 1: The value returned by funcRet1: "<<funcRet1()<<endl;


cout <<"Line 2: The value returned by funcRet2: "<<funcRet2(num)<<endl;

_getch();
}

int funcRet1()
{
int x = 45;

return 23, x; //only the value of x is returned


}

int funcRet2(int z)
{
int a = 2;
int b = 3;

return 2 * a + b, z + b; //only the value of z + b is returned


}

Sample Output
Line 1: The value returned by funcRet1: 45
Line 2: The value returned by funcRet2: 7

Note: Even though a return statement can contain more than one expression, a return statement in
your program should contain only one expression. Having more than one expression in a return
statement may result in redundancy, wasted code, and a confusing syntax.

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 9 of 22

#include <iostream>
#include <conio.h>

using namespace std;

char courseGrade(int score);

void main()
{
int score;

cout<<"Enter Student's Score (0-100): ";


cin>>score;

cout<<"Course Grade: "<<courseGrade(score);


_getch();
}

char courseGrade(int score)


{
switch (score / 10)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return 'F';
case 6:
return 'D';
case 7:
return 'C';
case 8:
return 'B';
case 9:
case 10:
return 'A';
}
}

Sample output
Enter Student's Score (0-100): 60
Course Grade: D

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 10 of 22

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <conio.h>
using namespace std;
int rollDice(int num);
void main()
{
cout << "The number of times the dice are rolled to "<< "get the sum 10
= " << rollDice(10) << endl;
cout << "The number of times the dice are rolled to "<< "get the sum 6
= " << rollDice(6) << endl;

_getch();
}
int rollDice(int num)
{
int die1;
int die2;
int sum;
int rollCount = 0;
srand(time(0));
do
{
die1 = rand() % 6 + 1
;
die2 = rand() % 6 + 1;
sum = die1 + die2;
rollCount++;
}
while (sum != num);

return rollCount;
}

Output
The number of times the dice are rolled to get the sum 10 = 11
The number of times the dice are rolled to get the sum 6 = 7

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 11 of 22

#include <iostream>
#include <conio.h>

using namespace std;

double larger(double x, double y);

void main()
{
double num;
double max;
int count;

cout << "Enter 10 numbers." << endl;


cin >> num;
max = num;

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


{
cin >> num;
max = larger(max, num);
}

cout << "The largest number is " << max<< endl;

_getch();
}

double larger(double x, double y)


{
if (x >= y)
return x;
else
return y;
}

Sample Output
Enter 10 numbers.
5 6 90 30 90 12 47 52 60 6
The largest number is 90

#include <iostream>
#include <iomanip>
#include <conio.h>

using namespace std;

//Named constants residential customers


const double RES_BILL_PROC_FEES = 4.50;
const double RES_BASIC_SERV_COST = 20.50;
const double RES_COST_PREM_CHANNEL = 7.50;

//Named constants business customers


const double BUS_BILL_PROC_FEES = 15.00;
const double BUS_BASIC_SERV_COST = 75.00;
const double BUS_BASIC_CONN_COST = 5.00;

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 12 of 22

const double BUS_COST_PREM_CHANNEL = 50.00;


double residential();
double business();

void main()
{
int accountNumber;
char customerType;
double amountDue;

cout << "This program computes a cable bill."<< endl;


cout << "Enter account number: ";
cin >> accountNumber;
cout << endl;
cout << "Enter customer type: R, r "<< "(Residential), B, b (Business):
";
cin >> customerType;
cout << endl;

switch (customerType)
{
case 'r':
case 'R':
amountDue = residential();
cout << "Account number = "<< accountNumber << endl;
cout << "Amount due = $"<< amountDue << endl;
break;
case 'b':
case 'B':
amountDue = business();
cout << "Account number = "<< accountNumber << endl;
cout << "Amount due = $"<< amountDue << endl;
break;
default:
cout << "Invalid customer type."<< endl;
}

_getch();
}

double residential()
{
int noOfPChannels; //number of premium channels
double bAmount; //billing amount

cout << "Enter the number of premium "<< "channels used: ";
cin >> noOfPChannels;
cout << endl;

bAmount = RES_BILL_PROC_FEES + RES_BASIC_SERV_COST + noOfPChannels *


RES_COST_PREM_CHANNEL;

return bAmount;
}
double business()
{
int noOfBasicServiceConnections;

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 13 of 22

int noOfPChannels; //number of premium channels


double bAmount; //billing amount

cout << "Enter the number of basic "<< "service connections: ";
cin >> noOfBasicServiceConnections;
cout << endl;
cout << "Enter the number of premium "<< "channels used: ";
cin >> noOfPChannels;
cout << endl;

if (noOfBasicServiceConnections <= 10)


bAmount = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST +
noOfPChannels * BUS_COST_PREM_CHANNEL;
else
bAmount = BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST +
(noOfBasicServiceConnections - 10) * BUS_BASIC_CONN_COST + noOfPChannels *
BUS_COST_PREM_CHANNEL;

return bAmount;
}

Sample Output
This program computes a cable bill.
Enter account number: 521

Enter customer type: R, r (Residential), B, b (Business): r

Enter the number of premium channels used: 22

Account number = 521


Amount due = $190.00

Local and Global Variables/Scope of Variables

Void Functions
Void functions and value-returning functions have similar structures. Both have a heading and a body.
Because void functions do not have a data type, they are not used (called) in an expression. A call to a
void function is a stand-alone statement.

Function Definition
The function definition of void functions with parameters has the following syntax:
void functionName(formal parameter list)
{
statements
}

Function Call
The function call has the following syntax:
functionName(actual parameter list);

Example

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 14 of 22

#include <iostream>
#include <conio.h>

using namespace std;

void printStars(int blanks, int starsInLine);

void main()
{
int noOfLines;
int counter;
int noOfBlanks;

cout << "Enter the number of star lines (1 to 20) "<< "to be printed:
";
cin >> noOfLines;

while (noOfLines < 0 || noOfLines > 20)


{
cout << "Number of star lines should be "<< "between 1 and 20" <<
endl;
cout << "Enter the number of star lines "<< "(1 to 20) to be
printed: ";

cin >> noOfLines;


}

cout << endl << endl;


noOfBlanks = 30;

for (counter = 1; counter <= noOfLines; counter++)


{
printStars(noOfBlanks, counter);
noOfBlanks--;
}

_getch();
}

void printStars(int blanks, int starsInLine)


{
int count;

for (count = 1; count <= blanks; count++)


cout << ' ';

for (count = 1; count <= starsInLine; count++)


cout << " * ";

cout << endl;


}

S a m p l e O u t p u t

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 15 of 22

Enter the number of star lines (1 to 20) to be printed: 15

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * *

Parameters
Parameters provide a communication link between the calling function (such as main) and the called
function. They enable functions to manipulate different data each time they are called. In general, there
are two types of formal parameters: value parameters and reference parameters.
Value parameter: A formal parameter that receives a copy of the content of the corresponding actual
parameter.
Reference parameter: A formal parameter that receives the location (memory address) of the
corresponding actual parameter.
When you attach & after the dataType in the formal parameter list of a function, the variable following
that dataType becomes a reference parameter.

void expfun(int one, int& two, char three, double& four)


{
.
.
.
}

Value Parameters
#include <iostream>
#include <conio.h>

using namespace std;

void funcValueParam(int num);

void main()
{
int number = 6;

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 16 of 22

cout<<"Before calling the function "<<"funcValueParam, number = "<<


number<<endl;

funcValueParam(number);

cout<<"After calling the function "<<"funcValueParam, number = "


<<number<<endl;

_getch();
}

void funcValueParam(int num)


{
cout <<"In the function funcValueParam, "<<"before changing, num = "<<
num<<endl;
num = 15;
cout<<"In the function funcValueParam, "<<"after changing, num = "<<
num<<endl;
}

Output

Before calling the function funcValueParam, number = 6


In the function funcValueParam, before changing, num = 6
In the function funcValueParam, after changing, num = 15
After calling the function funcValueParam, number = 6

Reference Variables as Parameters


Reference parameters are useful in three situations:

When the value of the actual parameter needs to be changed


When you want to return more than one value from a function
When passing the address would save memory space and time relative to copying a large
amount of data

#include <iostream>
#include <conio.h>

using namespace std;

void getScore(int& score);


void printGrade(int score);

void main()
{
int courseScore;

cout << "Based on the course score, \n"<< " this program computes the
"<< "course grade." << endl;

getScore(courseScore);
printGrade(courseScore);

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 17 of 22

_getch();
}

void getScore(int& score)


{
cout << " Enter course score: ";
cin >> score;
cout << endl << " Course score is "<< score << endl;
}

void printGrade(int cScore)


{
cout << " Your grade for the course is ";

if (cScore >= 90)


cout << "A." << endl;
else if (cScore >= 80)
cout << "B." << endl;
else if(cScore >= 70)
cout << "C." << endl;
else if (cScore >= 60)
cout << "D." << endl;
else
cout << "F." << endl;
}

Sample Output
Based on the course score,
this program computes the course grade.
Enter course score: 85
Course score is 85
Your grade for the course is B.

Value and Reference Parameters and Memory Allocation


#include <iostream>
#include <conio.h>

using namespace std;

void funOne(int a, int& b, char v);


void funTwo(int& x, int y, char& w);

void main()
{
int num1, num2;
char ch;

num1 = 10;
num2 = 15;

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 18 of 22

ch = 'A';

cout << "Inside main: num1 = " << num1<< ", num2 = " << num2 << ", and
ch = "<< ch << endl;

funOne(num1, num2, ch);

cout << "After funOne: num1 = " << num1<< ", num2 = " << num2 << ", and
ch = "<< ch << endl;

funTwo(num2, 25, ch);

cout << "After funTwo: num1 = " << num1<< ", num2 = " << num2 << ", and
ch = "<< ch << endl;

_getch();
}

void funOne(int a, int& b, char v)


{
int one;

one = a;
a++;
b = b * 2;
v = 'B';

cout << "Inside funOne: a = " << a<< ", b = " << b << ", v = " << v<<
", and one = " << one << endl;
}

void funTwo(int& x, int y, char& w)


{
x++;
y = y * 2;
w = 'G';

cout << "Inside funTwo: x = " << x<< ", y = " << y << ", and w = " <<
w<< endl;
}

Output
Inside main: num1 = 10, num2 = 15, and ch = A
Inside funOne: a = 11, b = 30, v = B, and one = 10
After funOne: num1 = 10, num2 = 30, and ch = A
Inside funTwo: x = 31, y = 50, and w = G
After funTwo: num1 = 10, num2 = 31, and ch = G

#include <iostream>
#include <conio.h>

using namespace std;

void addFirst(int& first, int& second);

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 19 of 22

void doubleFirst(int one, int two);


void squareFirst(int& ref, int val);

void main()
{
int num = 5;
cout << "Inside main: num = " << num<< endl;

addFirst(num, num);

cout << "Inside main after addFirst:"<< " num = " << num << endl;

doubleFirst(num, num);

cout << "Inside main after "<< "doubleFirst: num = " << num << endl;

squareFirst(num, num);

cout << "Inside main after "<< "squareFirst: num = " << num << endl;

_getch();
}

void addFirst(int& first, int& second)


{
cout << " Inside addFirst: first = "<< first << ", second = " << second
<< endl;

first = first + 2;

cout << " Inside addFirst: first = "<< first << ", second = " << second
<< endl;

second = second * 2;

cout << " Inside addFirst: first = "<< first << ", second = " << second
<< endl;
}

void doubleFirst(int one, int two)


{
cout << " Inside doubleFirst: one = "<< one << ", two = " << two <<
endl;

one = one * 2;

cout << " Inside doubleFirst: one = "<< one << ", two = " << two <<
endl;

two = two + 2;

cout << " Inside doubleFirst: one = "<< one << ", two = " << two <<
endl;
}

void squareFirst(int& ref, int val)


{

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 20 of 22

cout << " Inside squareFirst: ref = "<< ref << ", val = " << val <<
endl;

ref = ref * ref;

cout << " Inside squareFirst: ref = "<< ref << ", val = " << val <<
endl;

val = val + 2;

cout << " Inside squareFirst: ref = "<< ref << ", val = " << val <<
endl;
}

Output
Inside main: num = 5
Inside addFirst: first = 5, second = 5
Inside addFirst: first = 7, second = 7
Inside addFirst: first = 14, second = 14
Inside main after addFirst: num = 14
Inside doubleFirst: one = 14, two = 14
Inside doubleFirst: one = 28, two = 14
Inside doubleFirst: one = 28, two = 16
Inside main after doubleFirst: num = 14
Inside squareFirst: ref = 14, val = 14
Inside squareFirst: ref = 196, val = 14
Inside squareFirst: ref = 196, val = 16
Inside main after squareFirst: num = 196

Global Variables
#include <iostream>
#include <conio.h>

using namespace std;

int t;

void funOne(int& a);

void main()
{
t = 15;

cout <<"In main: t = "<< t << endl;

funOne(t);

cout << "In main after funOne: "<< " t = " << t << endl;

_getch();
}

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 21 of 22

void funOne(int& a)
{
cout << "In funOne: a = " << a<< " and t = " << t << endl;

a = a + 12;

cout <<"In funOne: a = "<<a<< " and t = " << t << endl;

t = t + 13;

cout << "In funOne: a = " << a<< " and t = " << t << endl;
}

Output
In main: t = 15
In funOne: a = 15 and t = 15
In funOne: a = 27 and t = 27
In funOne: a = 40 and t = 40
In main after funOne: t = 40

Static and Automatic Variables


A variable for which memory is allocated at block entry and deallocated at block exit is called an
automatic variable. A variable for which memory remains allocated as long as the program executes is
called a static variable. Global variables are static variables, and by default, variables declared within a
block are automatic variables. You can declare a static variable within a block by using the reserved
word static. The syntax for declaring a static variable is:
static dataType identifier;

The following program shows how static and automatic variables behave.

#include <iostream>
#include <conio.h>

using namespace std;

void test();

void main()
{
int count;

for (count = 1; count <= 5; count++)


test();

_getch();
}

void test()
{
static int x = 0;

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman


Lab # 01: Introduction to Lab & Functions I Page 22 of 22

int y = 10;
x = x + 2;
y = y + 1;
cout << "Inside test x = " << x << " and y = "<< y << endl;
}

Output
Inside test x = 2 and y = 11
Inside test x = 4 and y = 11
Inside test x = 6 and y = 11
Inside test x = 8 and y = 11
Inside test x = 10 and y = 11

CL103: Computer Programming Compiled By: Mr. Najeeb Ur Rehman

You might also like