Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

fundametals of programming two

The document provides a comprehensive overview of fundamental programming concepts in C++, focusing on functions, data structures, and file management. It covers topics such as predefined and user-defined functions, function arguments, structures, and file operations, along with examples and exercises. The content is structured to guide readers through the essential elements of programming, including the use of arrays and the importance of function prototypes.

Uploaded by

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

fundametals of programming two

The document provides a comprehensive overview of fundamental programming concepts in C++, focusing on functions, data structures, and file management. It covers topics such as predefined and user-defined functions, function arguments, structures, and file operations, along with examples and exercises. The content is structured to guide readers through the essential elements of programming, including the use of arrays and the importance of function prototypes.

Uploaded by

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

Contents

Overview fundamental programming .......................................................................................................... 1


Functions ....................................................................................................................................................... 3
Predefined Functions ................................................................................................................................ 3
User-Defined Functions ............................................................................................................................ 5
Default Arguments (Parameters) ............................................................................................................ 10
Working of default arguments ............................................................................................................ 10
Declaring and Defining Functions ........................................................................................................... 12
Declaring the Function ........................................................................................................................ 12
Function Prototypes............................................................................................................................ 13
Defining the Function.............................................................................................................................. 13
Execution of Functions ............................................................................................................................ 16
Function Arguments: .............................................................................................................................. 19
Inline function ......................................................................................................................................... 24
Function Overloading.............................................................................................................................. 26
Recursion ............................................................................................................................................ 28
Exercise ....................................................................................................................................................... 29
Structure ..................................................................................................................................................... 30
Defining a Structure: ............................................................................................................................... 30
Accessing Structure Members: ............................................................................................................... 31
Structure and Function ........................................................................................................................... 33
Exercise ................................................................................................................................................... 36
File Management ........................................................................................................................................ 37
Open a file ............................................................................................................................................... 38
Closing a file ............................................................................................................................................ 38
Text files .................................................................................................................................................. 38
Binary files............................................................................................................................................... 40
Exercise ................................................................................................................................................... 41
Index............................................................................................................................................................ 42
Reference .................................................................................................................................................... 44

I|Page
Overview fundamental programming
Variables in a program have values associated with them. During program execution these values
are accessed by using the identifier associated with the variable in expressions etc. In none of the
programs written so far have very many variables been used to represent the values that were
required. Thus even though programs have been written that could handle large lists of numbers
it has not been necessary to use a separate identifier for each number in the list. This is because
in all these programs it has never been necessary to keep a note of each number individually for
later processing. For example in summing the numbers in a list only one variable was used to
hold the current entered number which was added to the accumulated sum and was then
overwritten by the next number entered. If that value were required again later in the program
there would be no way of accessing it because the value has now been overwritten by the later
input.

If only a few values were involved a different identifier could be declared for each variable, but
now a loop could not be used to enter the values. Using a loop and assuming that after a value
has been entered and used no further use will be made of it allows the following code to be
written. This code enters six numbers and outputs their sum:

sum = 0.0;
for (i = 0; i < 6; i++)
{
cin >> x;
sum += x;
}
This of course is easily extended to n values where n can be as large as required. However if it
was required to access the values later the above would not be suitable. It would be possible to
do it as follows by setting up six individual variables:

float a, b, c, d, e, f;

and then handling each value individually as follows:

sum = 0.0;
cin >> a; sum += a;
cin >> b; sum += b;
cin >> c; sum += c;
cin >> d; sum += d;
cin >> e; sum += e;
cin >> f; sum += f;

1|Page
which is obviously a very tedious way to program. To extend this solution so that it would work
with more than six values then more declarations would have to be added, extra assignment
statements added and the program re-compiled. If there were 10000 values imagine the tedium of
typing the program (and making up variable names and remembering which is which)!

To get round this difficulty all high-level programming languages use the concept of a data
structure called an Array.

2|Page
Functions
A function is, in effect, a subprogram that can act on data and return a value. Every C++ program
has at least one function, main(). When your program starts, main() is called automatically.
main() might call other functions, some of which might call still others.
Each function has its own name, and when that name is encountered, the execution of the
program branches to the body of that function. When the function returns, execution resumes on
the next line of the calling function.

