You are on page 1of 92

C Programming Language

C programming is considered as the base for other programming languages, that is why it is known as mother
language.
It can be defined by following ways:
1.
2.
3.
4.
5.

Mother language
System programming language
Procedure-oriented programming language
Structured programming language
Mid level programming language

1) C as a mother language :

C language is considered as the mother language of all the modern languages

because most of the compilers, JVMs, Kernels etc. are written in C language and most of languages follows
c syntax e.g. C++, Java etc. It provides the core concepts like array, functions, file handling etc. that is being used
in many languages like C++, java, C# etc.

2) C as a system programming language: A system programming language is used to create system


softwares. C language is a system programming language because it can be used to do low level
programming (e.g. driver and kernel). It is generally used to create hardware devices, OS, drivers,
kernels etc. For example, Linux kernel is written in C.
It can? Be used in internet programming like java, .net, php etc.

3) C as a procedural language: A procedure is known as function, method, routine, subroutine etc. A


procedural language specifies a series of steps or procedures for the program to solve the
problem. A procedural language breaks the program into functions, data structures etc. C is a
procedural language. In C, variables and function prototypes must be declared before being used.

4) C as a structured programming language :

A structured programming language is a subset of procedural

language. Structure means to break a program into parts or blocks so that it may be easy to understand. In
C language, we break the program into parts using functions. It makes the program easier to understand and
modify.

5) C as a mid-level programming language :

C is considered as a middle level language because

it supports the feature of both low-level and high level language. C language program is converted into
assembly code, supports pointer arithmetic (low level), but it is machine independent (feature of high level).
Low level language is specific to one machine i.e. machine dependent. It is machine dependent, fast to run. But
it is not easy to understand.
High Level language is not specific to one machine i.e. machine independent. It is easy to understand.

--------------------------------------------------------------------------------------------------------------------What does Procedural Language mean?


Ans: Procedural language is a computer programming language that specifies a series of well-structured steps and
procedures within its programming context to compose a program. It contains a systematic order of statements,
functions and commands to complete a computational task or program. Procedural language is also known as
imperative language.

--------------------------------------------------------------------------------------------------------------------What is programming paradigm?


Ans: Programming paradigm: Programming paradigm means that the fundamental of computer programming.
Programming style or methods are changed from language to language.
There are three programming paradigm

1.

Imperative / Procedural: Imperative programming languages are the most traditional once. Their code

consists of sequential statements to achieve the desired goal.


For Ex:
2.

Basic and Pascal

Functional / Modular: Functional programming languages are as name suggest, the problems are divided

into functions / modules.


For Ex:
3.

Object Oriented: Object oriented programming languages; they mainly focus around objects that have their

own properties and procedural / method.


It is also possible to create classes that include the functionality of other already existing classes.

---------------------------------------------------------------------------------------------------------------------

History of C:

C language is a general purpose and structured programming language developed by 'Dennis

Ritchie' at AT &T's Bell Laboratories in the 1972s in USA. It is also called as 'Procedure oriented programming
language.'

Year of
Establishment

1960

Developed By

ALGOL-60

Cambridge University

CPL (Combined Programming

1963

1967

Language Name

Language)

BCPL (Basic Combined Programming

Martin Richard at Cambridge

Language)

University

1970

1972

CPL : (1963) :

Cambridge University

Ken Thompson at AT & T's Bell


Laboratories.

Dennis Ritchie at AT & T' Bell


Laboratory.

CPL is an acronym for Combined Programming Language. It was developed at

Cambridge University.

BCPL : (1967) : BCPL is an acronym for Basic Combined Programming Language. It was developed
by Martin Richards at Cambridge University in 1967. BCPL was not so powerful. So, it was failed.

B : (1970) : B language was developed by Ken Thompson at AT & T Bell Laboratories in 1970. It was
machine dependent. So, it leads to specific problems.

C : (1972) : 'C' Programming Langauage was developed by Dennis Ritchie at AT & T Bell
Laboratories in 1972. This is general purpose, compiled, structured programming langauage. Dennis
Ritchie studied the BCPL, then improved and named it as 'C' which is the second letter of BCPL

OR

History of C Language
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T (American
Telephone & Telegraph), located in U.S.A.
Dennis Ritchie is known as the founder of c language.
It was developed to overcome the problems of previous languages such as B, BCPL etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many features of previous
languages such as B and BCPL.
Let's see the programming languages that were developed before C language.

Language

Year

Developed By

Algol

1960

International Group

BCPL

1967

Martin Richard

1970

Ken Thompson

Traditional C

1972

Dennis Ritchie

K&RC

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

--------------------------------------------------------------------------------------------------------------------Q4. The C language has following numerous features as:

Portability

Flexibility

Effectiveness and efficiency

Reliability

Interactivity

Features of C Language:
1. It is robust language because of rich set of binary in - function
2. It is efficient and fast because of its variant data-types and powerful operation.
3. It is highly Portable i.e., programs written in one computer can be run on another
4. It is well suited for structure program, thus allows the user to think about the problem in
the terms of functional blocks.
5. Debugging, testing and maintenance is easy

6. Ability to extend itself, we can continuously add our own functions to the program.

or

Features of C Language
C is the widely used language. It provides a lot of features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible

1) Simple : C is a simple language in the sense that it provides structured approach (to break the
problem into parts), rich set of library functions, data types etc.
2) Machine Independent or Portable : Unlike assembly language, c programs can be executed in
many machines with little bit or no change. But it is not platform-independent.
3) Mid-level programming language : C is also used to do low level programming. It is used to
develop system applications such as kernel, driver etc. It also supports the feature of high level
language. That is why it is known as mid-level language.
4) Structured programming language : C is a structured programming language in the sense that we
can break the program into parts using functions. So, it is easy to understand and modify.
5) Rich Library: C provides a lot of inbuilt functions that makes the development fast.
6) Memory Management: It supports the feature of dynamic memory allocation. In C language, we
can free the allocated memory at any time by calling the free() function.
7) Speed: The compilation and execution time of C language is fast.
8) Pointer: C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array etc.
9) Recursion: In c, we can call the function within the function. It provides code reusability for
every function.
10) Extensible: C language is extensible because it can easily adopt new features.

---------------------------------------------------------------------------------------------------------------------

Structure of C program
#include <stdio.h>
/* Include files for input/output functions*/
#define const_namevalue
/* constant declaration if required */
main() /* Main function */
{

/* each declarations and statements are separated by semi colon */

declarations
/* variables; arrays; records;

function declarations etc */


statements
}
function definitions
--------------------------------------------------------------------------------------------------------------------------------------------

Execution of C Program :
C program executes in following 4 (four steps).

1.

Creating a program :

An editor like notepad or wordpad is used to create a C program. This file contains a source code
which consists of executable code. The file should be saved as '*.c' extension only.
2.

Compiling the program :

The next step is to compile the program. The code is compiled by using compiler. Compiler converts
executable code to binary code i.e. object code.
3.

Linking a program to library :

The object code of a program is linked with libraries that are needed for execution of a program.
The linker is used to link the program with libraries. It creates a file with '*.exe' extension.
4.

Execution of program :

The final executable file is then run by dos command prompt or by any other software.

--------------------------------------------------------------------------------------------------------------------------------------------

Variables in C
A variable is a name of memory location. It is used to store data. Its value can be changed and it can be reused
many times. It is a way to represent memory location through symbol so that it can be easily identified.
Let's see the syntax to declare a variable:
type variable_list;
The example of declaring variable is given below:
int a;
float b;
char c;
Here, a, b, c are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:

int a=10,b=20;//declaring 2 variable of integer type


float f=20.8;
char c='A';
There are many types of variables in c:
1.
2.
3.
4.
5.

local variable
global variable
static variable
automatic variable
external variable

(1) Local Variable : A variable that is declared inside the function or block is called local variable. It must be
declared at the start of the block.
void function1()
{
int x=10; //local variable
}
You must have to initialize the local variable before it is used.
(2) Global Variable : A variable that is declared outside the function or block is called global variable. Any function
can change the value of the global variable. It is available to all the functions.
It must be declared at the start of the block.
int value=20;
//global variable
void function1()
{
int x=10; //local variable
}
(3) Static Variable : A variable that is declared with static keyword is called static variable.
It retains its value between multiple function calls.
void

function1()

{
int

x=10;

static int

//local variable

y=10;

//static variable

x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
If you call this function many times, local variable will print the same value for each function call e.g,
11,11,11 and so on. But static variable will print the incremented value in each function call e.g. 11, 12, 13
and so on.
(3) Automatic Variable : All variables in C that is declared inside the block, are automatic variables by default. By we
can explicitly declare automatic variable using auto keyword.
void main()
{
int x=10; //local variable (also automatic)
auto int y=20;
//automatic variable
}
(5) External Variable : We can share a variable in multiple C source files by using external variable. To declare a
external variable, you need to use extern keyword.

myfile.h
extern int x=10; //external variable (also global)
program1.c
#include "myfile.h"
#include <stdio.h>
void printValue()
{
printf("Global variable: %d", global_variable);
}

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 C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

----------------------------------------------------------------------------------------------------BITWISE OPERATORS IN C : Assume variable A holds 60 and variable B holds 13, then:

Example
#include <stdio.h>
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */

printf("Line 6 - Value of c is %d\n", c );


}

Operators Precedence in C
Advertisements

Previous Page
Next Page

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds
into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
Category

Operator

Associativity

Postfix

() [] -> . ++ - -

Left to right

Unary

+ - ! ~ ++ - - (type)* & sizeof

Right to left

Multiplicative

*/%

Left to right

Additive

+-

Left to right

Shift

<< >>

Left to right

Relational

< <= > >=

Left to right

Equality

== !=

Left to right

Bitwise AND

&

Left to right

Bitwise XOR

Left to right

Bitwise OR

Left to right

Logical AND

&&

Left to right

Logical OR

||

Left to right

Conditional

?:

Right to left

Assignment

= += -= *= /= %=>>= <<= &= ^= |=

Right to left

Comma

Left to right

Example
Try the following example to understand the operator precedence available in C programming language:

#include <stdio.h>

main()
{
int a = 20;

int b = 10;
int c = 15;
int d = 5;
int e;

e = (a + b) * c / d;

// ( 30 * 15 ) / 5

printf("Value of (a + b) * c / d is : %d\n", e );

e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );

e = (a + b) * (c / d); // (30) * (15/5)


printf("Value of (a + b) * (c / d) is : %d\n", e );

e = a + (b * c) / d;

// 20 + (150/5)

printf("Value of a + (b * c) / d is : %d\n" , e );

return 0;
}
When you compile and execute the above program it produces the following result:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
Preprocessor : This is a program, that processes the source program before it is passed on to the

compiler. The program typed in the editor is the source code to the preprocessor, then it passed
the source code to the compiler. It is not necessary to write program with preprocessor & activity
Preprocessor directories are always initialized at the beginning of the program. it begins
with the symbol (#) hash. It place before the main() function
Eg: # include <station>
# define PI 3.14

Q6. What is preprocessor ?


Anwer: The preprocessor provides the ability for the inclusion of header files, macro
expansions, conditional compilation, and line control. In many C implementations, it is a
separate program invoked by the compiler as the first part of translation.

C Preprocessor directives:

Before a C program is compiled in a compiler, source code is processed by a program called


preprocessor. This process is called preprocessing.

Commands used in preprocessor are called preprocessor directives and they begin with #
symbol.
Below is the list of preprocessor directives that C language offers.

S.no Preprocessor
Syntax
1 Macro
#define
2
3
4

Header file
inclusion
Conditional
compilation
Other directives

Description
This macro defines constant value and can be any of
the basic data types.
#include <file_name> The source code of the file file_name is included in the
main program at the specified place
#ifdef, #endif, #if,
Set of commands are included or excluded in source
#else, #ifndef
program before compilation with respect to the condition
#undef, #pragma
#undef is used to undefine a defined macro variable.
#Pragma is used to call a function before and after main
function in a C program

A program in C language involves into different processes. Below diagram will help you to understand
all the processes that a C program comes across.

Example program for #define, #include preprocessors in C:


#include <stdio.h>
#define height 100
void main()
{
printf("value of height
}

: %d \n", height );

Output:
value of height : 100

Example program for conditional compilation directives:


a) Example program for #ifdef, #else and #endif in C:
o
o

#ifdef directive checks whether particular macro is defined or not. If it is defined, If


clause statements are included in source file.
Otherwise, else clause statements are included in source file for compilation and
execution.

#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif

return 0;

Output:
RAJU is defined. So, this line will be added in this C file

b) Example program for #ifndef and #endif in C:


