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

Introduction To C Part 1

Here are some examples of variable declarations in C++: int age; // declares an integer variable called age double gpa = 3.4; // declares a double variable called gpa and initializes it to 3.4 string name; // declares a string variable called name char grade = 'A'; // declares a char variable called grade and initializes it to 'A' The data types int, double, string and char declare variables of different types that can store different kinds of data like integers, floating point numbers, text and single characters. Variables must be declared before they are used and can be initialized during declaration.

Uploaded by

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

Introduction To C Part 1

Here are some examples of variable declarations in C++: int age; // declares an integer variable called age double gpa = 3.4; // declares a double variable called gpa and initializes it to 3.4 string name; // declares a string variable called name char grade = 'A'; // declares a char variable called grade and initializes it to 'A' The data types int, double, string and char declare variables of different types that can store different kinds of data like integers, floating point numbers, text and single characters. Variables must be declared before they are used and can be initialized during declaration.

Uploaded by

Yousef Aldrisi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

INTRODUCTION TO PROGRAMMING WITH C++

BY/ MOHAMED HASHEM


SESSION RULES

Don’t forget:

★ ***** You have to study the previous session before the next session *****
★ It’s better to show your face and open camera.
★ Raise your hand if you want to ask a questions.
★ Stick with discussion time and don’t interrupt the session there is a time for Q / A after every topic
★ Attending sessions is not optional and it’s a part of your graduation
★ You have to attend with PC or Laptop, Phones are not allowed anymore.
WHAT IS PROGRAMMING ?
• You have to talk with it by a language it can understand ,and computers understand only (0,1) language .

• Programming language is high level language that can executed by machine by convert it to machine code, which is compiles by
computers into (0,1) to understand our instructions .

• Programming means writing instructions for a computer to perform desired actions by programmer.

• A programmer is a person who gives a computer instructions to perform these actions.

• The instructions are written in some programming language that the computer understands.

• A programming language is a language that a computer understands. And it is an intermediary between a computer and a programmer.

• Programming languages provide the rules for building websites, apps, and other computer-based technologies. 

• All the programming languages share a common goal—to be able to control the behavior and output of a computer.

• Programming languages are roughly categorized into two groups

- Low-level programming languages.

- High-level programming languages.

• Low-level programming languages means that the language is close to machine code. This makes it highly efficient. But this also
makes it hard for us developers to understand, debug, and maintain.

• High-level programming languages tend to be more “English-like” languages so that are easier to learn
SESSION 1 OUTLINE
• Very brief history of C++
• Definition object-oriented programming
• Why C++ is a good choice
• Install CodeBlocks IDE
• First program!
• Some C++ syntax
• Variables
• Operators ( Assignment – Arithmetic – Increment/Decrement – Relational – Logical )
• IF / Else Statements
• Casting
• Error ( Syntax – Run time – Logic )
• Exercises
VERY BRIEF HISTORY OF C++

Simu
la 67

C++
WHY AND WHEN TO CHOOSE C++

• Despite its many competitors C++ has remained popular • Choose C++ when:
for ~30 years and will continue to be so in the • Program performance matters
foreseeable future. • Dealing with large amounts of data, multiple CPUs,
complex algorithms, etc.
• Why?
• Complex problems and programs can be effectively • The programming language itself can help organize
implemented your code
• Memory Mangement • Ex. In C++ your objects can closely model elements of
your problem
• No other language quite matches C++’s combination of
performance, expressiveness, and ability to handle • Access to libraries
complex programs. • Ex. Nvidia’s CUDA Thrust library for GPUs
• Multi paradigm language (Functional - OOP)
OBJECT-ORIENTED PROGRAMMING

• The principal of data hiding helps the programmer to build secure programs that cannot be invaded by code in
other part of the program.
• It is easy to partition the work in a project, based on objects.
• This is a highly effective way of modeling real world problems inside of a computer program.
• Object oriented systems can be easily upgraded from small to large systems.
• Through inheritance, we can eliminate redundant code and extend the use of existing classes.
• Software complexity can be easily managed.
• This is a highly effective way of modeling real world problems inside of a computer program.
OBJECT-ORIENTED PROGRAMMING
“Class Car”

public interface

private data and methods


CODEBLOCKS

• In this tutorial we will use the CodeBlocks integrated development environment (IDE) for writing
and compiling C++
• About C::B
• cross-platform: supported on Mac OSX, Linux, and Windows
• Oriented towards C, C++, and Fortran, supports others such as Python
• Short learning curve compared with other IDEs such as Eclipse or Visual Studio

• Has its own automated code building system, so we can concentrate on C++
• Project homepage: https://bit.ly/Codeblocks-Setup
OPENING C::B

• The 1st time it is opened C::B will search for compilers it can use.
• A dialog that looks like this will open. Select GCC if there are multiple options:

• And click OK.