When a program calls a function, execution switches to the function and then resumes at the line
after the function call. Well-designed functions perform a specific and easily understood task.
Complicated tasks should be broken down into multiple functions, and then each can be called in
turn. Functions come in two varieties: user-defined and built-in. Built-in functions are part of
your compiler package--they are supplied by the manufacturer for our use.

Predefined Functions
C++ Standard Library contains many predefined functions to perform various operations.
Predefined functions are organized into separate libraries. I/O functions are in iostream header
Math functions are in cmath header some predefined C++ mathematical functions:
 Power Function - pow(x,y):
 Power function pow(x,y) has two parameters
 pow(x,y) returns value of type double
 pow(x,y) calculates x to the power of y: pow(2,3) = 8.0
 x and y called parameters (or arguments) of function pow
 Square Root Function - sqrt(x):
 Square root function sqrt(x) has only one parameter
 sqrt(x) returns value of type double
 sqrt(x) calculates non-negative square root of x, for x >= 0.0: sqrt(2.25) = 1.5
 Floor Function - floor(x):
 Floor function floor(x) has only one parameter
 floor(x) returns value of type double
 floor(x) calculates largest whole number not greater than x: floor(48.79) = 48.0

3|Page
Example: In general, function arguments may be constants, variables or more complex
expressions The pre-defined math function sqrt listed above takes one input value (of type
double) and returns its square root. Sample calls:
double x = 9.0, y = 16.0, z;
z = sqrt(36.0); // sqrt returns 6.0 (gets stored in z)
z = sqrt(x);// sqrt returns 3.0 (gets stored in z)
z = sqrt(x + y);// sqrt returns 5.0 (gets stored in z)
cout << sqrt(100.0);// sqrt returns 10.0, which gets printed
cout << sqrt(49); // because of automatic type conversion rules
// we can send an int where a double is expected
// this call returns 7.0
// in this last one, sqrt(625.0) returns 25.0, which gets sent as the
// argument to the outer sqrt call. This one returns 5.0, which gets
// printed
cout << sqrt(sqrt(625.0));

4|Page
User-Defined Functions
For better understanding of arguments and return in functions, user-defined functions can be
categorized as:

 Function with no argument and no return value.


 Function with no argument but return value.
 Function with argument but no return value.
 Function with argument and return value.

Consider a situation in which you have to check prime number. This problem is solved below by
making user-defined function in 4 different ways as mentioned above.

5|Page
Example No arguments passed and no return value.

6|Page
Example No arguments passed but a return value

7|Page
Example Arguments passed but no return value

8|Page
Example Arguments passed and a return value.

9|Page
Default Arguments (Parameters)
In C++ programming, you can provide default values for function parameters. The idea behind
default argument is simple. If a function is called by passing argument/s, those arguments are
used by the function. But if the argument/s are not passed while invoking a function then, the
default values are used. Default value/s are passed to argument/s in the function prototype.

Working of default arguments

10 | P a g e
Example C++ Program to demonstrate working of default argument.

11 | P a g e
Declaring and Defining Functions
Using functions in your program requires that you first declare the function and that you then
define the function. The declaration tells the compiler the name, return type, and parameters of
the function. The definition tells the compiler how the function works. No function can be called
from any other function that hasn't first been declared. The declaration of a function is called its
prototype.

Declaring the Function


There are three ways to declare a function:
• Write your prototype into a file, and then use the #include directive to include it in your
program.

• Write the prototype into the file in which your function is used.

• Define the function before it is called by any other function. When you do this, the
definition acts as its own declaration.

Although you can define the function before using it, and thus avoid the necessity of creating a
function prototype, this is not good programming practice for three reasons.
First, it is a bad idea to require that functions appear in a file in a particular order. Doing so
makes it hard to maintain the program as requirements change.
Second, it is possible that function A() needs to be able to call function B(), but function B() also
needs to be able to call function A() under some circumstances. It is not possible to define
function A() before you define function B() and also to define function B() before you define
function A(), so at least one of them must be declared in any case.
Third, function prototypes are a good and powerful debugging technique. If your prototype
declares that your function takes a particular set of parameters, or that it returns a particular type
of value, and then your function does not match the prototype, the compiler can flag your error
instead of waiting for it to show itself when you run the program.