#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, If
clause statements are included in source file.
Otherwise, else clause statements are included in source file for compilation and
execution.

o
o

#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program);
#endif
return 0;
}

Output:
SELVA is not defined. So, now we are going to define here

c) Example program for #if, #else and #endif in C:


o
o

If clause statement is included in source file if given condition is true.


Otherwise, else clause statement is included in source file for compilation and execution.

#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");
#endif
return 0;
}

Output:
This line will be added in this C file since a = 100

Example program for undef in C:

This directive undefines existing macro in the program.


#include <stdio.h>
#define height 100
void main()
{
printf("First defined value for height
: %d\n",height);
#undef height
// undefining variable
#define height 600
// redefining the same for new value
printf("value of height after undef \& redefine:%d",height);
}

Output:
First defined value for height : 100
value of height after undef & redefine : 600

Example program for pragma in C:


Pragma is used to call a function before and after main function in a C program.
#include <stdio.h>
void function1( );
void function2( );
#pragma startup function1
#pragma exit function2
int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
}
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end of " \
"main function" ) ;"
}

Output:
Function1 is called before main function call
Now we are in main function
Function2 is called just before end of main function

More on pragma directive in C:


S.no
Pragma command
1 #Pragma startup
<function_name_1>
2 #Pragma exit
<function_name_2>
3 #pragma warn rvl

description
This directive executes function named function_name_1 before
This directive executes function named function_name_2 just
before termination of the program.
If function doesnt return a value, then warnings are suppressed by

#pragma warn par

#pragma warn rch

this directive while compiling.


If function doesnt use passed function parameter , then warnings
are suppressed
If a non reachable code is written inside a program, such warnings
are suppressed by this directive.

-----------------------------------------------------------------------------------------------------Q6. Compiler Directives


(1)

#include statements : used to include the header file for input/output stdio.h, the standard mathematics library

math.h etc. These files are enclosed within < >


(2)

#define: helps in defining constant symbol.

Example:
#include<conio.h>
#define i 6
void main()
{ /* integer declaration */
int x, y;
/* Assignment statements */
x=7;
y= i + x;
/* output statement */
printf("%d\n", y);
getch();
}

output: 13

---------------------------------------------------------------------------------------Expression: An expression is a sequence of operands and operators that reduces to single value
Eg:

10+25 is an expression whose value is 35

Q8. Arithmetic Expression : An expression is a combination of variables, constants and operators written
according to the syntax of C language.
Every expression evaluates to a value of a certain type that can be assigned to a variable.
Precedence in Arithmetic Operators An arithmetic expression without parenthesis will be evaluated from left to right
using the rules of precedence of operators.
There are two distinct priority levels of arithmetic operators in C.

(1) High priority

*/%

(2) Low priority

+-

Rules for evaluation of an expression


When Parenthesis are used, the expressions within parenthesis assume highest priority.
Parenthesized sub expression left to right are evaluated.
If parenthesis are nested, the evaluation begins with the innermost sub expression.
The precedence rule is applied in determining the order of application of operators in evaluating sub expressions.
The associability rule is applied when two or more operators of the same precedence level appear in the sub
expression.

----------------------------------------------------Q22. Pointer: A pointer is a variable which contains the address in memory of another
variable. We can have a pointer to any variable type.

C Pointer is a variable that stores/points the address of another variable.


C Pointer is used to allocate memory dynamically i.e. at run time.
The variable might be any of the data type such as int, float, char, double, short
etc.

Syntax:

data_type *var_name;

Example : int *p;

char *p;

In the above example * is used to denote that p is pointer variable and not a
normal variable.

Key points to remember about pointers in C:

Normal variable stores the value whereas pointer variable stores the address of
the variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.

& symbol is used to get the address of the variable.


* symbol is used to get the value of the variable that the pointer is pointing to.
If pointer is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available
between these two pointers.

But, Pointer addition, multiplication, division are not allowed.


The size of any pointer is 2 byte (for 16 bit compiler).

Example program for pointer in C:


#include <stdio.h>
int main()
{
int *ptr, q;

q = 50;
/* address of q is assigned to ptr
*/
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}

Output: 50
-----------------------Example2:
#include<stdio.h>
#include<conio.h>
void main()
{
int a, *ptr;
a = 10;
ptr = &a;
clrscr();
printf("&a = %u\n",&a);
printf("a = %d\n",a);
printf("ptr = %d\n",ptr);
printf("&ptr = %u\n",&ptr);
printf("*ptr = %d\n",*ptr);
getch();
}
output:

why we use pointer ?


ans :

it is easy to create program using pointer

by using pointer we can process data at there memory level.

by using pointer we can access function variable declare outside


the function

pointer increase the speed of execution of program.

disadvantages of pointer

without any knowledge of pointer it is harmful for computer because with declaring beginning
address of pointer it will crash the system.

it is difficult to find errors in pointer.

by using pointer we can easily pass string data and array in function for process.

-----------------------------------------------------------------------------------

The unary or monadic operator & gives the ``address of a variable''.

The indirection or dereference operator * gives the ``contents of an object


pointed to by a pointer''.

------------------------------------------------------------------------Pointers:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, *ptr;
a = 10;
ptr = &a;
cout<<"&a "<<&a<<endl;
cout<<"a

"<<a<<endl;

cout<<"ptr " <<ptr<<endl;


cout<<"&ptr "<<&ptr<<endl;
cout<<"*ptr

"<<*ptr<<endl;

getch();
}
----------------------------#include<stdio.h>
#include<conio.h>
void main()
{
int a, *ptr;
a = 10;
ptr = &a;
clrscr();

printf("&a = %u\n",&a);
printf("a = %d\n",a);
printf("ptr = %d\n",ptr);
printf("&ptr = %u\n",&ptr);
printf("*ptr = %d\n",*ptr);

getch();
}

output:

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, *ptr;
ptr = &a;
*ptr = 25;
cout<<a;
getch();
}

-----------#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();

int a, *ptr;
ptr = &a;
*ptr = 10;
printf("%d",a);
getch();
}

output:25
-----------------------------------------#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,c, *ptr1,*ptr2;
a = 10,b = 20;
ptr1 = &a;
ptr2 = &b;
c = *ptr1 + *ptr2;
cout<<c;
getch();
}
----------------------//array of pointer
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int *a;

int b[10] = {1,2,3,4,5};


a = &b[0];
for(int i = 0;i<=4;i++)
{
cout<<*a;
a++;
}
getch();
}

-------------------//array of pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int *a,i;
int b[10] = {1,2,3,4,5};
a = &b[0];
clrscr();
for(i = 0;i<=4;i++)
{
printf("%d",*a);
a++;
}
getch();
}
----------------------

#include <stdio.h>
#include<conio.h>
swap (int *, int *);
main()
{
int a, b;
clrscr();
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore increment:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter increment:\n");
printf("\na = %d\n\nb = %d", a, b);
getch();
}

swap (int *x, int *y)


{
++*x;
++*y;
}
-----------------------------//passing pointer to function
#include<iostream.h>
#include<conio.h>
fun(int *,int *); // declaration
void main()
{
clrscr();

int a,b;
a = 1;
b = 2;

fun(&a,&b);

//call

getch();
}

int fun(int *a,int *b)


{
++ *a;
++ *b;
cout<<*a<<endl;
cout<<*b<<endl;
}
----------------------------#include<iostream.h>
#include<conio.h>
void main()
{
int *ptr=NULL;
cout<<*ptr;
getch();
}
---------------------------------------------------Q9. C Programming Pointers and Arrays
Arrays are closely related to pointers in C programming but the important difference between them is that, a
pointer variable can take different addresses as value whereas, in case of array it is fixed. This can be
demonstrated by an example:

#include <stdio.h>
int main(){
char c[4];
int i;
for(i=0;i<4;++i){
printf("Address of c[%d]=%x\n",i,&c[i]);
}
return 0;
}
Address
Address
Address
Address

of
of
of
of

c[0]=28ff44
c[1]=28ff45
c[2]=28ff46
c[3]=28ff47

Notice, that there is equal difference (difference of 1 byte) between any two consecutive elements of array.
Note: You may get different address of an array.
Relation between Arrays and Pointers
Consider and array:
int arr[4];
Relation between arrays and pointers
In arrays of C programming, name of the array always points to the first element of an array. Here, address
of first element of an array is &arr[0]. Also, arr represents the address of the pointer where it is pointing.
Hence, &arr[0] is equivalent to arr.
Also, value inside the address &arr[0] and address arr are equal. Value in address &arr[0] is arr[0] and value
in address arr is *arr. Hence, arr[0] is equivalent to *arr.
Similarly,
&a[1]
&a[2]
&a[3]
.
.
&a[i]

is equivalent to (a+1)
is equivalent to (a+2)
is equivalent to (a+1)

AND, a[1] is equivalent to *(a+1).


AND, a[2] is equivalent to *(a+2).
AND, a[3] is equivalent to *(a+3).

is equivalent to (a+i)

AND, a[i] is equivalent to *(a+i).

