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

Fundamentals of Programming in C++ - CH 1

This chapter discusses fundamentals of computer programming and problem solving. It covers what a program and programming language are, as well as the need to learn computer programming. The chapter also describes the different generations of programming languages from machine languages to modern languages. It discusses problem solving processes, software engineering principles, and algorithm design including using flowcharts to model logic.

Uploaded by

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

Fundamentals of Programming in C++ - CH 1

This chapter discusses fundamentals of computer programming and problem solving. It covers what a program and programming language are, as well as the need to learn computer programming. The chapter also describes the different generations of programming languages from machine languages to modern languages. It discusses problem solving processes, software engineering principles, and algorithm design including using flowcharts to model logic.

Uploaded by

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

Fundamentals of Programming in C++ - CH 1 2021

Chapter One
Fundamentals of C++ programming language & Problem-solving using
computer
What is program & programming?
Program: is a set of instructions, to make a computer to do something.
Programming: is a skill that can be acquired by a computer professional that gives
him/her the knowledge of making the computer perform the required operation or
task.

Why do we need to learn computer programming?


Computer programming: is critical if one wants to know how to make the
computer perform a task. Most users of a computer only use the available
applications on the computer. These applications are produced by computer
programmers. Thus, if someone is interested to make such kind of applications,
he/she needs to learn how to talk to the computer, which is learning computer
programming.

What is programming language?


Programming Language: is a set different category of written symbols that
instruct computer hardware to perform specified operations required by the
designer.
What skills do we need to be a programmer?
For someone to be a programmer, in addition to basic skills in computer,
needs to have the following major skills:
• Programming Language Skill: knowing one or more programming
language to talk to the computer and instruct the machine to perform a
task.
• Problem Solving Skill: skills on how to solve real world problem and
represent the solution in understandable format.
• Algorithm D e v e l o p m e n t : skill o f coming up with sequence of
simple and human understandable set of instructions showing the step of
solving the problem. Those set of steps should not be dependent on any
programming language or machine.
In every programming Language there are sets of rules that govern the symbols used in a
programming language. These set of rules determine how the programmer can make the
computer hardware to perform a specific operation. These sets of rules are called syntax.

Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 1


Fundamentals of Programming in C++ - CH 1 2021

1.1. Generations of programming language.


Programming languages are categorized into five generations: (1st, 2nd, 3rd , 4th and 5th
generation languages). These programming languages can also be categorized into two
broad categories: low level and high level languages.
• Low level languages are machine specific or dependent.
• High level languages like COBOL, BASIC are machine independent and can run
on variety of computers.
From the five categories of programming languages, first and second generation
languages are low level languages and the rest are high level programming languages.The
higher the level of a language, the easier it is to understand and use by programmers.
Languages after the fourth generation are referred to as very high level languages.

1.1.1. First Generation (Machine languages, 1940’s):


✓ Difficult to write applications with.
✓ Dependent on machine languages of the specific computer being used.
✓ Machine languages allow the programmer to interact directly with the hardware, and
it can be executed by the computer without the need for a translator.
✓ Is more powerful in utilizing resources of the computer.
✓ Gives power to the programmer.
✓ They execute very quickly and use memory very efficiently.

1.1.2. Second Generation (Assembly languages, early 1950’s):


✓ Uses symbolic names for operations and storage locations.
✓ A system program called an assembler translates a program written in assembly
language to machine language.
✓ Programs written in assembly language are not portable. i.e., different
computer architectures have their own machine and assembly languages.
✓ They are highly used in system software development.

1.1.3. Third Generation (High level languages, 1950’s to 1970’s):


✓ Uses English like instructions and mathematicians were able to define variables
with statements such as Z = A + B
✓ Such languages are much easier to use than assembly language.
✓ Programs written in high level languages need to be translated into machine
language in order to be executed.
✓ The use of common words (reserved words) within instructions makes them
easier to learn.
✓ All third generation programming languages are procedural languages.
✓ In procedural languages, the programmer is expected to specify what is required
and how to perform it.

Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 2