OPENING C::B AND CREATING A 1ST C++

PROJECT…
Step 1. Create a project from the File menu or the Start Here tab:
• Step 2. Choose the Console category and then the Console application and click Go.
• Step 3: Click Next on the “Welcome to the new console application wizard!” screen.
• Step 4: Choose C++!
• …then click Next.
• Step 5. Enter a project title. Let C::B fill in the other fields for you. If you like you can change the
default folder to hold the project. Click Next.
• Step 6: Choose the compiler. For this tutorial, choose GNU GCC as the compiler. Click Next.
• Step 8: Your project is now created! Click on Sources in the left column, then double-click
main.cpp.
• Click the icon in the toolbar or press F9 to compile and run the program.
HELLO, WORLD!
• Console window:

• Build and compile messages


HELLO, WORLD!  loads a header file to provide basic input and output
services.
EXPLAINED  Loads a namespace called std. Namespaces are used to
separate sections of code for programmer convenience to
save the name clash.
 Comments are marked for a single line with a // or for
multiples with a pair of /* and */
 The main routine – the start of every C++ program! It
returns an integer value to the operating system and (in
this case) takes no arguments: main()
 Curly braces are used to denote a code block (like the
main() function): { … some code … }
 Each command line end with a semicolon.
 endl and ‘\n’ are used to make a newline.
 << is the C++ insertion operator. It is used to pass
 The return statement returns an integer characters from the right to the object on the left.
value to the operating system after  cout is the object that writes to the stdout device, i.e. the
completion. 0 means “no error”. console window.
 It works as indicate that the program ended
successfully.
OUTPUT (COUT)

• The  “cout “ object is used to display the output to the user screen.
Examples /
• Create a program to print your name.
• Create a program to print:
“Hello
World!“
BUILT-IN (PRIMITIVE) TYPES
• “primitive” means these types are not objects

• Primitive data type is the data type that allows you to store only single
value and always starts with a lowercase letter.

• Here are the most commonly used types 

• Named constants are declared for constant and fixed values which are
referenced by :
• const int MAXITEMS = 100;
• const string NAME = "Fred Flintstone";
• const double PI = 3.141592654;
• const char NEWLINE = '\n’;

• Constants must be initialized in their declaration, and can’t be assigned a


value later.
VARIABLES
Variable : is a container store data inside it.
Variable declarations:
• Variable is a location in memory, referenced by name and data type.
• C++ requires that all variables be declared before they are used.
• Every variable has a name, type, size, value and address.
• Memory cannot be "empty", it always stores a random value (garbage value) so using the value of a variable that
has not yet been Initialization is one of the most common logic errors in programs.
• it is good practice to always give every newly declared variable a specific initial value.
• Can contain (letters, numbers , _underscore).
• Must begin with a letter or underscore (not a number). int Weight = 0,
Height = 0,
• Can not redefine a name in the same scope. Length = 0;
• Can not use C++ keywords.
double Average = 0.0,
• C++ is a case sensitive language. GPA = 0.0;
Basic declaration syntax is: string Major;
data type variable_name; Major = "Computer Science";
C++ RESERVED WORDS

The C++ Standard specifies certain symbols and words as the official "vocabulary" of the C++ language.

These reserved words (and symbols) are preempted by the C++ language definition and may only be used in
the manner the language rules specify.

Fortunately the number of reserved words is relatively small (< 300). Here's a sample:

bool const double for return


break continue else if struct
case default enum int switch
char delete false long typedef
class do float new while
INPUT (CIN)

• The ”cin” object is used to take input from user’s keyboard


• Examples /
• Create a program to take your first name and save it into variable it and print (“My Name is “ + your name)
• Create a program to take two number from user and print their SUM.
TYPE CASTING

• C++ is strongly typed. It will auto-convert a variable of one type to another in a limited
fashion: if it will not change the value.

short x = 1 ;
int y = x ; // OK
short z = y ; // NO!

• Conversions that don’t change value: increasing precision (float  double) or integer
 floating point of at least the same precision.
• C++ allows casting with the syntax: (new type) expression
double x = 1.0 ;
int y = (int) x ;
float z = (float) (x / y) ;
BEHIND THE SCENES: THE COMPILATION
PROCESS
STEP 1: PREPROCESSOR CONVERTS SOURCE
CODE TO EXPANDED CODE

When you run the program, the source code is first sent to the tool known as Preprocessor. Preprocessors
basically do two things:
• It removes the comments, black lines and white spaces from the program.
• It expands the Preprocessor directives such as macros or file inclusion.
• It finally converts the source code to  expanded code.
• Basically, the source code first-program.cpp is converted to  first-program.i which contains the expanded code.
STEP 2: COMPILER CONVERTS THE EXPANDED
CODE TO ASSEMBLY CODE.

The compiler does two things:


