Académique Documents
Professionnel Documents
Culture Documents
(http://www.tcs.com)
Chapter 1: Introduction to C++ Basics
Index
1.1.C++ Datatypes and Conditional Constructs (/communities/unix-c-oracle-lounge-0/content/c-datatypes-and-conditional-constructs)
Go to Doubts
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++ :
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.
Note: In C++ this size is machine dependent, hence there can be a variation.
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
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 .
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.
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 [ ].
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.
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
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
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.
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,
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.
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};
Class
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.
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
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
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.
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
You can use const prefix to declare constants with a specific type as follows:
Syntax: <const type> variable = value;
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
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.
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(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
#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.
#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:
#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
Submit