12 | P a g e
Function Prototypes
Many of the built-in functions you use will have their function prototypes already written in the
files you include in your program by using #include. For functions you write yourself, you must
include the prototype.
The function prototype is a statement, which means it ends with a semicolon. It consists of the
function's return type, name, and parameter list.
The parameter list is a list of all the parameters and their types, separated by commas. .The
function prototype and the function definition must agree exactly about the return type, the name,
and the parameter list. If they do not agree, you will get a compile-time error. Note, however,
that the function prototype does not need to contain the names of the parameters, just their types.
A prototype that looks like this is perfectly legal:
Syntax:
datatype name(datatype name,datatype name); or
datatype name(datatype,datatype);
example int Area(int length, int width);
int Area(int, int);
This prototype declares a function named Area() that returns a long and that has two parameters,
both integers. Although this is legal, it is not a good idea. Adding parameter names makes your
prototype clearer. The same function with named parameters might be.

Defining the Function


The definition of a function consists of the function header and its body. The header is exactly
like the function prototype, except that the parameters must be named, and there is no
terminating semicolon. The body of the function is a set of statements enclosed in braces.
Functions
Function Prototype Syntax
return_type function_name ( [type [parameterName]]...);
Function Definition Syntax
return_type function_name ( [type parameterName]...){ statements;}

13 | P a g e
A function prototype tells the compiler the return type, name, and parameter list. Functions are
not required to have parameters, and if they do, the prototype is not required to list their names,
only their types. A prototype always ends with a semicolon (;). A function definition must agree
in return type and parameter list with its prototype. It must provide names for all the parameters,
and the body of the function definition must be surrounded by braces. All statements within the
body of the function must be terminated with semicolons, but the function itself is not ended
with a semicolon; it ends with a closing brace. If the function returns a value, it should end with
a return statement, although return statements can legally appear anywhere in the body of the
function. Every function has a return type. If one is not explicitly designated, the return type will
be int. be sure to give every function an explicit return type. If a function does not return a value,
its return type will be void.

Example calculates the area of the yard using function prototype.

14 | P a g e
Example this program finds the absolute value of an integer using a function.

15 | P a g e
Example write a program that display when user enter 1 “Hello”,0 “good bye”.

Execution of Functions
• Each function has its own name.

• When that name is encountered, called function call, the execution of the program
branches to the body of that function – called function.

• When the function returns, execution resumes on the next line of the calling function.

• Functions can also call other functions and can even call themselves.

Variable

– Local variable - variables declared within a function (or block)

– Global variabler – variables declared outside of every function definition

16 | P a g e
Example The use of local variables and parameters. Displays temperature:

Example The use of global variables and parameters. calculate the sum of 3 numbers with
no parameter and return values

17 | P a g e
Example finding the maximum of three floating point numbers using function definition

Example C++ Program to convert binary number to decimal.

18 | P a g e
Function Arguments:

If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.

While calling a function, there are two ways that arguments can be passed to a function:

Call Type Description


This method copies the actual value of an argument into the formal
Call by value parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the
Call by pointer
actual argument used in the call. This means that changes made to
the parameter affect the argument.
This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the
Call by reference
actual argument used in the call. This means that changes made to
the parameter affect the argument.

19 | P a g e
Example the following program show that the addition in function by passing the value.

Example calculate the sum of 3 numbers with no parameter and return values

20 | P a g e
Example calculate the sum of 3 numbers with return value no parameters

Example calculate the sum of 3 numbers with parameter passing

21 | P a g e
Example passing parameters by reference

22 | P a g e
Example Simple Merge Sort Program Using Functions and Array.

23 | P a g e
Inline function
C++ inline function is powerful concept that is commonly used with classes. If a function is
inline, the compiler places a copy of the code of that function at each point where the function is
called at compile time. Any change to an inline function could require all clients of the function
to be recompiled because compiler would need to replace all the code once again otherwise it
will continue with old functionality. To inline a function, place the keyword inline before the
function name and define the function before any calls are made to the function. The compiler
can ignore the inline qualifier in case defined function is more than a line. A function definition
in a class definition is an inline function definition, even without the use of the inline specifies.

Syntax

inline return_type function_name ( [type parameterName1], [type parameterName2]...)

statements;

24 | P a g e
Following example, which makes use of inline function to return max of two numbers.

Following is an example, which makes use of inline function to return multiplication of two
numbers.

