Вы находитесь на странице: 1из 40

C++ Basics, Constructs and Loops

Computer Programming (Object Oriented Programming)


CSN104
Dr. Bjarne Stroustrup

C++ is designed to allow you to express ideas,


but if you don't have ideas or don't have any clue
about how to express them, C++ doesn't offer
much help.

Design and programming are human activities; forget that and all is
lost.
COMPILATION PROCESS
C++ TOKENS

A token is the smallest element of a program that is meaningful to the compiler.


Keywords
Keywords are pre-defined or reserved words in a programming language.
Identifiers
•Identifiers are used for naming of variables, functions and arrays.
•These are user defined names consisting of sequence of letters and digits
with either a letter or the underscore(_) as a first character.

RULES
•They must begin with a letter or underscore(_).
•They must consist of only letters, digits, or underscore.
•No other special character is allowed.
•It should not be a keyword.
•It must not contain white space.
•It should be up to 31 characters long as only first 31 characters are significant.
NAME VALID OR INVALID IDENTIFIER??
_A9 Valid
Temp.var Invalid as it contains special character other than the underscore
void Invalid as it is a keyword

C++ program:
int main()
{
int a = 10;
return 0;
}

In the above program there are 2 identifiers:


1) main: function name
2) a: variable name.
C++ Data Types

• Data types are used to tell the variables the type of data it can store.
• Whenever a variable is defined in C++, the compiler allocates some
memory for that variable based on the data-type with which it is
declared. Every data type requires different amount of memory.
• Data types in C++ is mainly divided into two types: Primitive Data
Types and Abstract/User-Defined Data Types
• Abstract /User defined data typesà Classes
Primitive Data Types
These data types are built-in or predefined data types and can be used directly by the user
to declare variables.

• Integer (int) – 4 bytes


• Character (char) – one byte
• Boolean (bool)- one byte
• Floating Point (float) – 4 bytes - storing single precision floating point
values
• Double Floating Point (double) - storing double precision floating point
values
• Valueless or Void (void) -used for those function which does not return a
value.
• Wide Character(wchar_t) – 2 or 4 bytes long
Datatype Modifiers:

These are used with the built-in data types to modify the length of
data that a particular data type can hold.
• Signed
• Unsigned
• Short
• Long
We can display the size of all the data types by using the sizeof()
operator and passing the keyword of the datatype as argument to this
operator as shown below:
Using char datatype
#include //for cout, etc.
using namespace std;
int main()
{
char charvar1 = ‘A’; //define char variable as character
char charvar2 = ‘\t’; //define char variable as tab
cout << charvar1; //display character
cout << charvar2; //display character
charvar1 = ‘B’; //set char variable to char constant
cout << charvar1; //display character
cout << ‘\n’; //display newline character
return 0;
}
Constants
Constants are also like normal variables. But, only difference is, their values
can not be modified by the program once they are defined.

const data_type variable_name;


Example: const int x=10;

Types of Constants:
Integer constants – Example: 0, 1, 1218, 12482
Floating point constants – Example: 0.0, 1203.03, 30486.184
Character constants -Example: ‘a’, ‘A’, ‘z’
String constants -Example: “PunjabEngineeringCollege”
Area of circle
Using # for MACROS
Macros are piece of code in a program which is given some name.
Whenever this name is encountered by the compiler the compiler replaces the
name with the actual piece of code. The ‘#define’ directive is used to define a
macro.
#define PI 3.14159
Macros with arguments:
We can also pass arguments to macros. Macros defined with arguments works
similarly as functions. Let us understand this with a program:
File inclusion using #
• #include< file_name > (for standard/header files)
• #include"filename” ( for user defined files)
Strings
Strings are nothing but an array of characters ended with a null character
(‘\0’).

Declarations for String:


char string[20] = {‘p’, ’e’, ‘c’, ‘\0’};

char string[20] = “pec”;

char string [] = “pec”;


Special Symbols
[] () {}, ; * = #

• Brackets[]
• Parentheses()
• Braces{}
• comma (,)
• semi colon (;)
• asterisk (*)
• assignment operator (=)
• pre processor(#)
Expressions
int n; // declaration
n = 1; // expression

int n = 5 + 100 + 32;


int factor = 3 + 2;
int principal = (100 / 20) + (50 / 5);
int total = factor * principal;
Programmers combine variables, constants and operators to
make expressions.
The if Statement
Example
NESTED IF
If else if ladder
Switch Case statement
The expression provided in the switch
should result in a constant
value otherwise it would not be valid.
Valid expressions for switch:
// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)

Invalid switch expressions for switch:


// Variable expression not allowed
switch(ab+cd)
switch(a+b+c)
SWITCH CASE is better for multi-
way branching and is executed
faster

IF ELSE is better for boolean


values
Loops
• There are three kinds of loops in C++: the for loop, the while loop, and
the do while loop.

Here’s the output:


0 1 4 9 16 25 36 49 64 81 100 121 144 169 196
Here’s another for loop example:

for(count=0; count<100; count++)


// loop body

How many times will the loop body be repeated here?

Exactly 100 times, with count going from 0 to 99.


The while Loop Sample Output
1
27
33
144
9
0
Do-while loop

The do-while loop is similar to the while


loop, except that the test condition occurs
at the end of the loop.

Having the test condition at the end,


guarantees that the body of the loop
always executes at least one time.
/*The following program fragment is an input routine that insists that the user type a correct
response -- in this case, a small case ‘y’ or capital case 'Y'. The do-while loop guarantees that the
body of the loop (the question) will always execute at least one time.*/

#include <iostream>
using namespace std;

int main()
{
char ans;
do
{
cout<<"Do you want to continue (Y/N)?\n";
cout<< "You must type a 'Y' or an 'N'.\n";
cin >> ans;
} while((ans =='Y')|| (ans =='y'));
}

/*the loop continues until the user enters the correct response*/

Вам также может понравиться