In C, you can declare an array and can use pointer to alter the data of an array.
//Program to find the sum of six numbers with arrays and pointers.
#include<stdio.h>
#include<conio.h>
void main(){
int i,a[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i){
scanf("%d",(a+i)); // (class+i) is equivalent to &class[i]
sum += *(a+i); // *(class+i) is equivalent to class[i]
}

printf("Sum=%d",sum);
getch();
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum=21

---------------------------1. C Constant Pointer and Pointer to Constant


we should understand the difference between constant pointer and pointer to constant.

C Constant pointer
A pointer is said to be constant pointer when the address its pointing to cannot be changed.
Lets take an example :
char ch, c;
char *ptr = &ch
ptr = &c

In the above example we defined two characters (ch and c) and a character pointer ptr. First, the pointer
ptr contained the address of ch and in the next line it contained the address of c. In other words, we can
say that Initially ptr pointed to ch and then it pointed to c.
But in case of a constant pointer, once a pointer holds an address, it cannot change it. This means a constant
pointer, if already pointing to an address, cannot point to a new address.
If we see the example above, then if ptr would have been a constant pointer, then the third line would have
not been valid.
A constant pointer is declared as :
<type-of-pointer> *const <name-of-pointer>

For example :
#include<stdio.h>
int main(void)
{
char ch = 'c';
char c = 'a';
char *const ptr = &ch; // A constant pointer
ptr = &c; // Trying to assign new address to a constant pointer. WRONG!!!!
}

return 0;

When the code above is compiled, compiler gives the following error :

Cannot modify a const object

So we see that, as expected, compiler throws an error since we tried to change the address held by constant
pointer.

C Pointer to Constant
this type of pointer cannot change the value at the address pointed by it.
Lets understand this through an example :
char ch = 'c';
char *ptr = &ch
*ptr = 'a';

In the above example, we used a character pointer ptr that points to character ch. In the last line, we
change the value at address pointer by ptr. But if this would have been a pointer to a constant, then the last
line would have been invalid because a pointer to a constant cannot change the value at the address its
pointing to.
A pointer to a constant is declared as :
const <type-of-pointer> *<name-of-pointer>;

For example :
#include<stdio.h>
int main(void)
{
char ch = 'c';
const char *ptr = &ch; // A constant pointer 'ptr' pointing to 'ch'
*ptr = 'a';// WRONG!!! Cannot change the value at address pointed by 'ptr'.
}

return 0;

When the above code was compiled, compiler gave the following error :
Cannot modify a const object

So now we know the reason behind the error above ie we cannot change the value pointed to by a constant
pointer.

2. C Pointer to Pointer
its a special variable that can store the address of an other variable. Then the other variable can very well be
a pointer. This means that its perfectly legal for a pointer to be pointing to another pointer.
Lets suppose we have a pointer p1 that points to yet another pointer p2 that points to a character ch. In
memory, the three variables can be visualized as :

So we can see that in memory, pointer p1 holds the address of pointer p2. Pointer p2 holds the address of
character ch.
So p2 is pointer to character ch, while p1 is pointer to p2 or we can also say that p2 is a pointer to
pointer to character ch.
Now, in code p2 can be declared as :
char *p2 = &ch;

But p1 is declared as :
char **p1 = &p2;

So we see that p1 is a double pointer (ie pointer to a pointer to a character) and hence the two *s in
declaration.
Now,

p1 is the address of p2 ie 5000


*p1 is the value held by p2 ie 8000
**p1 is the value at 8000 ie c

I think that should pretty much clear the concept, lets take a small example :
#include<stdio.h>
int main(void)
{
char **ptr = NULL;
char *p = NULL;
char c = 'd';
p = &c;
ptr = &p;
printf("\n c = [%c]\n",c);
printf("\n *p = [%c]\n",*p);
printf("\n **ptr = [%c]\n",**ptr);
return 0;

Here is the output :


$ ./doubleptr
c = [d]
*p = [d]
**ptr = [d]

3. C Array of Pointers
Just like array of integers or characters, there can be array of pointers too.
An array of pointers can be declared as :

<type> *<name>[<number-of-elements];

For example :
char *ptr[3];

The above line declares an array of three character pointers.


Lets take a working example :
#include<stdio.h>
#include<conio.h>
void main(void)
{
char *p1 = "Himanshu";
char *p2 = "Arora";
char *p3 = "India";
char *arr[3];
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;
printf("\n p1 = [%s] \n",p1);
printf("\n p2 = [%s] \n",p2);
printf("\n p3 = [%s] \n",p3);
printf("\n arr[0] = [%s] \n",arr[0]);
printf("\n arr[1] = [%s] \n",arr[1]);
printf("\n arr[2] = [%s] \n",arr[2]);
}

getch();

In the above code, we took three pointers pointing to three strings. Then we declared an array that can
contain three pointers. We assigned the pointers p1, p2 and p3 to the 0,1 and 2 index of array. Lets see
the output :
Output:
p1 = [Himanshu]
p2 = [Arora]
p3 = [India]
arr[0] = [Himanshu]
arr[1] = [Arora]
arr[2] = [India]

So we see that array now holds the address of strings.

4. C Function Pointers
Just like pointer to characters, integers etc, we can have pointers to functions.
A function pointer can be declared as :
<return type of function> (*<name of pointer>) (type of function arguments)

For example :
int (*fptr)(int, int)

The above line declares a function pointer fptr that can point to a function whose return type is int and
takes two integers as arguments.
Lets take a working example :

#include<stdio.h>
int func (int a, int b)
{
printf("\n a = %d\n",a);
printf("\n b = %d\n",b);
return 0;
}
int main(void)
{
int(*fptr)(int,int); // Function pointer
fptr = func; // Assign address to function pointer
func(2,3);
fptr(2,3);
return 0;
}

In the above example, we defined a function func that takes two integers as inputs and returns an integer. In
the main() function, we declare a function pointer fptr and then assign value to it. Note that, name of the
function can be treated as starting address of the function so we can assign the address of function to
function pointer using functions name. Lets see the output :
$ ./fptr
a = 2
b = 3
a = 2
b = 3

So from the output we see that calling the function through function pointer produces the same output as
calling the function from its name.

----------------------------------------------------------------------------Q10. Pass array to function as argument


In C programming, a single array element or an entire array can be passed to a function. Also, both onedimensional and multi-dimensional array can be passed to function as argument.
Passing One-dimensional Array In Function
C program to pass a single element of an array to function
#include <stdio.h>
void display(int a)
{
printf("%d",a);
}
int main(){
int c[]={2,3,4};
display(c[2]); //Passing array element c[2] only.
return 0;
}
Output

4
While passing arrays to the argument, the name of the array is passed as an argument(,i.e, starting address of
memory area is passed as argument).

----------------------------------------------------------Q11. Passing Multi-dimensional Arrays to Function


To pass two-dimensional array to a function as an argument, starting address of memory area reserved is
passed as in one dimensional array
Example to pass two-dimensional arrays to function
#include
void Function(int c[2][2]);
int main(){
int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
scanf("%d",&c[i][j]);
}
Function(c); /* passing multi-dimensional array to function */
return 0;
}
void Function(int c[2][2]){
/* Instead to above line, void Function(int c[][2]){ is also valid */
int i,j;
printf("Displaying:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d\n",c[i][j]);
}
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
------------------------------------------------------------------------------------

Q12. Pointers and Functions - Call by Reference


When, argument is passed using pointer, address of the memory location is passed instead of value.
Example of Pointer And Functions
Program to swap two number using call by reference.
/* C Program to swap two numbers using pointers and function. */
#include <stdio.h>

void swap(int *a,int *b);


int main(){
int num1=5,num2=10;
swap(&num1,&num2); /* address of num1 and num2 is passed to swap
function */
printf("Number1 = %d\n",num1);
printf("Number2 = %d",num2);
return 0;
}
void swap(int *a,int *b){ /* pointer a and b points to address of num1
and num2 respectively */
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output
Number1 = 10
Number2 = 5
Explanation
The address of memory location num1 and num2 are passed to function and the pointers *a and *b accept
those values. So, the pointer a and b points to address of num1 and num2 respectively. When, the value of
pointer are changed, the value in memory location also changed correspondingly. Hence, change made to *a
and *b was reflected in num1 and num2 in main function.
This technique is known as call by reference in C programming.
------------------------------------------------------------------------------

Q13. Dynamic Memory Allocation


The exact size of array is unknown untill the compile time,i.e., time when a compier compiles code written
in a programming language into a executable form. The size of array you have declared initially can be
sometimes insufficient and sometimes more than required. Dynamic memory allocation allows a program to
obtain more memory space, while running or to release space when no space is required.
Although, C language inherently does not has any technique to allocated memory dynamically, there are 4
library functions under "stdlib.h" for dynamic memory allocation.
Function
malloc()
calloc()
free()
realloc()

Use of Function
Allocates requested size of bytes and returns a pointer first byte of allocated space
Allocates space for an array elements, initializes to zero and then returns a pointer
to memory
dellocate the previously allocated space
Change the size of previously allocated space

(1) malloc( ): The name malloc stands for "memory allocation". The function malloc() reserves a block of
memory of specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax of malloc( ):
ptr=(cast-type*)malloc(byte-size)

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of
byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.

(2) calloc( ): The name calloc stands for "contiguous allocation". The only difference between malloc()
and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks
of memory each of same size and sets all bytes to zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4
bytes.

(3) free(): Dynamically allocated memory with either calloc() or malloc() does not get return on its own.
The programmer must use free() explicitly to release space.
syntax of free()
free(ptr);
This statement cause the space in memory pointer by ptr to be deallocated.
Examples of calloc() and malloc()
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);

}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}

(4) realloc( ) : If the previously allocated memory is insufficient or more than sufficient. Then, you can
change memory size previously allocated using realloc().
Syntax of realloc()
ptr=realloc(ptr,newsize);
Here, ptr is reallocated with size of newsize.
#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)

printf("%u\t",ptr+i);
return 0;
}

What is the difference between calloc() and malloc() ?


Calloc
Argument

calloc() needs two arguments.

Contents calloc() initializes the


of
allocated memory to ZERO
allocated
memory

Return
value

Syntax

calloc() allocates a

memory area, the length will


be the product of its
parameters. calloc fills the
memory with ZERO's and returns
a pointer to first byte. If it
fails to locate enough space
it returns a NULL pointer.

Syntax:
ptr_var=(cast_type
*)calloc(no_of_blocks ,
size_of_each_block);
i.e. ptr_var=(type
*)calloc(n,s);

Malloc
Malloc() takes a single
argument(memory required in bytes)
malloc() does not initialize the
memory allocated(malloc does not
touch the contents of the allocated
block of memory, which means it
contains garbage values.)
malloc() allocates a single
block of memory of REQUSTED SIZE
and returns a pointer to first
byte. If it fails to locate
requsted amount of memory it
returns a null pointer.

Syntax: ptr_var=(cast_type
*)malloc(Size_in_bytes);

--------------------Q14. Difference between array and link list


1. Linked lists do not need contiguous blocks of memory; extremely large data sets stored in an array
might not be able to fit in memory.
2. Linked list storage does not need to be preallocated (again, due to arrays needing contiguous memory
blocks).
3. Inserting or removing an element into a linked list requires one data update, inserting or removing an
element into an array requires n (all elements after the modified index need to be shifted).

DIFFERENCE BETWEEN LINKED LIST AND ARRAY IN DATA STRUCTURE

LINKED LIST:1)
2)
3)
4)

Can quickly insert and delete items in linked list.


You simply rerrange those pointers that are affected by the change in linked list.
Linked list are very difficulty to sort.
Can not immediately locate the desires element.need to traverse the whole list to reach that element.

5)
6)
7)

Linked list are not constrained to be stored in adjacent locations.


Basically 3 types are there :- singly,doubly,and circular.
Linked list is a list whose order is given by links from one item to the next.

ARRAY:1)
2)
3)
4)
5)
6)
7)

Can not do so quickly as in linked list.


Inserting and deleting items in an array requires you to either make room for new item or fill the hole left
by deleting an item.
They are not difficulty to sort.
Easy to locate the desired element.
The element of an array occupy contiguous memory locations.
Basically two types are there :- one dimention, two dimention.
An array is a group of related data items that share a common name.

List out differences between arrays and linked list


The difference between arrays and linked lists are:
- Arrays are linear data structures. Linked lists are linear and non-linear data structures.
- Linked lists are linear for accessing, and non-linear for storing in memory
- Array has homogenous values. And each element is independent of each other positions. Each node in the linked list is connected
with its previous node which is a pointer to the node.
- Array elements can be modified easily by identifying the index value. It is a complex process for modifying the node in a linked list.
- Array elements can not be added, deleted once it is declared. The nodes in the linked list can be added and deleted from the
list.

Both Arrays and Linked List can be used to store linear data of similar types, but they both have some advantages and
disadvantages over each other.
Following are the points in favour of Linked Lists.
(1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally,
the allocated memory is equal to the upper limit irrespective of the usage, and in practical uses, upper limit is rarely reached.
(2) Inserting a new element in an array of elements is expensive, because room has to be created for the new elements and
to create room existing elements have to shifted.
For example, suppose we maintain a sorted list of IDs in an array id[].
id[] = [1000, 1010, 1050, 2000, 2040, .....].
And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000
(excluding 1000).
Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[],
everything after 1010 has to be moved.

So Linked list provides following two advantages over arrays


1) Dynamic size
2) Ease of insertion/deletion
Linked lists have following drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do
binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.
3) Arrays have better cache locality that can make a pretty big difference in performance.

--------------------------------------------------------------------------------------Q16. Increment and Decrement operators:


Increment and decrement operators are unary operators that add or subtract one from
their operand, respectively.
the increment operator is written as ++ and the decrement operator is written as --.
++

adds 1 to operand and -- subtracts 1 to operand respectively. For example:

Let a=5
a++; //a
a--; //a
++a; //a
--a; //a

becomes
becomes
becomes
becomes

6
5
6
5

Example 2
int
int

x;
y;

// Increment operators
x = 1;
y = ++x;
// x is now 2, y is also 2
y = x++;
// x is now 3, y is 2
// Decrement operators
x = 3;
y = x--;
// x is now 2, y is 3
y = --x;
// x is now 1, y is also 1
x = x+1;

x = x+1;

is the same as

can be written as

x++;

++x; // prefix form

And similarly:
x = x-1;

x = x+1;
can be written as
x++; // postfix form

is the same as
x--;

Increment operators (++)

The increment operator increases the value of its operand by 1

Increment operator are two types as follows :


1.
Post increment
2.
Pre increment

Decrement operators ( -- )

decrement operator decreases the value of its modifiable arithmetic operand by 1.

As like Increment operators, decrement


operators are also two type as :
1.
Post decrement
2.
Pre decrement

x = 5
x = x+1
x = 6

x = 5
++x
x = 6

x = 5
x++
x=5

In above program u notice that value of x


