C & C++Language IMP Questions03042023
C & C++Language IMP Questions03042023
Step 1 : start
Step 2 : read a,b
Step 3 : compute c= a+b
Step 4 : print c
Step 5 : stop.
2. What is Flowchart?
Flowchart: Diagrammatic representation of algorithm is called a flow chart.
Symbols:
Start/stop
Input/output
computation
conditi
on
connector
1
Data flow
Example:
start
Read a b
C= a+b
Print c
stop
2
3. Explain about History of C-Language?
History of C Language
Let's see the programming languages that were developed before C language.
Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.
• It is a robust language, which has a rich set of built-in functions and operators
available can be used to write any complex program.
• Programs Written in C are efficient and fast. This is due to its variety of data type and
powerful operators.
3
• C is highly portable this means that programs once written can be run on another
machines with little or no modification.
Tokens in C
Tokens in C is the most important element to be used in creating a program in C. We can define
the token as the smallest individual element in C. For `example, we cannot create a sentence
without using words; similarly, we cannot create a program in C without using tokens in C.
Therefore, we can say that tokens in C is the building block or the basic component for creating
a program in C language.
Classification of tokens in C
o Variables in C
o Datatypes in C
o Keywords in C
o Operators in C
o Constant in C
Variables: A variable is a user defined data name that may be used to store some fixed value.
Its values can be changed during the program execution.
4
Declaration of Variable
Declaration Syntax:
datatype variableName;
Example
int number;
The above declaration tells to the compiler that allocates 2 bytes of memory with the
name number and allows only integer values into that memory location.
Datatypes:
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
5
Basic Data Types
The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating
system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
Float 4 byte
Double 8 byte
6
Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There
are only 32 reserved words (keywords) in the C language.
Constants :
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a',
3.4, "c programming" etc.
1. const keyword
2. #define preprocessor
1) C const keyword
2) C #define preprocessor
Syntax:
7
Operators :
An operator is a symbol used to perform arithmetic and logical operations in a program. That
means an operator is a special symbol that tells the compiler to perform mathematical or logical
operations.
operators that are classified as follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
Arithmetic Operators:
The arithmetic operators are the symbols that are used to perform basic mathematical
operations like addition, subtraction, multiplication, division and percentage modulo.
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
8
Relational Operators :
== Is equal to 10 == 5 is FALSE
Logical Operators :
The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.
⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is
FALSE then complete condition becomes FALSE.
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is
TRUE then complete condition becomes TRUE.
9
Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it is TRUE
The increment and decrement operators are called unary operators because both need only one
operand. The increment operators adds one to the existing value of the operand and the
decrement operator subtracts one from the existing value of the operand. The following table
provides information about increment and decrement operators.
The increment and decrement operators are used infront of the operand (++a) or after the
operand (a++). If it is used infront of the operand, we call it as pre-increment or pre-
decrement and if it is used after the operand, we call it as post-increment or post-decrement.
Assignment Operators :
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand
side variable (Lvalue). The assignment operator is used in different variants along with
arithmetic operators. The following table describes all the assignment operators in the C
programming language.
+= Add both left and right-hand side values and store the result into left-hand side variable A += 10
⇒ A = A+10
Bitwise Operators :
The bitwise operators are used to perform bit-level operations in the c programming language.
When we use the bitwise operators, the operations are performed based on the binary values.
The following table describes all the bitwise operators in the C programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
10
Operator Meaning Example
| OR A|B
⇒ 29 (11101)
^ XOR A^B
⇒ 13 (01101)
~ complement ~A
⇒ 6 (00110)
Conditional Operator :
The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making. In this operator, first we verify a condition, then we
perform one operation out of the two operations based on the condition result. If the condition
is TRUE the first option is performed, if the condition is FALSE the second option is
performed.
The conditional operator is used with the following syntax.
Example
Special Operators :
The following are the special operators in c programming language.
11
sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This
operator is used with the following syntax.
sizeof(variableName);
Example
C Input Functions
C programming language provides built-in functions to perform input operations. The input
operations are used to read user values (input) from the keyboard. The c programming language
1. scanf()
2. getchar()
3. getch()
4. gets()
scanf() function :
The scanf() function is used to read multiple data values of different data types from the
keyboard. The scanf() function is built-in function defined in a header file called "stdio.h".
int i;
scanf("%d",&i);
12
getchar() function :
The getchar() function is used to read a character from the keyboard and return it to the
program. This function is used to read a single character.
char ch;
ch = getchar();
getch() function :
The getch() function is similar to getchar function.
char ch;
ch = getch();
gets() function :
The gets() function is used to read a line of string and stores it into a character array.
char name[30];
gets(name);
C Output Functions :
C programming language provides built-in functions to perform output operation. The output
operations are used to display data on user screen (output screen) or printer or any file. The c
1. printf()
2. putchar()
3. puts()
printf() function :
The printf() function is used to print string or data values or a combination of string and data
values on the output screen (User screen). The printf() function is built-in function defined in
a header file called "stdio.h".
printf("Hello! Welcome to btechsmartclass!!!");
putchar() function :
The putchar() function is used to display a single character on the output screen.
char ch = 'A';
putchar(ch);
13
puts() function :
The puts() function is used to display a string on the output screen.
char name[30];
puts(name);
7. Explain about Structure of C Language?
A C program is divided into different sections. There are six main sections to a basic c program.
Documentation Section :
The documentation section is the part of the program. we usually give the name of the program,
the details of the author and other details. they cannot recognise the compiler.
Example
/*
*/
Link Section :
This part of the code is used to declare all the header files that will be used in the program.
Example
1 #include<stdio.h>
14
Definition Section :
In this section, we define different constants. The keyword define is used in this part.
1 #define PI=3.14
1 void main( )
2 {
3 int a=10;
4 printf(" %d", a);
5 return 0;
6 }
15
Example Program
/* Demonstration program */
#include<stdio.h>
Void main()
Printf(“bye bye”);
getch();
Output :
welcome to C program
bye bye
These are the statements which is used to execute a block of statements. If conditions become
true. Otherwise, next statements is executed.
1. if statement
2. switch statement
if statement in c :
It is a power full single way decision making statement , if statement is classified into four
types as follows...
1. Simple if statement
2. if-else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)
16
Simple if statement :
Simple if statement is used to verify the given condition and executes the block of statements
based on the condition result. If it is TRUE, it executes the next statement or block of
statements. If the condition is FALSE, it skips the execution of the next statement or block of
statements. The general syntax and execution flow of the simple if statement is as follows.
if-else statement :
The if-else statement is used to verify the given condition and executes only one out of the two
blocks of statements based on the condition result. The if-else statement evaluates the specified
condition. If it is TRUE, it executes a block of statements (True block). If the condition is
FALSE, it executes another block of statements (False block). The general syntax and
execution flow of the if-else statement is as follows.
Nested if statement :
Writing a if statement inside another if statement is called nested if statement. The general
syntax of the nested if statement is as follows...
17
if-else-if statement (if-else ladder) :
Writing a if statement inside else of an if statement is called if-else-if statement. The general
syntax of the if-else-if statement is as follows...
• while loop
• do-while loop
• for loop
18
while loop :
This is the one of the loop-controlled statement which is used to executed for a specified
Number of times until condition becomes false.
During the process the condition is evaluated first when the condition becomes true then
statement block is executed. After that again check the condition continuously until condition
becomes false.
void main()
{
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
while( n <= 10 )
{
19
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}
getch() ;
}
Output:
do-while loop :
It is similar to the while loop but different syntax do while starts with a keyword do and
20
During the process it executes the block of statements then check the condition if condition is
true then again executes the block of instructions continuously until condition becomes false.
Example Program | Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>
void main()
{
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;
getch() ;
}
Output:
for statement in C
It is the accurate loop control statement which is used to execute for a specified number of
21
Example Program | Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
22
getch() ;
}
Output:
Array : Arrays a kind of data structure that can store 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
23
Example program for Single Dimensional Array :
1. #include<stdio.h>
2. Void main()
3. {
4. int i=0;
5. int marks[5]={20,30,40,50,60};
6. for(i=0;i<5;i++)
7. {
8. printf("%d \n",marks[i]);
9. }
10. getch();
11. }
Output
20
30
40
50
60
Most popular and commonly used multi dimensional array is two dimensional array. The
2-D arrays are used to store data in the form of table. We also use 2-D arrays to create
mathematical matrices.
1. data_type array_name[rows][columns];
1. int twodimen[4][3];
24
Initialization of 2D Array in C
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
C Functions :
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program.
25
• Function Declaration (Function Prototype)
• Function Definition
• Function Call
Function Declaration :
The function declaration tells the compiler about function name, the data type of the return
value and parameters.
Function declaration syntax -
returnType functionName(parametersList);
In the above syntax, returnType specifies the data type of the value which is sent as a return
value from the function definition.
Function Definition :
The function definition provides the actual code of that function. The function definition is also
known as the body of the function.
Function definition syntax -
returnType functionName(parametersList)
{
Actual code...
Function Call :
The function call tells the compiler when to execute the function definition.
Function call syntax -
functionName(parameters);
void main()
int a;
a=power(2,6);
printf(“%d”,a);
a=power(3,4);
printf(“%d”,a);
26
getch();
int r=1,i;
for(i=1;i<=y;i++)
r=r*x;
return r;
Output :
64 81
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial
value of a variable. There are four types of storage classes in C
void main()
{
int a=10;
printf(“%d”,a);
int b=20;
27
printf(“%d”,a);
printf(“%d”,b);
printf(“%d”,a);
printf(“%d”,b);
getch();
Scope:
Void abc( )
++a;
Void main( )
{
int a=10;
abc( );
abc( );
abc( );
printf(“%d”,a);
getch();
28
Static :
Void abc( )
int L=0;
static int s;
L++;
S++;
Printf(“%d%d”,L,s);
Void main()
abc( );
abc( );
abc( );
printf(“%d”,s);
getch();
Extern:
Void pqr( )
extern int g;
++g;
int g;
29
void abc( )
++g;
Void xyz( )
++g;
Void main( )
++g;
abc();
xyz();
pqr();
printf(“%d”,g);
getch();
Output:4
Recursion in C :
Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function.
Void abc(int L)
printf(“\n%d”,L);
30
if(L<=2)
abc(L+1);
printf(“\n%d”,L);
Voi main()
abc(1);
getch();
Output:
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. The size of the pointer
depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.
1. int n = 10;
2. int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of
type integer.
31
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
An example of using pointers to print the address and value is given below.
As you can see in the above figure, pointer variable stores the address of number variable, i.e.,
fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Let's see the pointer example as explained for the above figure.
void mian()
{
int i;
int *ptr;
i=25;
ptr=&i;
printf(“\n%d%d”, &i, ptr);
printf(“\n%d%d”, i, *ptr);
*ptr=35;
printf(“\n%d%d”, &i, ptr);
printf(“\n%d%d”, i, *ptr);
getch();
}
output: 500 500
25 25
500 500
35 35
32
15 .Explain various parameter passing techniques of functions and pointers with
example.
(Or)
Distinguish call by value and call by reference with necessary example.
Parameter passing is a technique that passes data from one function to another function.
That is the function which is called must be assigned with some values passed by the calling
Function. There are two parameter passing techniques.
1. Call by value (or) pass by value technique
2. Call by reference (or) pass by reference technique
Let's understand call by value and call by reference in c language one by one.
o In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter by the
formal parameter.
o In call by value, different memory is allocated for actual and formal parameters since
the value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given below:
33
{
int t;
t=a;
a=b;
b=t;
}
Void main()
{
int a=10, b=20;
swap(a,b);
printf(“%d%d”,a,b);
getch();
}
Output : 10 20
o In call by reference, the address of the variable is passed into the function call as the
actual parameter.
o The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value stored
at the address of the actual parameters, and the modified value gets stored at the same
address.
34
int a=10, b=20;
swap(&a, &b);
printf(“%d%d”,a,b);
getch();
}
Output: 20 10
int *arr[5];
Where arr[0] will hold one integer variable address, arr[1] will hold another integer variable
address and so on.
#include <stdio.h>
void main ( )
35
{
getch ( );
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
36
Strlen() :
it is used to find the length of the string
Syntax :
int x=strlen(string);
Example :
#include<string.h>
Void main()
{
Char str[10]=”sita”;
int x=strlen(str);
printf(“length of the string =%d”,x);
getch();
}
Output :
Enter any string deepa
DEEPA
37
Strlwr() :
It converts the given string into lower case
Syntax :
Strlwr(string);
Example :
#include<string.h>
Void main()
{
Char str[10]=”RAMA”;
Strlwr(str);
Printf(“lower case string=%s”,str);
getch();
}
Output :
lower case string = rama
strrev() :
it reversed a given string
syntax :
strrev(string);
Example :
#include<string.h>
char str[10]=”Hello”;
strrev(str);
printf(“Reversed string=%s”,str);
getch();
}
Output :
Reversed string = olleH
Strcpy() :
It is used to copy the one string to another string
Syntax :
Strcpy(string2,string1);
38
Example :
#include<string.h>
Void main()
{
Char str1[10]=”ramu”,str2[10];
Strcpy(str2,str1);
Printf(“copied string=%s”,str2);
getch();
}
Output :
Copied string = ramu
Strcat() :
It concatenate (join) two strings. If second string is join at the end of the first string and the re
sultant string is first string .
Syntax :
Strcat(string1,string2);
Example :
#include<string.h>
Void main()
{
char str1[20]=”Hello”,str2[10]=”welcome”;
strcat(str1,str2);
printf(“concatenation of two strings=%s”,str1);
getch();
}
Output :
Concatenation of two strings = Hellowelome
Strcmp() :
It is used to compare two strings whether it is equal or not .here it compares only ASCII
values but not lengths.
Syntax :
X= strcmp(string1,string2);
39
Example :
#include<string.h>
Void main()
{
Char str1[10]=”hello”,str2[10]=”hello”;
int x;
x=strcmp(str1,str2);
if(x==0)
printf(“strings are equal “);
else if(x>0)
printf(“first string is greater than second string”);
else
printf(“first string is less than second string”);
getch();
}
Output :
Strings are equal
• Title
• Author
• Subject
• Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new
data type, with more than one member. The format of the struct statement is as follows −
struct [structure tag]
{
40
member definition;
member definition;
...
member definition;
} [one or more structure variables];
Here is the way you would declare the Book structure −
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
Accessing Structure Members
To access any member of a structure, we use the member access operator (.)
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
void main( )
{
getch();
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
41
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
union Data
{
int i;
float f;
char str[20];
} data;
union Data
{
int i;
float f;
char str[20];
};
void main( )
{
42
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
gech();
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Typecasting allows us to convert one data type into other. In C language, we use cast operator
for typecasting which is denoted by (type).
Syntax:
(type)value;
With Type Casting:
float f=(float) 9/4;
printf("f : %f\n", f );//Output: 2.250000
Type Casting example
Let's see a simple example to cast int value into the float.
1. #include<stdio.h>
2. int main(){
3. float f= (float)9/4;
4. printf("f : %f\n", f );
5. return 0; }
Output:
f : 2.250000
43
21.What is the use of enumerated data type?
Enum in C
The enum in C is also known as the enumerated type. It is a user-defined data type that consists
of integer values, and it provides meaningful names to these values. The use of enum in C
makes the program easy to understand and maintain. The enum is defined by using the enum
keyword.
22.Break statement in C?
The break is a keyword in C which is used to bring the program control out of the loop.
Syntax:
1. //loop or switch case
2. break;
44
Flowchart of break in c
Example
1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. int i;
6. for(i = 0; i<10; i++)
7. {
8. printf("%d ",i);
9. if(i == 5)
10. break;
11. }
12. printf("came outside of loop i = %d",i);
13.
14. }
Output
23.Continue statement in C ?
The continue statement in C language is used to bring the program control to the beginning
of the loop. The continue statement skips some lines of code inside the loop and continues with
the next iteration. It is mainly used for a condition so that we can skip some code for a particular
condition.
Syntax
The syntax for a continue statement in C is as follows −
45
continue;
Flow Diagram
Example
#include <stdio.h>
void main ( )
{
int a = 10;
do
{
if( a == 15)
{
a = a + 1;
continue;
}
} while( a < 20 );
getch( );
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
46
value of a: 18
value of a: 19
C++ is an Object Oriented Programming language but is not purely Object Oriented.
Its features like Friend and Virtual, violate some of the very important OOPS features.
The major difference being OOPS concept, C++ is an object oriented language whereas C is
a procedural language. Apart form this there are many other features of C++ which gives this
language an upper hand on C laguage.
2. All the OOPS features in C++ like Abstraction, Encapsulation, Inheritance etc makes
it more worthy and useful for programmers.
3. C++ supports and allows user defined operators (i.e Operator Overloading) and
function overloading is also supported in it.
5. The Concept of Virtual functions and also Constructors and Destructors for Objects.
C C++
C was developed by Dennis Ritchie C++ was developed by Bjarne
between the year 1969 and 1973 at Stroustrup in 1979.
AT&T Bell Labs.
47
For the development of code, C
supports procedural programming. C++ is known as hybrid language
because C++ supports
both procedural and object
oriented programming paradigms.
In .h extension are used for all the header C++ supports bool datatype apart
files. , from the five fundamental
datatypes of C ,
In C, the concept of structures is widely
used. In C++, .h extension is not
compulsory. ,
In C++, the concept of classes are
used.
Documentation Section:
• It can be also used to write for purpose of the program.
48
• Whatever written in the documentation section is the comment and is not
compiled by the compiler.
Linking Section:
Header Files:
• Generally, a program includes various programming elements like built-in
functions, classes, keywords, constants, operators, etc. that are already defined
in the standard C++ library.
Definition Section:
• It is used to declare some constants and assign them some value.
Global Declaration Section:
• Here, the variables and the class definitions which are going to be used in the
program are declared to make them global.
Main Function:
• The main function tells the compiler where to start the execution of the
program. The execution of the program starts with the main function.
• All the statements that are to be executed are written in the main function.
To write the first C++ program, open the C++ console and write the following code:
1. #include <iostream.h>
2. #include<conio.h>
3. void main()
4. {
5. clrscr();
6. cout << "Welcome to C++ Programming.";
7. getch();
8. }
#include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.
void main() The main() function is the entry point of every program in C++ language. The
void keyword specifies that it returns no value.
cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
getch() The getch() function asks for a single character. Until you press any key, it blocks
the screen.
49
27 .Explain about oop concepts in C++ ?
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies the software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object :
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class :
Inheritance :
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism :
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Abstraction :
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
50
Encapsulation :
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
Storage class is used to define the lifetime and visibility of a variable and/or function within a
C++ program.
Lifetime refers to the period during which the variable remains active and visibility refers to
the module of a program in which the variable is accessible.
There are five types of storage classes, which can be used in a C++ program
1. Automatic
2. Register
3. Static
4. External
5. Mutable
It is the default storage class for all local variables. The auto keyword is applied to all local
variables automatically.
1. {
2. auto int y;
3. float y = 3.45;
4. }
51
The above example defines two variables with a same storage class, auto can only be used
within functions.
The register variable allocates memory in register than RAM. Its size is same of register size.
It has a faster access than other variables.
It is recommended to use register variable only for quick access such as in counter.
The static variable is initialized only once and exists till the end of a program. It retains its
value between multiple functions call.
The static variable has the default value 0 which is provided by compiler.
1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
52
External Storage Class
The extern variable is visible to all the programs. It is used if two or more files are sharing
same variable or function.
"Data Member" and "Member Functions" are the new names/terms for the members of a
class, which are introduced in C++ programming language.
The variables which are declared in any class by using any fundamental data types (like int,
char, float etc) or derived data type (like class, structure, pointer etc.) are known as Data
Members. And the functions which are declared either in private section of public section are
known as Member functions.
1. Private members
2. Public members
1) Private members
The members which are declared in private section of the class (using private access
modifier) are known as private members. Private members can also be accessible within the
same class in which they are declared.
2) Public members
The members which are declared in public section of the class (using public access modifier)
are known as public members. Public members can access within the class and outside of the
class by using the object name of the class in which they are declared.
class Test
{
private:
int a;
float b;
char *name;
public:
int count;
53
void getB() { b=20; }
...;
};
Here, a, b, and name are the private data members and count is a public data member.
While, getA() is a private member function and getB() is public member functions.
C++ program that will demonstrate, how to declare, define and access data members an
member functions in a class?
#include <iostream>
#include <string.h>
using namespace std;
#define MAX_CHAR 30
//class definition
class person
{
//private data members
private:
char name [MAX_CHAR];
int age;
//main function
54
int main()
{
//creating an object of person class
person PER;
return 0;
}
Output
As we can see in the program, that private members are directly accessible within the
member functions and member functions are accessible within in main() function (outside of
the class) by using period (dot) operator like object_name.member_name;
----------------------------------------------------------------------------------------------------------------
IMPORTANT QUESTIONS
55
17. Explain about break, continue, enumerated statements with examples.
18. Write the structure of a C++ program.
19. Difference between C and C++.
20. Explain the Storage Classes of C++.
21. Explain Data Members and various Member-Functions.
56