Fundamentals of Programming in C++ - CH 1 2021

1.1.4 Fourth Generation (since late 1970’s):


✓ Have a simple, English like syntax rules; commonly used to access
databases.
✓ Fourth generation languages are non-procedural languages.
✓ The non-procedural method is easier to write, but you have less control over how
each task is actually performed.
✓ In non-procedural languages the programmer is not required to write traditional
programming logic. Programmers concentrate on defining the input and output
rather than the program steps required.
• For example, a command, such as LIST, might display all the records in a file on
screen, separating fields with a blank space. In a procedural language, all the
logic for inputting each record, testing for end of file and formatting each column on
screen has to be explicitly programmed.
✓ Fourth generation languages have a minimum number of syntax rules.
✓ This saves time and free professional programmers for more complex tasks.
✓ Some examples of 4GL are structured query languages (SQL), report
generators, application generators and graphics languages.
1.1.5 Fifth Generation (1990’s):
✓ These are used in artificial intelligence (AI) and expert systems; also used for
accessing databases.
✓ 5GLs are “natural” languages whose instruction closely resembles human speech.
E.g. “get me Jone Brown’s sales figure for the 1997 financial year”.
✓ 5GLs require very powerful hardware and software because of the
complexity involved in interpreting commands in human language.
1.2 Problem solving process and Software Engineering.
1.2.1. Software Engineering.
o Software engineering is the profession that creates and maintains
software applications by applying technologies and practices from
computer science, project management, engineering, application
domain and other fields.
o The method used in solving problems in computer science and/or
information systems is called the software development life cycle.
o The software development life cycle has the following components.
✓ Preliminary investigation
✓ Analysis
✓ Design
✓ Implementation
✓ Testing and maintenance

Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 3


Fundamentals of Programming in C++ - CH 1 2021

1.2.2. Problem Solving


❖ Problem solving is the process of transforming the description of a problem into
the solution by using our knowledge of the problem domain and by relying on our
ability to select and use appropriate problem-solving strategies, techniques, and
tools.
❖ A problem is an undesirable situation that prevents the organization from fully
achieving its purpose, goals and objectives. Or problem can also be defined as the
gap between the existing and the desired situation where problem solving will
try to fill this gap.
❖ There are two approaches of problem solving:
✓ Top down design: is a systematic approach based on theconcept that the
structure of the problem should determine the structure of the solution and what
should be done in lower level. This approach will try to disintegrate a larger
problem into more smaller and manageable problems to narrow the problem
domain.
✓ Bottom up design: is the reverse process where the lowest level
component are built first and the system builds up from the bottom until
the whole process is finally completed.

1.3 Basic Program development tips


The program we design in any programming language need to be:
• Reliable: the program should always do what it is expected to do and
handle all types of exception.
• Maintainable: the program should be in a way that it could be
modified and upgraded when the need arises.
• Portable: It needs to be possible to adapt the software written for one type
of computer to another with minimum modification.
• Efficient: the program should be designed to make optimal use of
time, space and other resources of the computer.

1.4 Algorithm designing and modeling the logic (using flow chart).
✓ A digital computer is a useful tool for solving a great variety of problems.
A solution to a problem is called an algorithm; it describes the sequence of steps to
be performed for the problem to be solved.
✓ Generally, an algorithm is a finite set of well-defined instructions for
accomplishing some task which, given an initial state, will terminate in a
corresponding recognizable end-state.
✓ The algorithm should be:
• Precise and unambiguous
• Efficient ..Correct
Simple

Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 4


Fundamentals of Programming in C++ - CH 1 2021

1.4.1 Modeling a programs logic using flow chart


✓ Algorithm could be designed using many techniques and tools.
✓ One tool of designing algorithm is by using flowcharts. Flowchart is a
graphical way of expressing the steps needed to solve a problem.
✓ A flow chart is a schematic (diagrammatic description) representation of a
process.

Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 5


Fundamentals of Programming in C++ - CH 1 2021

1.5 Compilers and Interpreters.