25 | P a g e
Function Overloading
Two or more functions having same name but different argument(s) are known as overloaded
functions. In C++ programming, two functions can have same name if number and/or type of
arguments passed are different. These functions having different number or type (or both) of
parameters are known as overloaded functions.

int test() { }

int test(int a) { }

float test(double a) { }

int test(int a, double b) { }

Example Function Overloading

26 | P a g e
Example Function Overloading Program to compute absolute value Works both for integer
and float.

27 | P a g e
Recursion
A function that calls itself is known as recursive function. And, this technique is known as
recursion.

How recursion works in C++?

void recurse()

... .. ...

recurse();

... .. ...

int main()

... .. ...

recurse();

... .. ...

Example: Calculate Sum of Natural numbers using Recursion

28 | P a g e
Exercise
1. Write the sum, subtract, product and division numbers using function.
2. Write a program Factorial /factorial calculator using function.
3. Write recursive factorial function.
4. Write a function which takes a floating point value for the variable x and computes the
value of the following expression x3-5x2+12x-24.
5. Write a program that Convert Octal Number to Decimal and vice-versa.

29 | P a g e
Structure

C/C++ arrays allow you to define variables that combine several data items of the same kind but
structure is another user defined data type which allows us to combine data items of different
kinds.

Defining a Structure:

To define a structure, we must use the struct statement. The struct statement defines a new data
type, with more than one member, for your program. The format of the struct statement is this:

struct [structure tag]


{
member definition;
member definition;
...
member definition;
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the structure's definition,
before the final semicolon, we can specify one or more structure variables but it is optional. Here
is the way we would declare the Book structure:

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
}book;

30 | P a g e
Accessing Structure Members:

To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use struct keyword to define variables of structure
type.

Following is the example to explain usage of structure:

31 | P a g e
Example the following program calculate bonus and score using structure.

Example Stores some personal data in a structure, then print the info out.

32 | P a g e
Example creating 5 students using an array

Structure and Function


Structure variables can be passed to a function and returned in a similar way as normal
arguments.

33 | P a g e
Example C++ Structure and Function.

34 | P a g e
Example returning structure from function in C++.

35 | P a g e
Exercise
1. A student record consist of his id number, a list of marks, average mark, and his rank for
n number of students.
2. Declare a single structure data type suitable for an employee record of the type illustrated
below:
Number Name Rate Hours
3462 JONES 4.62 40
6793 Robbins 5.83 38
7834 Swain 6.89 40
9002 Williams 4.75 42
3. Use the functions in problem number 1 to read and display a list of students record.
Modify the display function so that it displays the list in a tabular form. Add another
function to your program in problem number 2 which can display only the list of female
or male students depending on the user choice.
4. Write a program that demonstrates using member variables for user input, output, and
mathematical operations.

36 | P a g e
File Management
File handling is an important part of all programs. Most of the applications will have their own
features to save some data to the local disk and read data from the disk again. Files which are on
the secondary storage device are called physical files. In order to process file through program,
logical file must be created on the RAM. This logical file is nothing but an object having file
data type. As an object there should be a variable identifier that points to it. This variable is
called file variable and sometimes also called file handler. C++ File I/O classes simplify such file
read/write operations for the programmer by providing easier to use classes.

C++ provides the following classes to perform output and input of characters to/from files:
 ofstream: Stream class to write on files
 ifstream: Stream class to read from files
 fstream: Stream class to both read and write from/to files.
These classes are derived directly or indirectly from the classes istream, and ostream. We have
already used objects whose types were these classes: cin is an object of class istream and cout is
an object of class ostream. Therefore, we have already been using classes that are related to our
file streams. And in fact, we can use our file streams the same way we are already used to use cin
and cout, with the only difference that we have to associate these streams with physical files.
Examples the following programs creates a file name example and write on it.

37 | P a g e
Open a file
The first operation generally performed on an object of one of these classes is to associate it to a
real file. This procedure is known as to open a file. An open file is represented within a program
by a stream object (an instantiation of one of these classes, in the previous example this was
myfile) and any input or output operation performed on this stream object will be applied to the
physical file associated to it. In order to open a file with a stream object we use its member
function open():
open (filename, mode);