• It checks the program for syntax errors.
• If no error is found, it converts the expanded code to assembly code.
• Basically, the expanded code first-program.i is converted to first-program.s 
which contains the assembly code.
STEP 3: ASSEMBLER CONVERTS THE ASSEMBLY
CODE TO OBJECT CODE.

The tool known as Assembler converts the Assembly code into Object code.


• Object code is also known as bytecode or binary code or machine-level code which is
understandable by the computer.
• Basically, the assembly code first-program.s is converted to first-program.obj
which contains the machine code.
STEP 4: LINKER CONVERTS THE OBJECT CODE
TO EXECUTABLE CODE.

• The tool known as Linker converts the Object code to Executable code


• Basically, the machine code first-program.obj is converted to first-program.exe
which contains the executable code.
STEP 5: FINALLY, THE LOADER LOADS THE
EXECUTABLE FILE INTO MEMORY.

• In this last step, the Loader loads the executable file into memory and the program starts to
run in an executable environment.

• A few important takeaways:


• As a programmer, we can only understand the file content of Source code and expanded code.
• But you cannot directly understand the file content of Assembly code, Object code, and Executable
code. They are understandable by computers or some special software since they contain machine-
level code.
OPERATORS

• Assignment Operators
• Arithmetic Operators
• Compound assignment Operators

• Increment and decrement Operators


• Equality Operators
• Relational Operators
• Logical Operators
• Precedence Operators
ASSIGNMENT OPERATOR

• variable = value;
• The right hand side is stored in the left hand side.
• Left Hand Side = Right Hand Side
• Exercise
• Swap two variable using third variable
ARITHMETIC OPERATORS

Quick Quiz : what will be the printed


results.
EXERCISES

• Write a program to input number of five digits and print every digit separately in new line.
• Write a program that asks user to enter two numbers and print the Sum, Product, Difference, Division,
Modules, Quotient of the two number.
• Write a program in C++ to find the Area and Perimeter of a Rectangle.
•  Write a program in C++ to find the area and circumference of a circle.
• (Advanced) Swap two variable without using third variable.
REFRESH YOUR MIND

• Write program that reads an integer and prints the sum of it’s last 3 digits.
• Write Program to print
*
**
***
****
*****
COMPOUND ASSIGNMENT OPERATOR
INCREMENT AND DECREMENT
OPERATORS

Quick Quiz : what will be the


printed results
IF STATEMENT

● Controls the flow of your program.


● Syntax:

if (Boolean expression) {
//code to be executed
}
● If condition is true then execute statements.
● If condition is false then skip statements.
● You can ignore {} if you write only one statement.
EQUALITY OPERATORS
RELATIONAL OPERATORS
ELSE IF

• If else Statement
• If expression is true then execute statement 1
• If expression is false then execute statement 2

11/13/2022 41
EXERCISES

• Write program to take number print positive or negative.


• Write program to take two number and print max between them.
• Write program to take number then print even or odd.
ELSE IF ELSE STATEMENT

• If expression 1 is true then execute only statement 1


• If expression 1 is false and expression 2 is true then
execute statement 2
• If expression 1 and 2 are false then execute statement 3
EXAMPLE

44
INTRODUCTION TO LOGICAL OPERATOR

● What if we had multiple Boolean expressions that we want to check?


● What if we wanted to check the opposite result of some Boolean expression?
LOGICAL OPERATOR

• Let x = 5 , y = 2 , z = 5
HELP THE EMPLOYEE, ONE LAST TIME...
Given the Employee’s accuracy.

● Print “Excellent” if they were >= 85.

● Print “Very Good” if they were >= 75.

● Print “Good” if they were >= 65.

● Print “Passed” if they were >= 50.

● Otherwise, print “Failed”.


PRECEDENCE OPERATOR

C++ Operator Precedence


ERRORS
• Syntax Errors
Errors that occur when you violate the rules of writing C/C++ syntax and the compiler will complain and refuse
to compile the file as
• Missing Parenthesis (})
• Printing the value of variable without declaring it
• Missing semicolon like this ;
• Run-Time Errors
Errors which occur during program execution (run-time) as
• division by zero
• Logical Errors
• if the syntax and other factors are correct, we may not get the desired results due to logical issues.
• These errors solely depend on the logical thinking of the programmer and are easy to detect if we follow the
line of execution and determine why the program takes that path of execution. 
EXERCISES
• Write program to take 2 integers and char like(+,-,*,/) then print the result.
• Write program to take char from user then print if it capital or not (use ASCII Code).

• Two employees gave you their first letter in their names, and you should print the bigger between them.
• We have an employee that we need to create an ID to him, the ID format is “F\MM\YY”;
Input: E 6 1986  Output: E\06\86
NICE TO SEARCH NEXT SESSION

• Nested If
• Ternary operator
• switch case

Advanced
• Write program to sum number from 1 to N without for loop.

• Write Program to find remainder between two numbers without using % operator.

You might also like