Any program written in a language other than machine language needs to be translated t o
m a c h i n e language. The set of instructions that do this task are known as translators.
There are different kinds of translator software, among which compilers and interpreters
are of interest for most programmers.
Compilers: a compiler is a computer program that translates a series of statements written
in source code (a collection of statements in a specific programming language) into a resulting
object code (translated instructions of the statements in a programming language). A compiler
changes or translates the whole source code into executable machine code (also called object
code) which is output to a file for latter execution. E.g. C++, Pascal, FORTRAN, etc.
Interpreters: is a computer program that translates a single high level statement and
executes it and then goes to the next high level language line etc. E.g. QBASIC, Lisp etc.
Assemblers: is a computer program that translates an assembly language into machine
languages.

1. Design a flow chart algorithm which sums all the even numbers between 1 and 20
inclusive and then display the sum.

Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 6


Fundamentals of Programming in C++ - CH 1 2021

Mettu University
Collage of Engineering and technology

Worksheet 1
Course Title: Computer Programming / Fundamentals of Programming
Course No : __________

For each of the problems below, develop a flow chart

1) Receive a number and determine whether it is odd or even.


2) Obtain two numbers from the keyboard, and determine and display which (if either) is the
larger of the two numbers.
3) Receive 3 numbers and display them in ascending order from smallest to largest
4) Add the numbers from 1 to 100 and display the sum
5) Add the even numbers between 0 and any positive integer number given by the user.
6) Find the average of two numbers given by the user.
7) Find the average, maximum, minimum, and sum of three numbers given by the user.
8) Find the area of a circle where the radius is provided by the user.
9) Swap the contents of two variables using a third variable.
10) Swap the content of two variables without using a third variable.
11) Read an integer value from the keyboard and display a message indicating if this
number is odd or even.
12) Read 10 integers from the keyboard in the range 0 - 100, and count how many of them are
larger than 50, and display this result.
13) Take an integer from the user and display the factorial of that number

7 Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 7


Fundamentals of Programming in C++ - CH 1 2021

Fundamentals of C++ programming language

2.1 Brief history of C++


Before you jump into C++, you might find it helpful to know a little about the evolution of the C++
programming language. C++ is so deeply rooted in C that you should first see where C began. Bell Labs first
developed the C programming language in the early 1970s, by Dennis Ritchie, primarily so Bell
programmers could write their UNIX operating system for a new DEC (Digital Equipment Corporation)
computer. Until that time, operating systems were written in assembly language, which is tedious, time-
consuming, and difficult to maintain. The Bell Labs people knew they needed a higher-level programming
language to implement their project quicker and create code that was easier to maintain. Because other high-
level languages at the time (COBOL, FORTRAN, PL/I, and Algol) were too slow for an operating system’s
code, the Bell Labs programmers decided to write their own language. They based their new language on
Algol and BCPL. Algol is still used in the European markets, but is not used much in America. BCPL
strongly influenced C, although it did not offer the various data types that the makers of C required. After a
few versions, these Bell programmers developed a language that met their goals well. C is efficient (it is
sometimes called a high, low-level language due to its speed of execution), flexible, and contains the proper
language elements that enable it to be maintained over time.
In the 1980s, Bjourne Stroustrup, working for AT&T, took the C language to its next progression. Mr.
Stroustrup added features to compensate for some of the pitfalls C allowed and changed the way
programmers view programs by adding object-orientation to the language. The object-orientation aspect of
programming started in other languages, such as Smalltalk. Mr. Stroustrup realized that C++ programmers
needed the flexibility and modularity offered by a true OOP programming language

2.2. Structures of C++programs


Any meaningful program written in C++ has to contain a number of components: the main function; some
variable declarations; and some executable statements. For example, the following is a very basic C++
program:

1:#include <iostream.h>
2:
3: int main()
4: {
5: cout<< "Hello World!\n";
6: return 0;
7: }
8 Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 8
Fundamentals of Programming in C++ - CH 1 2021

