C Language Notes
C Language Notes
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 :
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.
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.
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.
1.
Imperative / Procedural: Imperative programming languages are the most traditional once. Their code
Functional / Modular: Functional programming languages are as name suggest, the problems are divided
Object Oriented: Object oriented programming languages; they mainly focus around objects that have their
---------------------------------------------------------------------------------------------------------------------
History of C:
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
1963
1967
Language Name
Language)
Language)
University
1970
1972
CPL : (1963) :
Cambridge University
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
ANSI C
1989
ANSI Committee
ANSI/ISO C
1990
ISO Committee
C99
1999
Standardization Committee
Portability
Flexibility
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 */
{
declarations
/* variables; arrays; records;
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.
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.
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:
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.
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 */
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
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;
// 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
C Preprocessor directives:
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.
: %d \n", height );
Output:
value of height : 100
#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
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
#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
Output:
First defined value for height : 100
value of height after undef & redefine : 600
Output:
Function1 is called before main function call
Now we are in main function
Function2 is called just before end of main function
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
#include statements : used to include the header file for input/output stdio.h, the standard mathematics library
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:
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.
*/%
+-
----------------------------------------------------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.
Syntax:
data_type *var_name;
char *p;
In the above example * is used to denote that p is pointer variable and not a
normal variable.
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.
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:
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.
by using pointer we can easily pass string data and array in function for process.
-----------------------------------------------------------------------------------
------------------------------------------------------------------------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;
"<<*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;
-------------------//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();
}
int a,b;
a = 1;
b = 2;
fun(&a,&b);
//call
getch();
}
#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)
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
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 :
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,
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;
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];
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]
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.
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).
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;
}
Return
value
Syntax
calloc() allocates a
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);
LINKED LIST:1)
2)
3)
4)
5)
6)
7)
ARRAY:1)
2)
3)
4)
5)
6)
7)
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.
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++;
And similarly:
x = x-1;
x = x+1;
can be written as
x++; // postfix form
is the same as
x--;
Decrement operators ( -- )
x = 5
x = x+1
x = 6
x = 5
++x
x = 6
x = 5
x++
x=5
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.
4 Post_decrement
i++
i
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:
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.
b = --5;
Or
b = 5--;
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= - 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).
----------------------------------------------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 */
/* 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
--------------------------------------------
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
Associativity
left-to-right
right-to-left
left-to-right
right-to-left
right-to-left
left-to-right
Category
Operator
Associativity
Postfix
Left to right
Unary
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
------------------------------------------------------------
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:
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
The example above defines two variables with the same storag e class, auto can only be used within
functions,
i.e., local variables.
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 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
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();
}
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.
(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.
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.
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..
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
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:
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
#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);
}
#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);
is
main
use
of
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 employee
{
char name[50];
char sex;
float salary;
} xyz;
To access a member (or field) of a struct, C provides dot (.) operator. For example,
xyz . sex ; xyz . salary;
xyz . name
SUNDAY};
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 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;
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
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 )
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++
m=6, y=5
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.
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:
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( )
{
# 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:
----------------------------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( ) ;
of an array. Just like variables, we have to declare arrays before using them. The general
syntax for declaring an array is
Syntax:
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];
#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:
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.
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
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");
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();
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;
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;
#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
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
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
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
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.
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
//warning
/ /valid
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.