increase to one in all three expression but
after the increasing one, the final value of x
in not same, third box result is differ to
another two boxes.
++ and -- operators are Unary operators.
Post
increment
or
decrement
are
lowest
precedence so it is solve at the end of program.
Hence above program in third box first value of
x is print i.e. 5 after, it is increase.
Unary operators are solve right to left.
Difference between ++ and -- operator as postfix and prefix
pre-increment and pre-decrement operators increments or decrements the value of the object and returns a
reference to the result.

post-increment and post-decrement creates a copy of the object, increments or decrements the value of the
object and returns the copy from before the increment or decrement.

S.no Operator type Operator


Description
++i
1 Pre increment
Value of i is incremented before assigning it to variable i.
2 Post-increment
3 Pre decrement

4 Post_decrement

i++
i

Value of i is incremented after assigning it to variable i.


(The operators in postfix expressions have left-to-right associativity.)
Value of i is decremented before assigning it to variable i
(Pre-decrement operator is used to decrement the value of variable before
using in the expression.)
Value of i is decremented after assigning it to variable i.
(Post-decrement operator is used to decrement the value of variable
immediatly after executing expression completely in which post decrement is
used. In the Post-decrement old value is first used in a expression and then
old value will be decrement by 1)

Example 1:
#include<stdio.h>
void main()
{
int a,b,x=10,y=10;
a = x--;
b = --y;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
}

Output :
Value of a : 10
Value of b : 9

Example 2:
#include <stdio.h>
int main()
{
int c=2,d=2;
printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.
printf("%d",++c);
//this statement increments 1 to c then, only c is displayed.
return 0;
}

Output
2
4

Example 3:

//Example for increment operators


#include <stdio.h>
int main()
{
int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}

Output:
123456789

Example 4:
//Example for decrement operators
#include <stdio.h>
int main()
{
int i=20;
while(i>10)
{
printf("%d ",i);
i--;
}
}

Output:
20 19 18 17 16 15 14 13 12 11

Example 5:
Example program for pre increment operators in C:
//Example for increment operators
#include <stdio.h>
int main()
{
int i=0;
while(++i < 5 )
{
printf("%d ",i);
}
return 0;
}

Output: 1 2 3 4
------------------------------------------------Limitations of increment and decrement operators:
Decrement Operator should not be used on Constants.

We cannot use decrement operator in the following case -

b = --5;

Or
b = 5--;

Q.1 Solve the expression in C language


compiler ,assuming x,z are integer variables:
z = x++ + x++
where x=7
Ans.
stepwise evaluation of this expression is shown
below :
z = x++ + x++ + ++x
//post increment of x=2
z = x + x + ++x
//++x increase the value of x one so x=8
/*Now all pre and post increment/decrement are
solved so we write the the expression in normal
mathematical expression*/
z = x + x + x
//put the current value of x i.e. 8
z = 8 + 8 + 8
z = 24
syntax : x=current value-post increment/decrement

so x = 8 + 2
x = 10
Q.2 Solve the following expression :
z = ++x + y-- - ++y - x-- - x-- - ++y - x-where
x = 7
y = -3
Ans.
z=++x + y-- - ++y - x-- - x-- - ++y - x-/* post decrement of x=3 and
post decrement of y=1 */

z= ++x + y - ++y - x - x - ++y - x


/* its unary operator so we solve it from
right to left*/
z=++x + y - ++y - x - x - y - x
//now y=-3+1=-2
z=++x + y - y - x - x - y - x
//now y=-2+1=-1
z=x + y - y - x - x - y - x
//now x=7+1=8
/*now all increment and decrement operators
all solved so we put the current value of x
and y.*/
z= 8 + (-1) - (-1) -8 - 8 - (-1) - 8
z= 8

z= - 16
z= -15

x=8-3=5
y=-1-1=-2
Related some increment or decrement operators
exercise:
Q.3 solve the following equations:
z = x++ + ++y - x-- + --y
where x = 7 and
y=9
hint:(For your cross-checking, answer is x=7, y=9 and z=18).
Q.4 solve the following equations:
z = x++ * y++ / ++x - --y % x++
where x = 5 and
y=2
hint:(For your cross-checking, answer is x=8, y=2 and z=0).

-------------------------------------------------------------------------------Q.3 answer with explanation :


z = x++ + ++y - x-- + --y
where x = 7 and
y=9
Ans:
post decrement of x = 1
post increment of x = 1
z = x + ++y - x + --y
z = x + ++y - x + y // now y = 9-1 = 8
z=x+y-x+y
// now y = 8+1 = 9
// now put the value of x and y
z=7+9-7+9
z=9+9
z = 18
Hence, our final answer will be:
x=7-1+1=7
y=9
z = 18

----------------------------------------------When you compile and execute the above prog ram it produces the following result:
C++
#include <iostream.h>
#include <conio.h>
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c;
c = a & b;

/* 12 = 0000 1100 */

cout<<"a & b "<<c<<endl;


c = a | b;

/* 61 = 0011 1101 */

cout<<"a | b "<<c<<endl;
c=a^b;

/* 49 = 0011 0001 */

cout<<"a ^ b "<<c<<endl;
c = ~a; /*-61 = 1100 0011 */
cout<<"~a "<<c<<endl;
c = a << 2; /* 240 = 1111 0000 */
cout<<"a<<2 "<<c<<endl;
c = a >> 2; /* 15 = 0000 1111 */
cout<<"a >>2 "<<c<<endl;
getch();
}
output:
a & b 12
a | b 61
a ^ b 49
~a -61
a<<2 240
a >>2 15
--------------------------------------------

Q18. Operators Precedence in C


There are distinct levels of precedence and an operator may belong to one of these levels.
The operators of higher precedence are evaluated first. This is known as associativity property of an
operator.
Certain operators have higher precedence than others; for example, the multiplication operator has higher
precedence than the addition operator.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so
it first gets multiplied with 3*2 and then adds into 7.
Example1
Examples
x+y*z/2+p
x + (y * z) / 2 + p
x + ((y * z) / 2) + p
(x + ((y * z) / 2)) + p
((x + ((y * z) / 2)) + p)

Example2
x+y-z/2*p
(x + y) - z / 2 * p
(x + y) - (z / 2) * p
(x + y) - ((z / 2) * p)
((x + y) - ((z / 2) * p))
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence operators will be evaluated first.

Operator Type
Primary Expression Operators
Unary Operators

Binary Operators

Ternary Operator
Assignment Operators
Comma

Operator Precedence Chart


Operator
() [] . -> expr++ expr-* & + - ! ~ ++expr --expr (typecast) sizeof
* / %
+ >> <<
< > <= >=
== !=
&
^
|
&&
||
?:
= += -= *= /= %= >>= <<= &= ^= |=
,

Associativity
left-to-right
right-to-left

left-to-right

right-to-left
right-to-left
left-to-right

Category

Operator

Associativity

Postfix

() [] . -> expr++ expr--

Left to right

Unary

* & + - ! ~ ++expr --expr (typecast) sizeof

Right to left

Multiplicative

*/%

Left to right

Additive

+-

Left to right

Shift

<< >>

Left to right

Relational

< <= > >=

Left to right

Equality

== !=

Left to right

Bitwise AND

&

Left to right

Bitwise XOR

Left to right

Bitwise OR

Left to right

Logical AND

&&

Left to right

Logical OR

||

Left to right

Conditional

?:

Right to left

Assignment

= += -= *= /= %=>>= <<= &= ^= |=

Right to left

Comma

Left to right

Example
Try the following example to understand the operator precedence available in C programming language:

#include <stdio.h>
main()
{
int
int
int
int
int

a =
b =
c =
d =
e;

20;
10;
15;
5;

e = (a + b) * c / d;
// ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n",

e );

e = ((a + b) * c) / d;
// (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" ,
e = (a + b) * (c / d);
// (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n",
e = a + (b * c) / d;
// 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" ,
}

e );
e );
e );

return 0;

When you compile and execute the above program it produces the following result:
Value
Value
Value
Value

of
of
of
of

(a + b) * c / d is : 90
((a + b) * c) / d is : 90
(a + b) * (c / d) is : 90
a + (b * c) / d is : 50

------------------------------------------------------------

Q21. C Programming Multidimensional Arrays


C programming language allows programmer to create arrays of arrays known as multidimensional arrays.
For example:
float a[2][6];

Here, a is an array of two dimension, which is an example of multidimensional array. This array has 2 rows
and 6 columns
For better understanding of multidimensional arrays, array elements of above example can be thinked of as
below:

Initialization of Multidimensional Arrays


In C, multidimensional arrays can be initialized in different number of ways.
int c[2][3]={{1,3,0}, {-1,5,9}};
OR
int c[][3]={{1,3,0}, {-1,5,9}};
OR
int c[2][3]={1,3,0,-1,5,9};

Initialization Of three-dimensional Array


double cprogram[3][2][4]={
{{-0.1, 0.22, 0.3, 4.3}, {2.3, 4.7, -0.9, 2}},
{{0.9, 3.6, 4.5, 4}, {1.2, 2.4, 0.22, -1}},
{{8.2, 3.12, 34.2, 0.1}, {2.1, 3.2, 4.3, -2.0}}
};

Suppose there is a multidimensional array arr[i][j][k][m]. Then this array can hold i*j*k*m numbers of
data.
Similarly, the array of any dimension can be initialized in C programming.
---------------------------------------------------------------------------------------------------------------for loop
for(initialization;condtion;increment/decrement)
{
}

-----------------#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
for(int i = 0 ; i<=10 ; i++)
printf("%d",i);
getch();
}

output:
0
1
2
3
4
5
6
7
8
9
10

----------------------Q19 C - STORAGE CLASSES


A storag e class defines the scope (visibility) and life-time of variables and/or functions within a C Prog ram.
T hese specifiers precede the type that they modify. T here are the following storag e classes, which can be
used in a C Prog ram
auto
reg ister
static
extern

The auto Storag e Class


T he auto storag e class is the default storag e class for all local variables.
{
int mount;
auto int month;
}

The example above defines two variables with the same storag e class, auto can only be used within
functions,
i.e., local variables.

The register Storag e Class

T he reg ister storag e class is used to define local variables that should be stored in a reg ister instead of
RAM.
This means that the variable has a maximum size equal to the reg ister size (usually one word) and can't
have the unary '&' operator applied to it (as it does not have a memory location).
{
register int miles;
}

The register should only be used for variables that require quick access such as counters. It should also be
noted that defining 'reg ister' does not mean that the variable will be stored in a register. It means that it
MIGHT be stored in a register depending on hardware and implementation restrictions.

The static Storag e Class

The static storag e class instructs the compiler to keep a local variable in existence during the life-time of
the prog ram instead of creating and destroying it each time it comes into and goes out of scope. There fore,
making local variables static allows them to maintain their values between function calls. The static
modifier may also be applied to global variables. When this is done, it causes that variable's scope to be
restricted to the file in which it is declared.
In C prog ramming , when static is used on a class data member, it causes only one copy of that member
to be shared by all objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main()
{
while(count--)
{
func();
}
return 0;
} /* function definition */
void func( void )
{
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}

You may not understand this example at this time because I have used function and global variables,
which I have not explained so far. So for now let us proceed even if you do not understand it completely.
When the above code is compiled and executed, it produces the following result:
i
i
i
i
i

is
is
is
is
is

6 and count is 4
7 and count is 3
8 and count is 2
9 and count is 1
10 and count is 0

The extern Storag e Class


T he extern storage class is used to give a reference of a global variable that is visible to ALL the program
files.

When you use 'extern', the variable cannot be initialized as all it does is point the variable name at a storage
location that has been previously defined.
When you have multiple files and you define a global variable or function, which will be used in other files
also, then extern will be used in another file to g ive reference of defined variable or function. Just for
understanding ,
extern is used to declare a global variable or function in another file.
T he extern modifier is most commonly used when there are two or more files sharing the same global
variables or functions as explained below.
Example 1:
#include<stdio.h>
#include<conio.h>
void main()
{
extern int a; //local variable
clrscr();
printf("%d",a);
getch();
}
int a = 1; //initialization
-----------------------------------Example 2:
First File: main.c
#include <stdio.h>
int count ;
extern void write_extern();
main()
{
count = 5;
write_extern();
}