Closing a file
When we are finished with our input and output operations on a file we shall close it so that its
resources become available again. In order to do that we have to call the stream's member
function close(). This member function takes no parameters, and what it does is to flush the
associated buffers and close the file:
Example myfile.close();
Once this member function is called, the stream object can be used to open another file, and the
file is available again to be opened by other processes. In case that an object is destructed while
still associated with an open file, the destructor automatically calls the member function close().

Text files
Text file streams are those where we do not include the ios::binary flag in their opening mode.
These files are designed to store text and thus all values that we input or output from/to them can
suffer some formatting transformations, which do not necessarily correspond to their literal
binary value. Data output operations on text files are performed in the same way we operated
with cout:

38 | P a g e
Example writing on a text file

Example reading a text files


1. First open notepad.
a. Click start
b. Click notepad
2. Save the file name example.

39 | P a g e
Binary files
In binary files, to input and output data with the extraction and insertion operators (<< and >>)
and functions like getline is not efficient, since we do not need to format any data, and data may
not use the separation codes used by text files to separate elements (like space, newline, etc...).
File streams include two member functions specifically designed to input and output binary data
sequentially: write and read. The first one (write) is a member function of ostream inherited by
ofstream. And read is a member function of istream that is inherited by ifstream. Objects of class
fstream have both members.
Their prototypes are:
write ( memory_block, size );
read ( memory_block, size );
Where memory_block is of type "pointer to char" (char*), and represents the address of an array
of bytes where the read data elements are stored or from where the data elements to be written
are taken. The size parameter is an integer value that specifies the number of characters to be
read or written from/to the memory block.
Example reading the binary file.
1. Open notepad.
2. Save notepad example.bin.

40 | P a g e
Exercise
1. Write c++ program to write number 1 to 100 in a data file num.txt
2. Write a c++ program that obtain the size of the file.

41 | P a g e
Index
University of Gondar
College of Natural and Computational Sciences
Department of Computer Science
Course Information: Instructor Contact Information:
Course Title: Fundamentals of Programming I Instructor’s Name : Shiferaw T.
Course Code:CoSc1014E-mail Address:shif18.teg@gmail.com
Credit Hour: 3 or ECTS 5Office location: Building T-09, Room: 302
Prerequisite: Fundamentals of Programming I
Course Description:
The course focuses on the procedural programming language which topics include: Array, string,
pointer, modular programming, structure and file management system.
Course Objectives:
At the end of the course students will be able to:
 Solve enormous problem using procedural approaches
 Identifyand use different C++ programming language tools and
 Apply the procedural programming language approaches and tools in varies area
 Develop varies application software using C++ programming language
 Acquire an excellent programming language skills
 Get familiar with array, pointer, string, function, file management and its application
Course contents:
1. Overview of Fundamental Programming I
Programming language paradigms and C++compiler, program structure, variable and its type,
identifier, constant and literals, data type, reserved words, variable definition and declaration,
assigning and initializing variables, operators, control and decision making structures.
2. Modular Programming

Function in C++, function definition and prototypes, function parameters and arguments, passing
arguments by value, reference and address, returning values by value, reference, and address,
recursive and inline functions, function overloading, default parameters, function Array and pointers

42 | P a g e
3. Structure
Structure specification, definition of structure, declaring and using structure data type, array of
structure,
declaring structure data type, array vs. structure
4. File Management
Streams and file, text and binary files, texts file processing, binary file processing, random access
file, Introduction to object oriented programming and defining class
Required Text books and Reference materials:
Walter Savitch, “Problem solving with C++ - The Object of programming”, Menlo Park:
Addison-Wesley, 1996.
Dietel&Dietel, “C How To Program”, Third Edition, Prentice – Hall, 2003
Robert Lafore, “The Waite Group’s programming Using Turbo C++” Techmedia, 1993
John R. Hubrard, “Fundamentals of Computing with C++,” Shuam’s Outline, 1997
Jess Liberry, “An Introduction to C++” 1995 Robert Lafore, “The Wait Group Object Oriented
programming With C++” 1994
Student Assessments:
Item and activities Point %
Quiz and Class participation 10 10
Test # 1 10 10
Test # 2 10 10
Assignment 10 10
Project 20 20
Final Exam 40 40

43 | P a g e
Reference
1. C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007.
2. Professional_c_2nd_edition Marc Gregoire Nicholas A. Solter Scott J. Kleper.
3. Computer science handout.

44 | P a g e

You might also like