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

Fundamental of Programming I

The document provides an overview of C++ programming fundamentals, including its history, the difference between procedural and object-oriented programming, and the structure of a C++ program. It details the compilation process, including preprocessing, compilation, assembling, and linking, as well as the role of the preprocessor and directives like #include and #define. Additionally, it presents simple C++ programs demonstrating basic operations such as addition, checking even/odd numbers, swapping values, and finding the largest number among three inputs.

Uploaded by

sirabetegbar12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Fundamental of Programming I

The document provides an overview of C++ programming fundamentals, including its history, the difference between procedural and object-oriented programming, and the structure of a C++ program. It details the compilation process, including preprocessing, compilation, assembling, and linking, as well as the role of the preprocessor and directives like #include and #define. Additionally, it presents simple C++ programs demonstrating basic operations such as addition, checking even/odd numbers, swapping values, and finding the largest number among three inputs.

Uploaded by

sirabetegbar12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Unit two:-fundamentals of c++ programming

C++ was developed by Bjarne Stroustrup at Bell Laboratories over a period starting in
1979. Since C++ is an attempt to add object-oriented features (plus other improvements) to C,
earlier it was called as “C with Objects”. As the language developed, Stroustrup named it as C++
in 1983.
Procedural and object oriented programming
Procedural Programming
Procedural programming uses a list of instructions to tell the computer what to do step-by-
step. Procedural programming relies on - you guessed it - procedures, also known as routines or
subroutines. A procedure contains a series of computational steps to be carried out. Procedural
programming is also referred to as imperative programming. Procedural programming languages
are also known as top-down languages.
Procedural programming is intuitive in the sense that it is very similar to how you would expect
a program to work. If you want a computer to do something, you should provide step-by-step
instructions on how to do it. It is, therefore, no surprise that most of the early programming
languages are all procedural. Examples of procedural languages include Fortran, COBOL and C,
which have been around since the 1960s and 70s.
Object-Oriented Programming
Object-oriented programming, or OOP, is an approach to problem-solving where all
computations are carried out using objects. An object is a component of a program that knows
how to perform certain actions and how to interact with other elements of the program. Objects
are the basic units of object-oriented programming. A simple example of an object would be a
person. Logically, you would expect a person to have a name. This would be considered a
property of the person. You would also expect a person to be able to do something, such as
walking. This would be considered a method of the person.
A method in object-oriented programming is like a procedure in procedural programming. The
key difference here is that the method is part of an object. In object-oriented programming, you
organize your code by creating objects, and then you can give those objects properties and you
can make them do certain things.
A key aspect of object-oriented programming is the use of classes. A class is a blueprint of an
object. You can think of a class as a concept and the object as the embodiment of that concept.
What is the basic structure of a C++ program?
Structure of a C++ program
A C++ program is structured in a specific and particular manner. In C++, a program is divided
into the following three sections:
1. Standard Libraries Section
2. Main Function Section
3. Function Body Section
For example, let’s look at the implementation of the Hello World program:
4. #include <iostream>
5. using namespace std;
6.
7. int main() {
8. cout << "Hello World!" << endl;
9. return 0;

Standard libraries section


1
2
#include <iostream>
using namespace std;

 #include is a specific preprocessor command that effectively copies and pastes the entire
text of the file, specified between the angle brackets, into the source code.
 The file <iostream>, which is a standard file that should come with the C++ compiler, is
short for input-output streams. This command contains code for displaying and getting
an input from the user.
 namespace is a prefix that is applied to all the names in a certain set.
 iostream file defines two names used in this program - cout and endl.
 This code is saying: Use the cout and endl tools from the std toolbox.
Main function section
1
int main() {}

 The starting point of all C++ programs is the main function.


 This function is called by the operating system when your
program is executed by the computer.
 { signifies the start of a block of code, and } signifies the end.
Function body section
1
2
cout << "Hello World" << endl;
return 0;

 The name cout is short for character output and displays


whatever is between the << brackets.
 Symbols such as << can also behave like functions and are
used with the keyword cout.

 The return keyword tells the program to return a value to the


function int main

 After the return statement, execution control returns to the


operating system component that launched this program.
 Execution of the code terminates here.
Compilation process of c++
When you develop a C++ program, the next step is to compile the program before running it.
The compilation is the process which converts the program written in human readable language
like C, C++ etc into a machine code, directly understood by the Central Processing Unit. For
example, if you have a C++ source code file named prog.cpp and you execute the compile
command,
g++ -Wall -ansi -o prog prog.cpp
There are 4 main stages involved in creating an executable file from the source file.
1. The C++ the preprocessor takes a C++ source code file and deals with the
headers(#include), macros(#define) and other preprocessor directives.
2. The expanded C++ source code file produced by the C++ preprocessor is compiled into
the assembly language for the platform.
3. The assembler code generated by the compiler is assembled into the object code for the
platform.
4. The object code file produced by the assembler is linked together
with the object code files for any library functions used to produce either a library or an
executable file.
Preprocessing
The preprocessor handles the preprocessor directives, like #include and #define. It is agnostic of
the syntax of C++, which is why it must be used with care.
It works on one C++ source file at a time by replacing #include directives with the content of the
respective files (which is usually just declarations), doing replacement of macros (#define), and
selecting different portions of text depending of #if, #ifdef and #ifndef directives.
The preprocessor works on a stream of preprocessing tokens. Macro substitution is defined as
replacing tokens with other tokens (the operator ## enables merging two tokens when it make
sense).
After all this, the preprocessor produces a single output that is a stream of tokens resulting from
the transformations described above. It also adds some special markers that tell the compiler
where each line came from so that it can use those to produce sensible error messages.
Some errors can be produced at this stage with clever use of the #if and #error directives.
By using below compiler flag, we can stop the process at preprocessing stage.
g++ -E prog.cpp
Compilation
The compilation step is performed on each output of the preprocessor. The compiler parses the
pure C++ source code (now without any preprocessor directives) and converts it into assembly
code. Then invokes underlying back-end(assembler in toolchain) that assembles that code into
machine code producing actual binary file in some format(ELF, COFF, a.out, ...). This object file
contains the compiled code (in binary form) of the symbols defined in the input. Symbols in
object files are referred to by name.
Object files can refer to symbols that are not defined. This is the case when you use a
declaration, and don't provide a definition for it. The compiler doesn't mind this, and will happily
produce the object file as long as the source code is well-formed.
Compilers usually let you stop compilation at this point. This is very useful because with it you
can compile each source code file separately. The advantage this provides is that you don't need
to recompile everything if you only change a single file.
The produced object files can be put in special archives called static libraries, for easier reusing
later on.
It's at this stage that "regular" compiler errors, like syntax errors or failed overload resolution
errors are reported.
In order to stop the process after the compile step, we can use the -S option:
g++ -Wall -ansi -S prog.cpp
Assembling
The assembler creates object code. On a UNIX system you may see files with a .o suffix (.OBJ
on MSDOS) to indicate object code files. In this phase the assembler converts those object files
from assembly code into machine level instructions and the file created is a relocatable object
code. Hence, the compilation phase generates the relocatable object program and this program
can be used in different places without having to compile again.
To stop the process after the assembly step, you can use the -c option:
g++ -Wall -ansi -c prog.cpp
Linking
The linker is what produces the final compilation output from the object files the assembler
produced. This output can be either a shared (or dynamic) library (and while the name is similar,
they don't have much in common with static libraries mentioned earlier) or an executable.
It links all the object files by replacing the references to undefined symbols with the correct
addresses. Each of these symbols can be defined in other object files or in libraries. If they are
defined in libraries other than the standard library, you need to tell the linker about them.
At this stage the most common errors are missing definitions or duplicate definitions. The former
means that either the definitions don't exist (i.e. they are not written), or that the object files or
libraries where they reside were not given to the linker. The latter is obvious: the same symbol
was defined in two different object files or libraries.

C++ compiler operation


The process of translating C++ source code into an executable program is called "compiling the
program" or just "compiling." We usually view the compilation process as a single action and
generally refer to it as such. Nevertheless, a modern C++ compiler consists of at least three
separate programs:
Most of the time, we refer to all three programs collectively as "the compiler." Whenever we say
"the compiler," context is usually sufficient to clarify if we are talking specifically about the
middle component or all three components together. If the context is not enough, then we must
explicitly clarify our meaning to avoid any confusion.
A modern integrated development environments (IDE) such as Visual Studio bundle the
preprocessor, compiler, and linker together so they work as a single unit and are operated
through a single, common interface. Programmers initiate the compilation process with a single
command (typically a single button press or menu item). Modern IDEs also include many
additional tools:
 a graphical user interface,
 a text editor for writing and editing source code,
 a dynamic syntax checker that detects syntax errors while you write code,
 a debugger to help locate logical and runtime errors,
 and a profiler to measure how much time the computer spends in each function.
Although these features are controlled through the common interface, most are implemented as
separate programs.

The Preprocessor
The preprocessor handles statements or lines of code that begin with the "#" character, which are
called "preprocessor directives." Note that directives are not C++ statements (and therefore do
not end with a semicolon) but rather instruct the preprocessor to carry out some action. The
preprocessor reads and processes each file one at a time from top to bottom. It does not change
the contents of any of the files that it processes but creates a temporary file that contains the
processed code. The compiler component reads and translates the temporary file from C++ to
machine code. When the compiler component finishes processing the code in the temporary file,
it removes the file. Two of the most common directives, and the first that we will use,
are #include and #define.

The #include Directive


The #include directive consists of two parts, all on the same line and separated by at least one
space:
1. #include
2. the name of a file (usually a header file)
When the preprocessor encounters the #include directive, it opens the header file and copies the
contents into the temporary file. The symbols surrounding the name of the header file are
important and determine where the preprocessor looks for the file.
<name>
The angle brackets denote a system include file that is part of the compiler itself (think of it
as "library" code) and directs the preprocessor to search for the file wherever the system
header files are located (which varies from one compiler to another and from one
operating system to another).
"name.h"
The double quotation marks identify a header file that is written as a part of a program. The
quotation marks instruct the preprocessor to look for the header file in the current
directory (i.e., in the same directory as the C++ source code). Header files that a
programmer writes as part of an application program typically end with a .h extension.
You might see two kinds of system header files in a C++ program. Older system header files end
with a ".h" extension: <name.h>. These header files were originally created for C programs, but
may also be used with C++. Newer system header files do not end with an extension: <name>,
may only be used with C++.
#include <iostream>
#include "person.h"
Example directives. File names appearing between < and > refer to system header files; file
name appearing between an opening and closing " refer to header files written by the
programmer as a part of the program.
Note
The include directive does not end with a semicolon and there must be at least one space
between the directive and the file name.

The #define Directive and Symbolic Constants


The #define directive introduces a programming construct called a macro. A simple macro only
replaces one string of characters with another string. We'll look at more complex, parameterized
macros in chapter 6. The #define directive is one (old) way of creating a symbolic constant (also
known as a named or manifest constant). The const and enum keywords are newer techniques
for creating constants, and are presented in more detail later. It is a well-accepted naming
practice to write the names of symbolic constants with all upper-case characters (this provides a
visual clue that the name represents a constant).

A simple c++ program


1. Adding to numbers in C++.
Ans. Take two variables and take user input and add them.
2. #include <iostream> 7. cin>>a>>b;
3. using namespace std; 8. cout<<a+b;
4. int main() { 9. return 0;
5. int a ; 10. }
6. int b ;
Input: 2 5
Output: 7
1. Check if a number is even or odd.
Ans. If the given number is divisible by 2 then it is even otherwise odd.
2. #include <iostream> 7. if(a%2 == 0) // if remainder is zero then
3. using namespace std; even number
4. int main() { 8. cout<<”even”;
5. int a ; 9. else cout<<”odd”;
6. cin>>a; 10. return 0;
11. }
Input: 8
Output: even
1. Write a program to swap two numbers.
Ans. Use a temporary variable to store one of the numbers.
2. #include <iostream> 7. cout<<a<<" "<<b<<endl;
3. using namespace std; 8. int temp = a;
4. int main() { 9. a = b;
5. int a = 10; 10. b = temp;
6. int b = 20; 11. cout<<a<<" "<<b<<endl;
12. return 0; 13. }
Output: 10 20
20 10

1. Write a program to find the largest number among three numbers.


Ans. A number will be largest if number is greater than both the other numbers.
2. #include <iostream> 9. if(b >= a && b >= c)
3. using namespace std; 10. cout << "Largest number: " << b;
4. int main() { 11. if(c >= a && c >= b)
5. float a, b, c; 12. cout << "Largest number: " << c;
6. cin >> a >> b >> c; 13. return 0;
7. if(a >= b && a >= c) 14. }
8. cout << "Largest number: " << a;
Input: 1 2 3
Largest number: 3

1. Find the sum of all the natural numbers from 1 to n.


Ans. We can do this using two ways, one is by iterating from 1 to n and adding them up while
the other way is using the summation formula –
2. summation of i from 1 to 9. for (int i = 1; i <= n; ++i) {
n=n(n+1)/2=1+2+3+4+..+(n-1)+n 10. sum += i;
3. #include <iostream> 11. }
4. using namespace std; 12. // or sum = n*(n+1)/2;
5. int main() 13. cout << sum;
6. { 14. return 0;
7. int n, sum = 0; 15. }
8. cin >> n;
Input: 5
Output: 15
Input/output in C++
C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of data. It
makes the performance fast.
If bytes flow from main memory to device like printer, display screen, or a network connection,
etc, this is called as output operation.
If bytes flow from device like printer, display screen, or a network connection, etc to main
memory, this is called as input operation.
Header Function and Description
File

<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard output stream
standard input stream and standard error stream, respectively.

<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision and setw

<fstream> It is used to declare services for user-controlled file processing.

Standard output stream (cout)


The cout is a predefined object of ostream class. It is connected with the standard output device,
which is usually a display screen. The cout is used in conjunction with stream insertion operator
(<<) to display the output on a console

Let's see the simple example of standard output stream (cout):


1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. char ary[] = "Welcome to C++ tutorial";
5. cout << "Value of ary is: " << ary << endl;
6. }
Output:
Value of ary is: Welcome to C++ tutorial

Standard input stream (cin)


The cin is a predefined object of istream class. It is connected with the standard input device,
which is usually a keyboard. The cin is used in conjunction with stream extraction operator (>>)
to read the input from a console.
Let's see the simple example of standard input stream (cin):
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. int age;
5. cout << "Enter your age: ";
6. cin >> age;
7. cout << "Your age is: " << age << endl;
8. }

Output:

Enter your age: 22


Your age is: 22

Standard end line (endl)


The endl is a predefined object of ostream class. It is used to insert a new line characters and
flushes the stream.
Let's see the simple example of standard end line (endl):
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. cout << "C++ Tutorial";
5. cout << " Javatpoint"<<endl;
6. cout << "End of line"<<endl;
7. }

Output:

C++ Tutorial Javatpoint


End of line

Comments in C++
C++ Comments

The C++ comments are statements that are not executed by the compiler. The comments in C++
programming can be used to provide explanation of the code, variable, method or class. By the
help of comments, you can hide the program code also.
There are two types of comments in C++.
o Single Line comment
o Multi Line comment
C++ Single Line Comment
The single line comment starts with // (double slash).
Let's see an example of single line comment in C++.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x = 11; // x is a variable
6. cout<<x<<"\n";
7. }
Output:

11

C++ Multi Line Comment

and asterisk (/∗ ..... ∗/).


The C++ multi line comment is used to comment multiple lines of code. It is surrounded by slash

Let's see an example of multi line comment in C++.


1. #include <ostream>
2. using namespace std;
3. int main()
4. {
5. /* declare and
6. print variable in C++. */
7. int x = 35;
8. cout<<x<<"\n";
9. }
Output:

35

Unit three: - Constants, Variables, Data Types and Operators


C++ tokens
Cc+++hdgjcvsdyssdhdsgcvdsgcdf+ Compiler
Operation

C++C++ Compiler Operation


Compiler Operation

You might also like