Sec ond File: support.c


#include <stdio.h>
extern int count;
void write_extern(void)
{
printf("count is %d\n", count);
}

Here, extern keyword is being used to declare count in the second file where as it has its definition in the
first file, main.c. Now, compile these two files as follows:
$gcc main.c support.c

T his will produce a.out executable prog ram, when this prog ram is executed, it produces the following
result:
5

-------------------------------C Programming Functions: In programming, a function is a segment that groups code to perform a
specific task. A C program has at least one function main( ). Without main() function, there is
technically no C program.
Types of C functions : Basically, there are two types of functions in C on basis of whether it is
defined by user or not.

Library function (in-built function)


User defined function

(1) Library function : Library functions are the in-built function in C programming system. For example:
1. main() : The execution of every C program starts from this main() function.

2. printf(): prinf() is used for displaying output in C.


3. scanf() : scanf() is used for taking input in C.

User defined function : C allows programmer to define their own function according to their requirement.
These types of functions are known as user-defined functions.

How user-defined function works in C Programming?


#include <stdio.h>
void function_name()
{
................
................
}
int main()
{
...........
...........
function_name();
...........
...........
}

As mentioned earlier, every C program begins from main() and program starts executing the codes inside
main() function. When the control of program reaches to function_name() inside main() function. The
control of program jumps to void function_name() and executes the codes inside it. When all the codes
inside that user-defined function are executed, control of the program jumps to the statement just after
function_name() from where it is called..

Advantages of user defined functions


1. User defined functions helps to decompose the large program into small segments which makes
programmar easy to understand, maintain and debug.
2. If repeated code occurs in a program. Function can be used to include those codes and execute when
needed by calling that function.
3. Programmer working on large project can divide the workload by making different functions.
1) Call by Value:-when we call a Function and if a function can accept the Arguments from the
Called Function, Then we must have to Supply some Arguments to the Function. So that the
Arguments those are passed to that function just contains the values from the variables but not an
Actual Address of the variable.

So that generally when we call a Function then we will just pass the variables or the Arguments and
we doesnt Pass the Address of Variables , So that the function will never effects on the Values or
on the variables. So Call by value is just the Concept in which you must have to Remember that the
values those are Passed to the Functions will never effect the Actual Values those are Stored into
the variables.

2) Call By Reference :-When a function is called by the reference then the values those are
passed in the calling functions are affected when they are passed by Reference Means they change
their value when they passed by the References. In the Call by Reference we pass the Address of
the variables whose Arguments are also Send. So that when we use the Reference then, we pass the
Address the Variables.

When we pass the Address of variables to the Arguments then a Function may effect on the
Variables. Means When a Function will Change the Values then the values of Variables gets
Automatically Changed. And When a Function performs Some Operation on the Passed values,
then this will also effect on the Actual Values.

CONTROL STATEMENTS
When we run a program,the statements are executed in the order in which they appear in the program. Also
each statement is executed only once. But in many cases we may need a statement or a set of statements to
be executed a fixed no of times or until a condition is satisfied. Also we may want to skip some statements
based on testing a condition. For all these we use control statements.
Control statements are of two types branching and looping.

BRANCHING
It is to execute one of several possible options depending on the outcome of a logical test ,which is
carried at some particular point within a program.
LOOPING
It is to execute a group of instructions repeatedly, a fixed no of times or until a specified condition is
satisfied.

BRANCHING
1. if else statement : It is used to carry out one of the two possible actions depending on the
outcome of a logical test. The else portion is optional.
The syntax is:
If (expression) statement1 [if there is no else part]
Or
If (expression)
Statement 1
else
Statement 2

Here expression is a logical expression enclosed in parenthesis. if expression is true ,statement 1 or


statement 2 is a group of statements ,they are written as a block using the braces { }
Example:

if(x<0) printf(\n x is negative);


if(x<0)
printf(\n x is negative);
else
printf(\n x is non negative);
if(x<0)
{
x=-x;
s=sqrt(x);
}
else
s=sqrt(x);

2. nested if statement : Within an if block or else block another if else statement can come. Such
statements are called nested if statements.

The syntax is
If (e1)
s1
if (e2)
s2
else
s3
else

Ladder if statement: In order to create a situation in which one of several courses of action is
executed we use ladder if statements.
The syntax is
If (e1) s1
else if (e2) s2
else if (e3) s3
.
else sn
Example:

if(mark>=90) printf(\n excellent);


else if(mark>=80) printf(\n very good);
else if(mark>=70) printf(\n good);
else if(mark>=60) printf(\n average);
else
printf(\n to be improved);

SWITCH STATEMENT
It is used to execute a particular group of statements to be chosen from several available options.
The selection is based on the current value of an expression with the switch statement.
The syntax is:
switch(expression)
{
case value1:
s1
break;
case value 2:
s2
break;
.
..
default:
sn
}

All the option are embedded in the two braces { }.Within the block each group is written after the
label case followed by the value of the expression and a colon. Each group ends with break

statement. The last may be labeled default. This is to avoid error and to execute the group of
statements in default if the value of the expression does not match value1, value2,..

LOOPING :
1. The while statement
This is to carry out a set of statements to be executed repeatedly until some condition is satisfied.
The syntax is:
While (expression) statement

The statement is executed so long as the expression is true. Statement can be simple or compound.
Example 1:

#include<stdio.h>
while(n > 0)
{
printf("\n");
n = n - 1;
}

Example 2:

#include<stdio.h>
main()
{
int i=1;
while(x<=10)
{
printf(%d,i);
++i;
}
}

2. do while statement: This is also to carry out a set of statements to be executed repeatedly so long
as a condition is true.
The syntax is:
do statement while(expression)
Example:

#include<stdio.h>
main()
{
int i=1;
do
{
printf(%d,i);
++i;
}while(i<=10);

}
THE DIFFERENCE BETWEEN while loop AND do while loop:
1) In the while loop the condition is tested in the beginning whereas in the other case it is done at
the end.
2) In while loop the statements in the loop are executed only if the condition is true. whereas in do
while loop even if the condition is not true the statements are executed at least once.

3. for loop
It is the most commonly used looping statement in C.
The general form is
For(expression1;expression2;expression3)statement

Here expression1 is to initialize some parameter that controls the looping


action.expression2 is a condition and it must be true to carry out the
action.expression3 is a unary expression or an assignment expression.
Example:

#include<stdio.h>
main()
{
int i;
for(i=1;i<=10;++i)
printf(%d,i);
}

Here the program prints i starting from 1 to 10. First i is assigned the value 1 and then it checks
whether i<=10 If so i is printed and then i is increased by one. It continues until i<=10.
An example for finding the average of 10 numbers;
#include<stdio.h>
main()
{
int i;
float x,avg=0;
for(i=1;i<=10;++i)
{
scanf(%f,&x);
avg += x;
}
avg /= 10;
printf(\n average=%f,avg);
}

Note: Within a loop another for loop can come


Example : for(i=1;i<=10;++i)
for(j=1;j<=10;++j);

The break statement:


The break statement is used to terminate4 loop or to exit from a
switch. It is used in for, while, do-while and switch statement.
The syntax is break;
Example 1: A program to read the sum of positive numbers only
#include<stdio.h>
main()
{
int x, sum=0;
int n=1;
while(n<=10)
{
scanf(%d,&x);
if(x<0) break;
sum+=x;
}
printf(%d,sum);

Example 2 :A program for printing prime numbers between 1 and 100:


#include <stdio.h>
#include <math.h>
main()
{
int i, j;
printf("%d\n", 2);
for(i = 3; i <= 100; i = i + 1)
{
for(j = 2; j < i; j = j + 1)
{
if(i % j == 0)
break;
if(j > sqrt(i))
{
printf("%d\n", i);
break;
}
}
}
return 0;
}

Here while loop breaks if the input for x is ve.

The continue statement


It is used to bypass the remainder of the current pass through a loop. The loop does not terminate
when continue statement is encountered, but statements after continue are skipped and proceeds to
the next pass through the loop.
In the above example of summing up the non-negative numbers when a negative value is input, it
breaks and the execution of the loop ends. In case if we want to sum 10 nonnegative numbers, we
can use continue instead of break
Example :

#include<stdio.h>
main()
{
int x, sum=0, n=0;
while(n<10)
{
scanf(%d,x);
if(x<0) continue;
sum+=x;
++n;
}
printf(%d,sum);
}

GO TO statement:
It is used to alter the normal sequence of program execution by transferring control to some other part of the
program .
The syntax is
goto label ;

Example :
#include<stdio.h>
main( )
{

int n=1,x,sum=0;
while(n<=10)
{
scanf(%d ,&x);
if(x<0)goto error;
sum+=x;
++n;
}
error:
printf(\n the number is non negative);

--------------------------------------------------Structure: A structure in C is a collection of items of different types. The


structures

is

main

use

of

to conveniently treat such collection as a unit. For example:

struct employee
{
char name[50];
char sex;
float salary;
};
The following declaration defines a variable xyz of struct type.
struct empolyee xyz;

Variables

can

also

be

declared between }

and ;

of

struct declaration, i.e.:

struct employee
{
char name[50];
char sex;
float salary;
} xyz;

struct variable can be pre-initialized at declaration:


struct employee
{
char name[50];
char sex;
float salary;
} xyz = {"john", m, 20000.50};

To access a member (or field) of a struct, C provides dot (.) operator. For example,
xyz . sex ; xyz . salary;

xyz . name

---------------------------------------------------User Defined Data Types


Enumerated Types : It contains a list of constants that can be addressed in integer values.

We can declare types as follows.


enum days {MONDAY, TUESDAY, ...,

SUNDAY};

Variables of enumerated type are defined as follows:


enum days week1, week2;
where week1 and week2 are variables
#include <stdio.h>
main()
{
enum Color {RED=5, YELLOW, GREEN=4,
BLUE};
printf("RED = %d\n", RED);
printf("YELLOW = %d\n", YELLOW);
printf("GREEN = %d\n", GREEN);
printf("BLUE = %d\n", BLUE);
}
Output:
RED = 5
YELLOW = 6
GREEN = 4
BLUE = 5
-------------------------------Type def : Defined as type definition by using typedef we can create new datatype.
Typedef type data _ame;
Type ---- datatype
Dataname---- Name of that type.
Type def program :
# include < stdio.h>
main ( )
{
typedef int amt ;

amt Rupees = 20;


printf ( Rupees %d, Rupees);
}
Output : Rupees 20.

Type Definitions
We can give a name to enum colors as COLOR
by using typedef as follows:
typedef enum colors COLOR;
COLOR x, y, z;
x = RED;
y = BLUE;
Now, every time the compiler sees COLOR, it'll
know that you mean enum colors.
We can also define user named data type for
even existing primitive types:
typedef int integer;
typedef bool boolean;
typedef can also be used with structures to
creates a new type.
Example:
typedef struct employee
{

char name[50];

char sex;
float salary;
} emp_type xyz ={"john", m, 2000.50};
emp_type is new data type of struct employee
type and can be initialized as usual:
It can be now used for declaring variables similar
to primitive data types are used.
Examples:
emp_type x, y, z

- Here x, y and z are variables of type


emp_type which are structures themselves.
emp_type emp[100];
- Here emp is an array of 100 elements with
each element of type emp_type.
Both declarations given below are same.
struct employee x, y, z;
emp_type x, y, z;
------------------------------------Functions and Arrays
Single dimensional arrays can be passed to
functions as follows:
float findaverage(int size,float list[])
{
int i;
float sum=0.0;
for (i=0; i<size; i++) sum+=list[i];
return(sum/size);
}

Here the declaration float list[] tells C compiler that list is an array of float type.
It should be noted that dimension of array is not specified when it is a parameter of a function.
Multi-dimensional arrays can be passed to functions as follows:
void printtable(int xsize,int ysize, float table[][5])
{

int x,y;

for (x=0; x<xsize; x++)


{

for (y=0; y<ysize;y++)

printf(\t%f,table[x][y]);
printf(\n);
}
}

Here float table[][5] tells C compiler that table is an array of dimension N X 5 of float.
Note we must specify the second

(and subsequent) dimension of the array BUT not the

first dimension.
------------------------------sizeof operator : is used to find the on. of bytes occupied by a variable / data type in computer memory.
eg :

sizeof (float)

returns

int m, x [ 50 ]
sizeof (m)

returns 2

sizeof ( x )

returns 100 ( 50 x 2 )

Increment and Decrement Operators:


++

and - -

The Operator + + adds 1 to the operand while -- subtracts 1, Both are unary operators
Eg :

++x

or

x ++

== > x+=1

== > x=x+1

-- x

or

x- -

== > x-=1

== > x=x-1

A Profix operator first adds 1 to the operand and then the result is assigned to the variable on
left. A postfix operator first assigns the value to the variable on the left and the increments
the operand.
Eg:

1) m = 5;

