Vous êtes sur la page 1sur 12

(/search) 1 (/messages) (/users/navya-14/notifications)

(http://www.tcs.com)
Chapter 1: Introduction to C++ Basics

C++ - All Chapters (/communities/unix-c-oracle-lounge-0/course/c-0)


Home (/communities/unix-c-oracle-lounge-0) See Leaderboard (/communities/unix-c-oracle-lounge-0/aspire_dashboard)

Index
1.1.C++ Datatypes and Conditional Constructs (/communities/unix-c-oracle-lounge-0/content/c-datatypes-and-conditional-constructs)

1.2.C++ Iterations and Operations (/communities/unix-c-oracle-lounge-0/content/c-iterations-and-operations)

1.3.Pointers and Functions (/communities/unix-c-oracle-lounge-0/content/pointers-and-functions)

1.4.Good Programming Practises (/communities/unix-c-oracle-lounge-0/content/good-programming-practises)

1.5.User Defined Datatypes (/communities/unix-c-oracle-lounge-0/content/user-defined-datatypes)

1.6.Storage Classes (/communities/unix-c-oracle-lounge-0/content/storage-classes)

1.7.Exception Handling (/communities/unix-c-oracle-lounge-0/content/exception-handling-2)

1.8.Introduction to Data Structures (/communities/unix-c-oracle-lounge-0/content/introduction-to-data-structures)

1.9.Linked List, Stack and Queue (/communities/unix-c-oracle-lounge-0/content/linked-list-stack-and-queue)

Go to Doubts

1.1. C++ Datatypes and Conditional Constructs


C++ Datatypes
1.1 Objective
To understand what are Data types and their usage in programs.

1.2 Introduction
A datatype defines a set of values set of operations that can be performed on those values. The size of the field in which data can be stored.

Datatypes in C++ :

Primitive or Basic datatype


Derived datatypes
User defined data types

1.2.1 Primitive or Basic datatypes in C++

void data type in C++: The void data type has no values and no operations.
Integer data types in C++: An integer is a number without a fractional part.

C++ supports three different sizes of the integer data type.


The size of the integer data types are as shown in the table below:

Note: In C++ this size is machine dependent, hence there can be a variation.

Floating point datatypes in C++:


Floating point: A floating point type is a number with a fractional part, such as 43.32. C++ supports three different sizes of floating point numbers.

The size of the integer data types are as shown in the table below:

Character Datatype in C++: character type can hold an ASCII character .When initializing a constant or a variable of char type, or when changing the value of a
variable of char type, the value is enclosed in single quotation marks.

Variable Declarations

Constants and variables must be declared before they can be used.


A constant declaration specifies the type, the name and the value of the constant.
A variable declaration specifies the type, the name and possibly the initial value of the variable.
When you declare a constant or a variable, the compiler reserves a memory location in which to store the value of the constant or variable.
Associates the name of the constant or variable with the memory location. In the program this name is used for referring to the constant or variable.
Constants are used to store values that never change during the program execution.

Syntax for declaring a constant :


const <type> <identifier> = <expression>;
Examples:
const double US2HK = 7.8; //Exchange rate of US$ to HK$
Variables are used to store values that can be changed during the program execution. A variable is best thought of as a container for a value.

Syntax:
< type > < identifier >;
< type > < identifier > = < expression >;

Examples:
int sum;
int total = 3445;
char answer = 'y';
double temperature = -3.14;

Boolean Datatype: A boolean type, typically denoted "bool" or "boolean", is typically a logical type that can be either "true" or "false".In C++, boolean values may be
implicitly converted to integers, according to the mapping false 0 and true 1 .

Derived Datatype:These are the datatypes derived from primitive datatypes.


Array
Pointer - Please refer to the chapter - 1.3 Pointers and Functions
Reference - Please refer to the chapter - 1.3 Pointers and Functions

Array:

C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as Age1, Age2, ..., and Age5, you declare one array variable such as Age and use Age[0], Age[1], and ..., Age[5] to
represent individual variables. A specific element in an array is accessed by an index or subscript.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays:
To declare an array in C++, the specify the type of the elements and the number of elements as size required by an array :
Syntax: type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type.

For Ex: double balance[5];

The above code declare a 5-element array called balance of type double

Initializing an Array:
An array can be initialized along with declaration. For array initialization it is required to place the elements separated by commas enclosed within braces.
You can initialize C++ array elements either one by one as follows:

You can initialize C++ array elements using a single statement as follows:

The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ].

The above figure represent array balance with specific values.

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write:
The above code will create exactly the same array as you did in the previous example.

Accessing Array Elements


In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus being
able to both read and modify its value. This is done by placing the index of the element within square brackets after the name of the array. For example:

The above statement will take 5th element from the array and assign the value to salary variable.
Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays:

This program makes use of setw() function to format the output. When the above code is compiled and executed, it produces the following result:

Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109

User defined Datatype

These are the datatyps defined by users. These are defined by user by combining different primitive and user defined datatypes.
Structure
union
enumaration
class

1.2.3.1 Structure

A structure is a user defined composite datatype.


A structure is one or a group of data elements of different types grouped together under one name .
A structure is declared in C++ by using the keyword struct using the following syntax

struct structure_name
{
member_datatype1 member_name1;
member_dataype2 member_name2;
..................
};
For example: struct students
{
char studentName[10]; //name of student
int SSN; // social security number
char standard[10];
float score;
}
Accessing the members of a Structure: We can access all the members of a structure by adding a period after the name of the structure variable name and then
the name of the field we want to access.

There are the two formats to access structure members:

struct_name_variable.member_name // structure
struct_name_pointer->member_name // structure pointer

For example if we create a structure variable of type Student declared above as,

Struct Student newStudent={Renuka,234576,12th,78.5};


The name of the newStudent can be changed as
newStudent.studentName=Renuka Lal;
If a pointer to structure is declared as,
struct Student *studentPtr=&newStudent;
In this case the members can be accessed using the instead of . As folows
studentPtr->newStudent;

1.2.3.2 Union
A union is also a user defined composite datatype like structure.
Unlike structure it enables to store different data types in the same memory location.
A union can be defined with many members, but only one member can contain a value at any given time.
Unions provide an efficient way of using the same memory location for multi-purpose.
The memory occupied by a union will be large enough to hold the largest member of the union. For example, in above example

To define a union, you must use the keyword union is used in very similar way like structure. The syntax of the union declaration statement is as follows:
union union_name
{
member_datatype1 member_name1;
member_dataype2 member_name2;
..................
};

union students
{
char studentName[20]; //name of student
int SSN; // social security number
char standard[10];
float score;
}

Now, a variable of Student type can store either an integer or a floating-point number, or a string of characters. This means that a single variable ie. same memory
location can be used to store multiple types of data. The memory occupied by a union will be large enough to hold the largest member of the union. For example, in
above example Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by character string.

Accessing the members of a union is same as structure.

Enumaration

Enumerated types used is to create new data types that can take on only a restricted range of values and these values are all expressed as constants.

When an enumerated type is declared, the name of the new type is specified along with the possible values it can take on.
Syntax is enum datatype_name {list of values};

For example , enum studentGrade {'A','B','C','D'};

Class

Please refer to the chapter - 2.1 Introduction to OOP concepts

C++ Fundamentals
C++ Overview

C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that supports procedural, object-oriented, and generic
programming.
C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features.
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey, as an enhancement to the C language and originally named
C with Classes but later it was renamed C++ in 1983.
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.

Note: A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time.

Writing first C++ Program


Let us have a look at a sample code in C++ that would print Hello World in the console:

Let us look various parts of the above program:


The C++ language defines several headers, which contain information that is either necessary to your program. For this program, the header <iostream> is
needed.
using namespace std; tells the compiler to use the namespace std.
int main() is the main function where program execution begins.
cout << "Hello World."; Displays the message Hello World on screen.
// prints Hello World : Is a single-line comment available in C++. Singleline comments begin with // and stop at the end of the line
return 0; terminates main()function and return the value 0 to the calling process.

Compiling and Executing C++ Program

Open a text editor and add the code as above.


Save the file as: hello.cpp
Open a command prompt and go to the directory where you saved the file.
Type 'g++ hello.cpp ' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would
generate a.out executable file.
Now, type ' a.out' to run your program.
You will be able to see ' Hello World ' printed on the window.

Working with Data Items

Variable Declaration in C++

A variable provides us with named storage that programs can manipulate.


Each variable in C++ has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory;
and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C++ is case-sensitive.
A variable declaration tells the compiler where and how much to create the storage for the variable. A variable declaration specifies a data type, and contains a list
of one or more variables of that type as follows:

Syntax: <datatype> variable_list;

Here, type must be a valid C++ data type including char, int, float, double, bool etc., and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here:

You can declare more than one variable of same type in a single statement

Variable Initialization in C++


When we declare a variable it's default value is undetermined. We can declare a variable with some initial value.
Syntax: variable_name = value

Variables can also be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:
Syntax: type variable_name = value;

The following example shows how variable can be declared an initialized inside the main function:

When the above code is compiled and executed, it produces the following result:
30
23.3333

Scope of Variable

A scope is a region of the program where variables can be declared:


Inside a function or a block which is called local variables,
Outside of all functions which is called global variables.
Local Variables:
Variables that are declared inside a function or block are local variables.
They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the
example using local variables:

Global Variables:
Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your
program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout the entire program after its declaration.

Following is the example using global and local variables:

A program can have same name for local and global variables but value of local variable inside a function will take preference. For example:

When the above code is compiled and executed, it produces the following result:

10

Using Constants in C++


Constants refers to fixed values that program may not alter. They are also called literals.
Any attempt to change the value of a constant will result in an error message. Constants can be of any of the basic data types and can be divided into Integer
constants, Floating-Point constants, Character constants, String constants and Boolean constants.
Constants are treated just like regular variables except that their values cannot be modified after their definition.

You can use const prefix to declare constants with a specific type as follows:
Syntax: <const type> variable = value;

Following example explains it in detail:

When the above code is compiled and executed, it produces the following result:
15
A

Conditional Structures
Objective

If Statement
If .. Else Statement
If .. Elseif .. else statement
Nested if statement
Switch .. case statement

If Statement

If statement can be use to evaluate conditional statements. Based on the result of evaluation one of more statements can be executed

syntax of the if statement

if(condition)
{
statement(s) if condition evaluates to true;
}
Statements are executed if the condition is true. No output if the condition false.

if .. else statement
To perform some action in either of the situation based on the conditional evaluation if.. else construct can be used.

syntax of the if..else statement

if(condition)
{
statement(s) if condition evaluates to true;
}
else
{
statement(s) if condition evaluates to false;
}

Note: If only one statement is there after the condition, {} are not required

if (condition)
statement;
else
statement;

If .. elseif ..else statement

Using if...elseif...else multiple condition can be evaluated.


syntax of the if statement

if(condition)
{
statement(s) if condition evaluates to true;
}
else if (condition2)
{
statement(s) if condition2 evaluates to true;
}

else
{
statement(s) if none of the above conditions are true;
}

Note: If only one statement is there after the condition, {} are not required

Consider the following example:

#include<iostream>
using namespace std;

int main()
{
int Size;
char Type;
cout<<Enter TV Size [20/30] :;
cin>>Size;
if(Size==20)
cout<< Discount = 10% <<endl;
else
{
cout<< Enter TV Type [ C:CRT / L:LED] : ;
if(Type=='C')
cout<< Discount= 15 % <<endl;
else
cout<< Discount= 20 % <<endl;
}

return 0;
}

Nested If statements
To evaluate multilevel conditional statements, If statements can be placed within another if/else block.

Consider the following example:

#include<iostream>
using namespace std;

int main()
{
int Age;
cout<<Enter Age ;
cin>>Age;
if(Age<13)
cout<< Child <<endl;
else if(Age<18)
cout<< Teen <<endl;
else if(Age<40)
cout<< Young <<endl;
else if(Age<55)
cout<< Middle Aged<<endl;
else
cout<< Old<<endl;

return 0;
}

Switch-case statements

The other way conditional evaluation can be performed using switch statement which permits multiple branching:
The syntax of switch statement is:

switch (var / expression)


{
case constant1 :
statement 1;
break;
case constant2 :
statement 2;
break;
...
default:
statement n;
break;
}
The execution of switch statement begins with the evaluation of expression. If the value of expression matches with the constant then the statements following this
statement execute sequentially till it reaches the break statement. The break statement transfers control to the end of the switch statement. If the value of
expression does not match with any constant, the statement with default is executed.

Some important points about switch statement

The expression of switch statement must be of type integer or character type.


The default case need not to be used at last case. It can be placed at any place.
The case values need not to be in specific order.

Consider the following example:

#include<iostream>
using namespace std;

int main()
{
char Grade;
cout<< Enter Grade :;
cin>>Grade;

switch(Grade)
{
case 'A':
cout<< Excellent <<endl;
break;
case 'B':
cout<< Good <<endl;
Break;
case 'C':
cout<< Fair <<endl;
Break;
case 'D':
cout<< Satisfactory <<endl;
Break;
case 'E':
cout<< Poor <<endl;
Break;
default:
cout<< Invalid Grade <<endl;
break;
return 0;
}

Related Videos:
(/communities/unix-c-oracle-lounge-0/content/c-iterations-and-operations) (/communities/unix-c-oracle-lounge-0/content/c-iterations-and-operations) Next

Ask a Doubt:

Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune

Note: Please do not use the doubts section for any quiz/quiz-content related queries.
Use the helpline (/feedbacks/new) () located above in top right corner for problems/queries related to quizzes.

Styles Format

Characters (including HTML): 0

Submit

Open Doubts Closed Doubts My Doubts

There are no doubts yet

Vous aimerez peut-être aussi