On line 1, the file iostream.h is included in the file. The first character is the # symbol, which is a signal to
the preprocessor. Each time you start your compiler, the preprocessor is run. The preprocessor reads through
your source code, looking for lines that begin with the pound symbol (#), and acts on those lines before the
compiler runs.

include is a preprocessor instruction that says, "What follows is a filename. Find that file and read it in right
here." The angle brackets around the filename tell the preprocessor to look in all the usual places for this file.
If your compiler is set up correctly, the angle brackets will cause the preprocessor to look for the file
iostream.h in the directory that holds all the H files for your compiler. The file iostream.h (Input-Output-
Stream) is used by cout, which assists with writing to the screen. The effect of line 1 is to include the file
iostream.h into this program as if you had typed it in yourself.

The preprocessor runs before your compiler each time the compiler is invoked. The preprocessor translates
any line that begins with a pound symbol (#) into a special command, getting your code file ready for the
compiler.

Line 3 begins the actual program with a function named main(). Every C++ program has a main() function.
In general, a function is a block of code that performs one or more actions. Usually functions are invoked or
called by other functions, but main() is special. When your program starts, main() is called automatically.

main(), like all functions, must state what kind of value it will return. The return value type for main() in
HELLO.CPP is int, which means that this function will return an integer value.

All functions begin with an opening brace ({) and end with a closing brace (}). The braces for the main()
function are on lines 4 and 7. Everything between the opening and closing braces is considered a part of the
function.

The meat and potatoes of this program is on line 5. The object cout is used to print a message to the screen.
cout is used in C++ to print strings and values to the screen. A string is just a set of characters.

Here's how cout is used: type the word cout, followed by the output redirection operator (<<). Whatever
follows the output redirection operator is written to the screen. If you want a string of characters written, be
sure to enclose them in double quotes ("), as shown on line 5. A text string is a series of printable characters.

9 Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 9


Fundamentals of Programming in C++ - CH 1 2021

The final two characters, \n, tell cout to put a new line after the words Hello World! All ANSI-compliant
programs declare main() to return an int. This value is "returned" to the operating system when your program
completes. Some programmers signal an error by returning the value 1.

The main() function ends on line 7 with the closing brace.

Any C++ program file should be saved with file name extension “ .CPP ”
Type the program directly into the editor, and save the file as hello.cpp, compile it and then run
it. It will print the words Hello World! on the computer screen.
The end of a single statement ends with semicolon (;).

2.3. Compilation process of C++ programs


When you write a c++ program, the next step is to compile the program before running it. The compilation is
the process which convert the program written in human readable language like C, C++ etc into a machine
code, directly understood by the Central Processing Unit. There are many stages involved in creating a
executable file from the source file. The stages include Preprocessing, Compiling and Linking in C++. This
means that even if the program gets compiled, it may result in not running as errors may arise during the
linking phase. Hence most IDE (Integrated Development Environment ) like Eclipse, Geany etc consider the
term build for transforming source code file to an executable file.
Now, how you compile a certain program, that depends upon operating system and compiler. These days
compilers are run from IDE (Integrated Development Environment) that contains building and analysis tools.
You just have to click the menu to compile the program and then execute it. But actually the whole process
occurs in different phases. That is where compiling and linking in C++ comes.
Preprocessing
In this phase the preprocessor changes the progr Preprocessingam according to the directives mentioned (that
starts with # sign). The C++ preprocessor takes the program and deals with the # include directives and the
resulting program is pure c++ program. For example, in c++ program #include<iostream> will tell the
preprocessor to read all the contents of the iostream header file and include the contents into the program and
generate the separate C++ program file. C++ supports many preprocessor directives like #include, #define,
#if, #else etc.

10 Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 10


Fundamentals of Programming in C++ - CH 1 2021

Compilation

This phase translates the program into a low level assembly level code. The compiler takes the preprocessed
file (without any directives) and generates an object file. Now, the object file created is in the binary form. In
the object file created, each line describes one low level machine level instruction.

Hence, the compilation phase generates the relocatable object program and this program can be used in
different places without have to compile again. But you still can’t run these object files until to convert them
into executable file, now here linker comes into play, which links all the object files to generate single
executable file

Linking
Linking as the name suggests, refers to creation of a single executable file from multiple object files. The file
created after linking is ready to be loaded into memory and executed by the system. There is difference in
linking and compilation when it comes to understanding errors. Compiler shows errors in syntax,
For example, semi-colon not mentioned, data type not defined etc but if there is an error that function has been
defined multiple times, then this error is from linker as it indicating that two or more source code files have the same
meaning and that is leading to an error.

2.4. Input/output in C++


✓ cout is an object used for printing data to the screen.
✓ To print a value to the screen, write the word cout, followed by the insertion operator also called
output redirection operator (<<) and the object to be printed on the screen.
Syntax: cout << Object;
✓ The object at the right hand side can be:
✓ A literal string: “Hello World”
✓ A variable: a place holder in memory
✓ cin is an object used for taking input from the keyboard.
✓ To take input from the keyboard, write the word cin, followed by the input redirection operator
(>>) and the object name to hold the input value.

11 Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 11


Fundamentals of Programming in C++ - CH 1 2021

✓ Syntax: cin >> Object;


✓ cin will take value from the keyboard and store it in the memory. Thus the cin statement needs
a variable which is a reserved memory place holder.
E.g.: cin >>var1>>var2>>var3;
Here t h r e e d i f f e r e n t v a l u e s will be entered for the three variables. The input should
be separated by a space, tan or newline for each variable.
cout<<var1<<”, “<<var2<<” and “<<var3;
Here the values of the three variables will be printed where there is a “,” (comma) between the first
and the second variables and the “and” word between the second and the third.
2.5. Comment in C++
A comment is a piece of descriptive text which explains some aspect of a program. Program comments
are text totally ignored by the compiler and are only intended to inform the reader how the source code is
working at any particular point in the program.
C++ provides two types of comment delimiters:
1) Single Line Comment: Anything after // {double forward slash} (until the end of the line on which it
appears) is considered a comment.
Eg: cout<<var1; //this line prints the value of var1

2) Multiple Line Comment: Anything enclosed by the pair /* and*/ is considered a comment.
Eg: /* this is a kind of comment where Multiple lines can be enclosed in one
prograsm */
✓ Comments should be used to enhance (not to hinder) the readability of a program. The following two
points, in particular, should be noted:
✓ A comment should be easier to read and understand than the code which it tries to explain. A
confusing or unnecessarily- complex comment is worse than no comment at all.Over-use of
comments can lead to even less readability. A program which contains so much comment that
you can hardly see the code can by no means be considered readable.
✓ Use of descriptive names for variables and other entities in a program, and proper indentation of
the code can reduce the need for using comments.

12 Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 12


Fundamentals of Programming in C++ - CH 1 2021

Mettu University
Collage of Engineering and technology

Worksheet 2
Course Title: Fundamentals of Programming
Course code CoSc 1013

For each of the problems write a C++ code to perform the required task. Your program should be
based on the flow chart you drawn in the first worksheet.

1) Receive a number and determine whether it is odd or even.


2) Obtain two numbers from the keyboard, and determine and display which (if either) is the
larger of the two numbers.
3) Receive 3 numbers and display them in ascending order from smallest to largest
4) Add the numbers from 1 to 100 and display the sum
5) Add the even numbers between 0 and any positive integer number given by the user.
6) Find the average of two numbers given by the user.
7) Find the average, maximum, minimum, and sum of three numbers given by the user.
8) Find the area of a circle where the radius is provided by the user.
9) Swap the contents of two variables using a third variable.
10) Swap the content of two variables without using a third variable.
11) Read a n i n t e g e r value from the keyboard and display a message indicating if this
number is odd or even.
12) read 10 integers from the keyboard in the range 0 - 100, and count how many of them are
larger than 50, and display this result

13 Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 13


Fundamentals of Programming in C++ - CH 1 2021

14 Compiled by: Dejene B. Dept. Computer Science, 2nd year Page 14

You might also like