2). m = 5

y = ++m;

y = m++

O/P m =6, y=6


-----------------------------------------

m=6, y=5

Basic Input output :

C has many input output functions in order to read data

from input devices and display the results on the screen.


Formatted Functions:

These functions read and write all types of data values. They

require a conversion symbol to indents the data type using these functions the O/P can be
presented in an aligned manner.

-------------------------------------------------------------------------------------------------------------------Unformatted functions character I/O functions


(1) getchar ( ) function is used to read one character at a time from the key board
Syntax
ch = getchar ( ); where ch is a char Var.
main ( )
{
char ch;
printf(Enter a char);
ch = getchar ( );
printf(ch =%c, ch);
}
O/P Enter a char M
M
ch = M
When this function is executed, the computer will wait for a key to be pressed and assigns the value to the
variable when the enter key pressed.
putchar ( ): function is used to display one character at a time on the monitor.
Syntax:
putchar (ch);
Ex char ch = M
putchar (ch);
The Computer display the value char of variable ch i.e M on the Screen.

getch ( ):
function is used to read a char from a key board and does not expect the
enter key press.

Syntax: ch = getch ( );
When this function is executed ,computer waits for a key to be pressed from the dey board. As soon as a key
is pressed, the control is transferred to the nextline of the program and the value is assigned to the char
variable. It is noted that the char pressed will not be display on the screen.
getche ( ):
function is used to read a char from the key board without expecting the enter
key to be pressed. The char read will be displayed on the monitor.
Syntax:

ch = getche ( );

Note that getche ( ) is similar to getch ( ) except that getche ( ) displays the key pressed from the dey board
on the monitor. In getch ( ) e stands for echo.
Strng I/O functions
gets ( ) function is used to read a string of characters including white spaces. Note that wite spaces in a strng
cannot be read using scanf( ) with %s format specifier.
Syntax:
Ex:

gets (S); where S is a char string variable

char S[ 20 ];

gets (S);
When this function is executed the computer waits for the string to be entered
--------ACTUAL AND FORMAL ARGUMENTS
Passing of values between the main program and the function takes place through arguments.
The arguments listed in the function calling statements are referred to as actual
arguments. These actual values are passed to a function to compute a value or to perform a
task.
The arguments used tin the function declaration are referred as formal arguments. They are simply formal
variables that accept or receive the values supplied by the calling function.
Note: The number of actual and formal arguments and their data types should match.
The function call sends two integer values 10 and 5 to the function
int mul(int x, int y) which are assigned to x and y respectively.
The function computers the product x and y assigns the result to the local variable p, and then returns the
value 25 to the main() where it is assigned to y again..
-----------------------------------------------------------------------------------------------------Write a program to convert years into (1) Minutes (2) Hours (3) Days (4) Months (5)
Seconds. Using switch ( ) Statements.
# include<stdio.h>
# include<conio.h>
main( )
{

long int ch, min, hrs, ds, mon, yrs, sec;


clrscr( ) ;
printf(\n

[1] MINUTES \n [2] HOURS \n [3] DAYS \n [4] MONTHS \n

[5] SECONDS \n [6] EXIT \n Enter your Choice:);


scanf (%d, &ch);
if(ch > 0 && ch < 6)
{
printf(Enter Years:);
scanf(%d, &yrs);
}
mon = yrs * 12;
ds = mon * 30;
hrs = ds * 24;
min = hrs * 60;
sec = min * 60;
switch(ch)
{
case 1: printf(\n Minutes : %ld, min);
break;
case 2: printf( \n Hours : % ld, hrs);
break;
case 3: printf( \n Days : %ld, ds);
break;
case 4: printf( \n Months: %ld, mon);
break;
case 5: printf( \n Seconds : %ld, Sec);
break;
case 6: printf(\n Terminated by Choice);
exit( ) ;
break;
default: printf( \n Invalid Choice);
}
getch ( ) :
}
-----------------Write a program to print five entered numbers in Ascending Order.

# include<stdio.h>
# include<conio.h>
main ( )
{
int a, b, c, d, e, Sum = 0, i;
clrscr( ) ;
printf( \n Enter five Numbers:);
scanf( %d %d %d %d %d %d, &a, &b, &c, &d, &e); printf( \ n Numbers in Ascending Order is :)
Sum = a + b + c + d + e;
for(i=1; i<=Sum; i++)
{
if(i = = a || i = =b || i = = c || i = = d || i = = e)
{
printf( %3d ,i);
}
}
getch();
}
Output:
Enter five numbers:

Numbers in Ascending Order is : 1

----------------------------Example-2:
Program to find out the largest and smallest element in an array.
# include<stdio.h>
#include<conio.h>
main( )
{
int i,n;
float a[50], large, small;
printf(size of vector/value:);
scanf(%d, &n);
printf( \n vector elements are \n); for(i=0; i<n; i++)
scanf( %f , &a[ i ]);
large = a[0];
small = a[0];
for(i=1; i<n; i++)
{
if(a[ i ] > large)
large = a[ i ];
else if(a[ i ] < small)
small = a[ i ];

}
printf(\n Largest element in vector is %8.2f \n, large);
printf( \n smallest element in vector is %8.2f \n, small); getch( );
}
Output:
Size of vector : 7
Vector elements
34.00 - 9.00 12.00 10.00 - 6.00 0.00 36.00
Largest element in vector is 36.00
Smallest element in vector is - 9.00
--------------------------------------------------------(2) Write a C program to count the number of vowels present in a sentence. Solution
Consider a sentence this is a book. Count the appearance of vowels AEIOU
in
capital or small letters.
Program
/* program to count vowels * /
# include<stdio.h>
# include<conio.h>
# include<string.h>
main( )
{
char st[80], ch;
int count = 0, i;
clrscr( );
/* loop to read a string * /
printf( \n Enter the sentence: \n); gets(st);
/* loop to count the vowels in the string * /
for( i=0; i<strlen(st); i++)
switch(st [i ])
{
case A:
case E:
case I:
case O:
case U:
case a:
case e:
case i:
case o:
case u:
count ++;
break;
}
printf(\n %d vowels are present in the sentence, count); getch( );
}
------------------------------------(3) Write a C program to test whether a given string is palindrome string. explain
The working of program.
Solution: Consider the string LIRIL when it is reversed, it reads again as LIRIL.
Any string of this kind is called a palindrome string. Few other palindrome strings are
DAD, MOM, MADAM, MALAYALAM
/* program to check for palindrome stirng */ # include<stdio.h>

# include<conio.h>
# include<string.h>
main( )
{
char st[20], rst[20];
int i,j;
clrscr( );
printf(\n Enter the string:);
scanf(%s, st);
/* loop to reverse the string */
i=0;
j=strlen(st)-1;
while( j >= 0 )
{
rst[ i ] = st[ j ];
i++;
j--;
}
rst[ i ] = \0;
if(strcmp(st,rst)==0)
printf(\n %s is a palindrome string, st);
else
printf(\n %s is not a palindrome string, st); getch( );
}
------------------------------------------(5) Write a C program to read an array of names and to sort them in alphabetical
order (dictionary).
Step involved in arranging names in alphabetical order are given below.
Step 1 : Read n
Step 2 : Loop to read n names of the list
Step 3 : Loop to arrange the names by comparison Step 4: Loop to print the arranged list.
Step 5 : Stop
PROGRAM TO ARRANGE NAMES IN ALPHABETICAL ORDER.
# include<stdio.h>
# include<conio.h>
# include<string.h>
main( )
{
char names[50][20], temp[20]; int n,i,j;
clrscr( ):
printf( \n How many names?); scanf(%d, &n);
printf( \n Enter the %d names one by one \ n,n); for( i=0; i<n; i++)
scanf(%s, names[ i ]);
/* loop to arrange names in alphabetical order * /
for( i=0; i<n-1; i++)
for ( j =i+1; j<n; j++)
if(strcmp(names[ i ], names[ j ]) > 0)
{
strcpy( temp, names[ i ]);
strcpy(names[ i ], names[ j ]); strcpy(names[ j ],temp);
/* loop to print the alphabetical list of names * /
printf ( \n names in alphabetical order);
for( i=0; i<n; i++)
printf(\n %s, names[ i ]); getch( );
}

Output:
How many names? 4
Enter the 4 names one by one
DEEPAK
SHERIN
SONIKA
ARUN
Names in Alphabetical order
ARUN
DEEPAK
SHERIN
SONIKA
---------6) Write a C program to convert a line in the lower case text to upper case.
Solution
/* PROGRAM TO CONVERT LOWER CASE TEST TO UPPER CASE * /
# include<stdio.h>
# include<conio.h>
# include<string.h>
main( )
{
char st[80];
int i;
clrscr( );
printf( \ n Enter a sentence : \ n); gets(st);
/* loop to convert lower case alphabet to upper case * /
for( i=0; i<strlen(st); i++)
if(st[ i ] >= a && st[ i ] <= z)
st[ i ] = st[ i ] - 32;
printf( \n the converted upper case strings \n %s, st); getch( );
}
OUTPUT:
Enter a sentence:
Logical thinking is a must to learn programming The converted upper case string is
LOGICAL THINKING IS A MUST TO LEARN PROGRAMING.

(7) Write a C program to count no of lines, words and characters in a given text.
Solution:
A while loop is used to read the text. The character $ is used to terminate the reading of text.
Program
# include<stdio.h>
# include<string.h>
# include<conio.h>
main( )
{
char txt[250], ch, st[30];
int ins, wds, chs, i;
clrscr( ) ;

printf( \n Enter the text, type $ st end \n \n);


i=0;
while((txt[i++]= getchar( ) ) ! = $);
i--;
st[ i ] = \0 ;
ins = wds = chs = 0;

/ * loop to count lines, words & characters in text * /


i=0;
while(txt[ i ]!=$)
{
switch(txt[ i ])
{
case ,:
case !:
case \t:
case :
{
wds ++;
chs ++;
break;
}
case ?:
case .:
{
wds ++;
chs ++;
break;
}
default:
chs ++;
break;
}
i++;
}
printf(\n\n no of char (incl.blanks) = %d, chs); printf(\n No. of words = %d, wds);
printf(\n No of lines = %d, lns);
getch( ) ;
}
Output:
Enter the text, type $ at end
What is a string? How do you initialize it? Explain with example. With example. $
No of char (inch. Blanks) = 63 No of words = 12
No of lines = 3.
Q5: What is array? Also explain the type of array with example?
Answer: Array is a group of elements of same type referred using a unique name. Each
element of an array are stored in memory locations indexed from 0 through n number of its
elements. The lowest indexed will be the first element and highest indexed the last element

of an array. Just like variables, we have to declare arrays before using them. The general
syntax for declaring an array is

Syntax:

type array_name[array size]

In the above syntax the "type" defines the data type, "array_name" defines the unique name,
"array size" defines the number of elements contained in an array even if the size is not
specified the C++ compiler counts the size.
Array are classified into three major types they are single dimensional, two dimensional, multi
dimensional arrays.
(i) Single / One Dimensional arrays: Single Dimensional Array is an array having a single
index value to represent the arrays element.

Syntax:
type array_name[array_size_1]

Example:
int Age[5] ;
float cost[30];

Initialization of One Dimensional 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.
Example:
int A[5] = {11,2,23,4,15};
It is possible to leave the array size open. The compiler will count the array size.
Example:
int B[] = {6,7,8,9,15,12};
C++ Simple array program to print array value.

#include <stdio.h>
#include <conio>
void main()
{
int a[5] = {1,2,3,4,5};
printf(%d,a[0]);
getch();
}
output: 1
(ii) Two Dimensional array: Two Dimensional Array is a simple form of multi-dimensional
array that stores the array elements in a row, column matrix format.

Syntax:
type array_name[array_size1][array_size2]
Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.

Example:
int a[3][4];
In above example A two-dimensional array can be think as a table, which contains 3 rows and
4 columns. Can be shown as below:

Initializing Two-Dimensional Arrays:


Multi dimensioned arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

C++ 2D array program to print array values.


#include <stdio.h>
#include<conio.h>
void main ()
{
int a[5][2] = {0,1, 2,3, 4,5, 6,7,8,9};
for ( int i = 0; i < 5; i++ )
{
for ( int j = 0; j < 2; j++ )
{
Printf(%d, a[i][j]);
}
Printf(\n);
}
getch();
}
output:
a[0][0]: 0
a[1][0]: 2
a[2][0]: 4
a[3][0]: 6
a[4][0]: 8

a[0][1]: 1
a[1][1]: 3
a[2][1]: 5
a[3][1]: 7
a[4][1]: 9

(iii) Multi Dimensional Array :The Multi Dimensional Array is an array with two or more
index values. It is also known as array of arrays. A two dimensional array is also a multi
dimensional array.

Syntax: type array_name[array_size_1][array_size_2]...[array_size_n]


Example: the following declaration creates a three dimensional 5 . 10 . 4 integer array:
int threedim[5][10][4];

Example:
#include <iostream.h>
void main()
{
int i,j;
char a[2] [2] = {'A','B','C','D'};
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout << "Row:: "<< i+1 << "s column::"<<
j+1 <<" element is:: "<< a[i][j]<< '\n';
}
}
}
Result:
Row::
Row::
Row::
Row::

1s
1s
2s
2s

column::1
column::2
column::1
column::2

element
element
element
element

is
is
is
is

::
::
::
::

A
B
C
D

Q8. What is Control Statement? Explain.


Answer: Control Structures are statements that change the flow of a program to a
different code segment based on certain conditions. The control structures are categorized
into three major Conditional types they are
(i) Selection/branching Statements
(ii) Looping or Iteration statements
(iii) Jump Statements
Selection Statements:
If statement
If Else Statement
If Else If statement
Nested If statement
Switch statement
(i) if statement: In this control statement if the if condition is true, statement is executed;
otherwise it is skipped. The statement may either be a single or compound statement.
syntax of the if statement:

if (condition)
{
statement(s);

if example:
if (x == 100)
printf("x is 100");

(ii) if else statement: In this control statement the given condition is evaluated first. If the
condition is true, statement1 is executed. If the condition is false, statement2 is executed. It
should be kept in mind that statement1 and statement2 can be single or compound
statement.
syntax of the if - else statement:
if (condition)
statement1;
else
statement2;

if else example:
if (x == 100)
print("x is 100");
else
printf("x is not 100");

(iii) If Else If or else if ladder statement:


syntax of if-else-if statement:
if(condition 1)
statement 1;
else if (condition 2)
statement2;
else
statement3;

if-else-if example:
if(percentage>=60)
cout<<"Ist division";
else if(percentage>=50)
cout<<"IInd division";
else if(percentage>=40)
cout<<"IIIrd division";
else
cout<<"Fail" ;

Nested if statement: The if block may be nested in another if or else block. This is called
nesting of if or else block.
syntax of the nested if statement:
if(condition 1)
{

if(condition 2)
{
statement(s);
}
}
Example:
//Write a program in c++ to find the greater number among three numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
cout<<"enter value of a,b,c";
cin>>a>>b>>c;
if(a>b)
{
if(a>c)
{
cout<<"a is greater";
}
else
{
cout<<"c is greater";
}
}
else
{
if(b>c)
{
cout<<"b is greater";
}
else
{
cout<<"c is greater";
}
}
getch();
}
switch statement: The if and if-else statements permit two way branching whereas switch
statement permits multiple branching. The
syntax of switch statement is:
switch (var / expression)
{
case constant1 : statement 1;
break;
case constant2 : statement2;
break;
.
.
default: statement3;
break;
}
Example:
#include<iostream.h>
#include<conio.h>

void main()
{
int i;
clrscr();
printf("select the case");
scnaf(%d,&i);
switch(i)
{
case 1:
printf(sunday");
break;
case 2:
cout<<"monday";
break;
case 3:
cout<<"tuesday";
break;
default:
cout<<"wrong choice";
break;
}
getch();
}
Output: select the case 2
monday
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 executes break. 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.
Looping statement: It is also called a Repetitive control structure. Sometimes we require a
set of statements to be executed a number of times by changing the value of one or more
variables each time to obtain a different result. This type of program execution is called
looping. In C++ the looping statement are categorized into three types they are :
while loop
do-while loop
for loop
While loop: In the while loop a condition is first evaluated. If the condition is true, the loop
body is executed and the condition is re-evaluated. Hence, the loop body is executed
repeatedly as long as the condition remains true. As soon as the condition becomes false, it
comes out of the loop and goes to the statement next to the while loop.
Syntax of while loop
while(condition)
{
statement(s);
}
Example:
#include<iostream.h>
#include<conio.h>
void main()

{
int i = 1;
clrscr();
while(i<=10)
{
Cout<<i;
i++;
}
getch();
}
output:
1 2 3 4 5 6 7 8 9 10

do-while loop: The do-while loop is similar to while loop but one important difference
between the while loop and the do-while loop is the relative ordering of the conditional test
and loop body execution. In the while loop, the loop repetition test is performed before each
execution the loop body; the loop body is not executed at all if the initial test fail. In the dowhile loop, the loop termination test is performed after each execution of the loop body.
Hence, the loop body is always executed least once.
Syntax of do-while loop
do
{
statements;
} while (condition);
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
int i = 1;
clrscr();
do
{
Cout<<i;
i++;
}while(i<=10);
getch();
}
output:

1 2 3 4 5 6 7 8 9 10

for loop: It is a count controlled loop in the sense that the program knows in advance how
many times the loop is to be executed.
syntax of for loop
for (initialization; decision; increment/decrement)
{
statement(s);
}
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();

for(int i = 1 ; i <= 10 ; i++)


{
Cout<<i;
}
getch();

output:
1 2 3 4 5 6 7 8 9 10
In for loop three operations take place:
Initialization of loop control variable
Testing of loop control variable
Update the loop control variable either by incrementing or decrementing.
Initialization operation is used to initialize the value. On the other hand, Decision operation is
used to test whether the condition is true or false. If the condition is true, the program
executes the body of the loop and then the value of loop control variable is updated. Again it
checks the condition and so on. If the condition is false, it gets out of the loop.

Jump Statements: The jump statements unconditionally transfer program control within a
function. In C++ the Jump statement are categorized into three types they are :
goto statement
break statement
continue statement
The goto statement: goto allows to make jump to another point in the program.
The general format is:
goto end;
.
.
..
end:
end: end is known as label. It is a user defined identifier. After the execution of goto
statement, the control transfers to the line after label end.
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
cout<<"enter the value of a";
cin>>a;
cout<<"enter the value of b";
cin>>b;
if(a>b)
{
goto statement1;
}
else
{

goto statement2;
}
statement1:
cout<<"greater number is
goto end;
statement2:
cout<<"greater number is

"<<a;

"<<b;

end:
getch();
}
output:
enter the value of a5
enter the value of b2
greater number is 5
The break statement: The break statement, when executed in a switch structure, provides
an immediate exit from the switch structure. Similarly, you can use the break statement in
any of the loop. When the break statement executes in a loop, it immediately exits from the
loop.
#include<iostream.h>
#include<conio.h>
void main()
{
for(int i = 1; i <=10;i++)
{
if(i == 6)
{
cout<<"i like 6";
break;
}
cout<<"the value of i is "<<i<<endl;
}
getch();
}
the value
the value
the value
the value
the value
i like 6

of
of
of
of
of

i
i
i
i
i

is
is
is
is
is

1
2
3
4
5

The continue statement : The continue statement is used in loops and causes a program to
skip the rest of the body of the loop starts a new iteration.
while (condition)
{
Statement 1;
If (condition)
continue;
statement;
}
#include<iostream.h>
#include<conio.h>
void main()
{
for(int i = 1; i <=10;i++)

{
if(i == 6)
{
cout<<"i like 6"<<endl;
continue;
}
cout<<"the value of i is "<<i<<endl;
}
getch();
}
output:
the value
the value
the value
the value
the value
i like 6
the value
the value
the value
the value

of
of
of
of
of

i
i
i
i
i

is
is
is
is
is

1
2
3
4
5

of
of
of
of

i
i
i
i

is
is
is
is

7
8
9
10

---------------------------------------------------------------------------------------------------------------------------------Q9. What do you mean my storage classes? How many storage classes are available
in C++?
Answer :
Storage class are used to specify the visibility/scope and life time of symbols
(functions and variables). That means, storage classes specify where all a variable or function
can be accessed and till what time those variables will be available during the execution of
program.
In C++ there are 4 different storage classes available:
auto
register
static
extern
summary of c++ storage class specifiers :

C++ Storage
Specifier
auto
static
register
extern

Storage
Location
Memory
(RAM)
Memory
(RAM)

Scope Of
Variable
Local

CPU register
Memory
(RAM)

Local
Global

Local

Life Time
With in function
Life time is from when the flow reaches
the first declaration to the termination
of program.
With in function
Till the end of main program

auto: Variables defined within the function body are called automatic variables. Automatic
variable, also called as local variable and it has scope only within the function block where it
is defined. auto is the keyword used to declare automatic variables. auto is the default

storage class for local variables. Local variables are variables declared within a function or
blocks (after the opening brace, { of the block). Local variables are automatic by default.
They can be accessed only from with in the declaration scope. auto variables are allocated at
the beginning of enclosing block and deallocated at the end of enclosing block.

Example
auto int x, y, z = 10;
is same as
int x, y, z = 10;

C++ program of auto storage class.


#include<iostream.h>
#include<conio.h>
void function(void)
{
auto int i = 1 ;
i++;
cout<<i;
}
void main()
{
function();
function();
function();
function();
getch();
}
Output:- 2 2 2 2
In the above example, every time the method function() is invoked, memory is allocated for
i and de allocated at the end of the method. So it's output will be same.
register: It's similar to auto variables. Difference is that register variables might be stored
on the processor register instead of RAM, that means the maximum size of register variable
should be the size of CPU register ( like 16bit, 32bit or 64bit). The keyword used to declare a
register variable is register. This is normally used for frequently accessed variables like
counters, to improve performance. But note that, declaring a variable as register does not
mean that they will be stored in the register. It depends on the hardware and
implementation.

Example:
{
register int i;
}
C++ program of register storage class.
#include<iostream.h>
#include<conio.h>
void main()

{
register int i;
int array[10] = {0,1,2,3,4,5,6,7,8,9};
for (i=0;i<10;i++)
{
cout<<array[i];
}
getch();
}
Output: 0 1 2 3 4 5 6 7 8 9
static: A static variable will be kept in existence till the end of the program unlike creating
and destroying each time they move into and out of the scope. This helps to maintain their
value even if control goes out of the scope. When static is used with global variables, they will
have internal linkage that means it cannot be accessed by other source files. When static is
used in case of a class member, it will be shared by all the objects of a class instead of
creating separate copies for each object. static is the keyword used to declare a static
variable. In C++, when static is used on a class data member, it causes only one copy of that
member to be shared by all objects of its class.
Example:
static int i;
C++ program of static storage class.
#include<iostream.h>
#include<conio.h>
void function(void)
{
static int i = 1 ;
i++;
cout<<i;
}
void main()
{
function();
function();
function();
function();
getch();
}
Output: 2 3 4 5
Since static variable will be kept in existence till the end of program, variable i will retain its
value across the method invocations.
extern: External variables are variables that are recognized globally, rather than locally. In
other words, extern variable is like global variable, its scope is through out the program. It
can be defined anywhere in the c++ program. A variable defined outside a function is
external. An external variable can also be declared within the function that uses it by using
the keyword extern hence it can be accessed by other code in other files. extern symbols
have static storage duration, that is accessible throughout the life of program. Since no
storage is allocated for extern variable as part of declaration, they cannot be initialized while

declaring. The external storage class is most commonly used when there are two or more files
sharing the same global variables or functions as explained below.
Example:
extern void display();
extern int count;

C++ program of extern storage class.

First File : first.cpp


#include <iostream.h>
#include <conio.h>
#include "second.cpp"
int count ;
extern void display();
void main()
{
display();
getch();
}

Second File: second.cpp


#include <iostream.h>
extern int count;
void display()
{
count = 5;
cout << Count is << count << endl;
}
Output: Count is 5

Another program of extern storage class.

#include <iostream.h>
#include <conio.h>
void main( )
{
extern int y ;
cout<<"y = "<< y;
getch();
}
int y = 20 ;
Output:y = 20
Q10. What is Pointer? How to use pointer in C++?
Answer: a variable which stores the address of another variable is called a pointer. In other
words we can say that A pointer is a variable whose value is the address of another variable.
Pointers are said to "point to" the variable whose address they store. Like any variable or
constant, we must declare a pointer before you can work with it. The general form of a
pointer variable declaration is:
type *var-name;
Example:
int *ip;

// pointer to an integer

To Using Pointers in C++ There are few important operations, which we will do with the
pointers very frequently.
(a) We define a pointer variable
(b) Assign the address of a variable to a pointer
(c) Finally access the value at the address available in the pointer variable. This is done by using unary
operator * that returns the value of the variable located at the address specified by its operand.
Example:
#include <iostream>
#include<conio.h>
void main ()
{
int x = 20;
// actual variable declaration.
int *ip;
// pointer variable
ip = &x;
// store address of variable x in pointer variable ip
cout << "Value of x variable: "<<x<< endl;
cout << "Address stored in ip variable: "<< ip << endl;
// print the address stored in ip pointer variable
cout << "Value of *ip variable: "<< *ip << endl;
// access the value at the address available in
pointer
getch();
}

Output:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

Q10. What is Pointer? How to use pointer in C++?


Answer: a variable which stores the address of another variable is called a pointer. In other
words we can say that A pointer is a variable whose value is the address of another variable.
Pointers are said to "point to" the variable whose address they store. Like any variable or
constant, we must declare a pointer before you can work with it. The general form of a
pointer variable declaration is:
type *var-name;

Example:
int *ip;

// pointer to an integer

To Using Pointers in C++ There are few important operations, which we will do with the
pointers very frequently.
(a) We define a pointer variable
(b) Assign the address of a variable to a pointer
(c) Finally access the value at the address available in the pointer variable. This is done by using unary
operator * that returns the value of the variable located at the address specified by its operand.
Example:
#include <iostream>
#include<conio.h>
void main ()
{
int x = 20;
// actual variable declaration.
int *ip;
// pointer variable
ip = &x;
// store address of variable x in pointer variable ip
cout << "Value of x variable: "<<x<< endl;
cout << "Address stored in ip variable: "<< ip << endl;
// print the address stored in ip pointer variable
cout << "Value of *ip variable: "<< *ip << endl;
// access the value at the address available in
pointer
getch();
}

Output:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

17. Explain typecasting.


It is the process of converting one type into another. In other words converting an expression of a given type
into another is called type casting. Typecasting is making a variable of one type, such as an int, act like

another type, a char, for one single operation. To typecast something, simply put the type of variable you
want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a'
function as a char.
There are two ways of achieving the type conversion namely:
(I) Implicit Conversion (Automatic Conversion)
(II) Explicit Conversion
Implicit Conversion : This is not done by any conversions or operators. In other words the value gets
automatically converted to the specific type to which it is assigned.
Let us see this with an example:
#include <iostream>
using namespace std;
void main()
{

short x=6000;
int y;
y=x;
}

In the above example the data type short namely variable x is converted to int and is assigned to the integer
variable y.
Explicit Conversion:
Explicit conversion can be done using type cast operator and the general syntax for doing this is :
datatype (expression);
In C++ the type casting can be done in either of the two ways mentioned below namely:

C style casting

C++ style casting

The C style casting takes the syntax as :


(type) expression
This can also be used in C++.
The C++ style casting takes the syntax as :
type (expression)

Example: explicit type casting


#include <iostream>
#include <conio.h>
void main()
{
int a;
float b,c;
cout << "Enter the value of a:";
cin >> a;
cout << "Enter the value of b:";
cin >> b;
c = float(a)+b;
cout << "The value of c is:" << c;
getch();
}
Output:
Enter the value of a:10
Enter the value of b:12.2
The value of c is:22.2
Or there is an another example:
#include <iostream>
#include<conio.h>

void main()
{
int a;
double b=2.55;
a = b;
cout << a << endl;
a = (int)b;
cout << a << endl;
a = int(b);
cout << a << endl;
getch();
}
Output:
2
2
2
17b. What is the Difference between type conversion and type casting ?
Answer: Difference between type conversion and type casting
Type conversion: The Type Conversion is that which automatically converts the one data type into another
Type casting : When a user can convert the one data type into then it is called as the type casting

18. Whats the difference between public, private and protected?

A member (either data member or member function) declared in a private section of a


class can only be accessed by member functions and friends of that class
A member (either data member or member function) declared in a protected section of
a class can only be accessed by member functions and friends of that class, and by
member functions and friends of derived classes
A member (either data member or member function) declared in a public section of a
class can be accessed by anyone

15. Write a short notes on recursion with example.


Recursion is defined as a function calling itself. It is in some ways similar to a loop because
it repeats the same code, but it requires passing in the looping variable and being
more careful. Many programming languages allow it because it can simplify some
tasks, and it is often more elegant than a loop.
void recurse()
{
recurse();
}
void main()
{
recurse();
}

WHAT IS DEFAULT ARGUMENT?


A default parameter is a function parameter that has a default value
provided to it. If the user does notsupply a value for this parameter, the default value
will be used. If the user does supply a value for the default parameter, the usersupplied value is used.
ANS:

Example:
#include <iostream.h>
#include <conio.h>
void PrintValues(int nValue1, int nValue2=10)
{
cout << "1st value: " << nValue1 << endl;
cout << "2nd value: " << nValue2 << endl;
}
void main()
{
PrintValues(1); // nValue2 will use default parameter of 10
PrintValues(3, 4); // override default value for nValue2

getch();
}
Output:
1st value: 1
2nd value: 10
1st value: 3
2nd value: 4

In the first function call, the caller did not supply an argument for nValue2, so the
function used the default value of 10. In the second call, the caller did supply a value
for nValue2, so the user-supplied value was used.

Built-In Data Types


The basic (fundamental) data types provided by c++ are integral, floating point and void data
type. Among these data types, the integral and floating-point data types can be preceded by several
type modifiers. These modifiers (also known as type qualifiers) are the keywords that alter either
size or range or both of the data types. The various modifiers are short, long, signed and unsigned.
By default the modifier is signed.

In addition to these basic data types, ANSI C++ has introduced two more data types namely, bool
and wchar_t.
Integral Data Type: The integral data type is used to store integers and includes char (character)
and int (integer) data types.
Char: Characters refer to the alphabet, numbers and other characters (such as {, @, #, etc.)
defined in the ASCII character set. In C++, the char data type is also treated as an integer data type
as the characters are internally stored as integers that range in value from -128 to 127. The char
data type occupies 1 byte of memory (that is, it holds only one character at a time).
The modifiers that can precede char are signed and unsigned. The various character data types
with their size and range are listed in Table

Int: Numbers without the fractional part represent integer data. In C++, the int data type is used
to store integers such as 4, 42, 5233, -32, -745. Thus, it cannot store numbers such as 4.28,
-62.533. The various integer data types with their size and range are listed in Table

Floating-point Data Type: A floating-point data type is used to store real numbers such as 3 .
28, 64. 755765, 8.01, -24.53. This data type includes float and double' data types. The various
floating -point data types with their size and range are listed in Table

Void: The void data type is used for specifying an empty parameter list to a function and return
type for a function. When void is used to specify an empty parameter list, it indicates that a

function does not take any arguments and when it is used as a return type for a function, it
indicates that a function does not return any value. For void, no memory is allocated and hence, it
cannot store anything. As a result, void cannot be used to declare simple variables, however, it can
be used to declare generic pointers.
Bool and wcha_t : The boo1data type can hold only Boolean values, that is; either true or false,
where true represents 1 and false represents O. It requires only one bit of storage, however, it is
stored as an integer in the memory. Thus, it is also considered as an integral data type. The bool
data type is most commonly used for expressing the results of logical operations performed on the
data. It is also used as a return type of a function indicating the success or the failure of the
function.
In addition to char data type, C++ provides another data type wchar_t which is used to store 16bit wide characters. Wide characters are used to hold large character sets associated with some
non-English languages.
Derived Data Types: Data types that are derived from the built-in data types are known as
derived data types. The various derived data types provided by C++ are arrays, junctions,
references and pointers.
Array An array is a set of elements of the same data type that are referred to by the same name.
All the elements in an array are stored at contiguous (one after another) memory locations and
each element is accessed by a unique index or subscript value. The subscript value indicates the
position of an element in an array.
Function A function is a self-contained program segment that carries out a specific well-defined
task. In C++, every program contains one or more functions which can be invoked from other parts
of a program, if required.
Reference A reference is an alternative name for a variable. That is, a reference is an alias for a
variable in a program. A variable and its reference can be used interchangeably in a program as
both refer to the same memory location. Hence, changes made to any of them (say, a variable) are
reflected in the other (on a reference).
Pointer A pointer is a variable that can store the memory address of another variable. Pointers
allow to use the memory dynamically. That is, with the help of pointers, memory can be allocated
or de-allocated to the variables at run-time, thus, making a program more efficient.
User-Defined Data Types
Various
user-defined
data
enumerations and classes.

types

provided

by

C++

are structures,

unions,

Structure, Union and Class: Structure and union are the significant features of C language.
Structure and union provide a way to group similar or dissimilar data types referred to by a single
name. However, C++ has extended the concept of structure and union by incorporating some new
features in these data types to support object -oriented programming.
C++ offers a new user-defined data type known as class, which forms the basis of object-oriented
programming. A class acts as a template which defines the data and functions that are included in

an object of a class. Classes are declared using the keyword class. Once a class has been declared,
its object can be easily created.
Enumeration: An enumeration is a set of named integer constants that specify all the
permissible values that can be assigned to enumeration variables. These set of permissible values
are known as enumerators. For example, consider this statement.
enum country {US, UN, India, China};

// declaring an
// enum type

In this statement, an enumeration data-type country (country is a tag name) , consisting of


enumerators US, UN and so on, is declared. Note that these enumerators represent integer values,
so any arithmetic operation can be performed on them.
By default, the first enumerator in the enumeration data type is assigned the value zero. The value
of subsequent enumerators is one greater than the value of previous enumerator. Hence, the value
of US is 0, value of UN is 1 and so on. However, these default integer values can be overridden by
assigning values explicitly to the enumerators
as shown here.
enum country {US, UN=3, India, china} ;
In this declaration, the value of US is O by default, the value of UN is 3, India is 4 and soon.
Once an enum type is declared, its variables can be declared using this statement.
country countryl, country2;
These variables countryl, country2 can be assigned any of the values specified in enum declaration
only. For example, consider these statements.
countryl India; // valid
country2 Japan; // invalid
Though the enumerations are treated as integers internally in C++, the compiler issues a warning,
if an int value is assigned to an enum type. For example, consider these statements.
Country1 = 3;
Country1 = UN;

//warning
/ /valid

Country1 = (country) 3; / /valid


C++ also allows creating special type of enums known as anonymous enums, that is, enums
without using tag name as shown in this statement.
enum {US, UN=3, India, China};
The enumerators of an anonymous enum can be used directly in the program as shown here.
int count = US;
The typedef Keyword

C++ provides a typedef feature that allows to define new data type names for existing data types
that may be built-in, derived or user-defined data types. Once the new name has been defined,
variables can be declared using this new name. For example, consider this declaration.
typedef int integer;
In this declaration, a new name integer is given to the data type into This new name now can be
used to declare integer variables as shown here.
integer i, j, k;
Note that the typedef is used in a program to contribute to the development of a clearer program.
Moreover, it also helps in making machine-dependent programs more portable.

You might also like