Introduction To C Programming
Introduction To C Programming
Introduction to C Programming
#include <stdio.h>
main() {
printf("Hello, world!\n");
return 0;
}
• #include <stdio.h> -This line tells the compiler to include this header file for
compilation.
• { } - These curly braces are equivalent to the stating that "block begin" and
"block end".These can be used at many places,such as switch and if statement.
• printf() - This is the actual print statement which is used in our c program
2
fraquently.we have header file stdio.h! But what it does? How it is defined?
Seems like trying to figure out all this is just way too confusing.
• Then the return 0 statement. Seems like we are trying to give something back,
and it gives the result as an integer. Maybe if we modified our main function
definition: int main() ,now we are saying that our main function will be returning
an integer!So,you should always explicitly declare the return type on the function.
• Let us add #include <stdlib.h> to our includes. Let's change our original return
statement to return EXIT_SUCCESS;. Now it makes sense!
• printf always returns an int. The main pages say that printf returns the number of
characters printed.It is good programming practice to check for return values. It
will not only make your program more readable, but at the end it will make your
programs less error prone. But we don't really need it in this particular case.So
we cast the function's return to (void). fprintf,exit and fflush are the only
functions where you should do this.
/* Main Function
* Purpose: Controls our program, prints Hello, World!
* Input: None
* Output: Returns Exit Status
*/
int main() {
(void)printf("Hello, world!\n");
return EXIT_SUCCESS;
}
Note:
The KEY POINT of this whole introduction is to show you the fundamental difference
between understandability and correctness. If you lose understandability in an attempt to
gain correctness, you will lose at the end. Always place the understandability as a priority
ABOVE correctness. If a program is more understandable in the end,the chances it can be
fixed correctly will be much higher. It is recommend that you should always document
your program. You stand less of a chance of screwing up your program later,if you try to
make your program itself more understandable.
3
The advantages of C
In other words,for writing anything from small programs for personal amusement to
complex industrial applications,C is one of a large number of high-level languages
designed for general-purpose programming.
• C is also succinct. It permits the creation of tidy and compact programs. This
feature can be a mixed blessing, however, and the C programmer must balance
readability and simplicity.
• C allows commands that are invalid in some other languages. This is no defect,
but a powerful freedom which, when used with caution, makes many things easily
possible. It does mean that there are concealed difficulties in C, but if you write
thoughtfully and carefully, you can create fast, efficient programs.
• With C, you can use every resource of your computer offers. C tries to link closely
with the local environment, providing facilities for gaining access to common
peripherals like printers and disk drives.
The filename must have extension ``.c'' (full stop, lower case c), e.g. myprog.c or
progtest.c. The contents must have to obey C syntax. For example, they might be as in
the above example,starting with the line /* /* end of the program */.
Compilation
There are many C compilers are present around. The cc is being the default Sun
compiler. The GNU C compiler gcc is popular and also available for many platforms. PC
users may also be familiar with Borland bcc compiler.
There are also C++ compilers which are usually denoted by CC (note upper case CC.For
example Sun provides GNU and CCGCC. The GNU compiler is also denoted by the
command g++
Other C/C++ compilers also exist. All the above compilers operate in essentially the
share many common command line options and same manner. However, the best source
of each compiler is through online manual pages of your system: e.g. man cc.
In the basic discussions of compiler operation,for the sake of compactness,we will simply
refer to the cc compiler -- other compilers can simply be substituted in place of cc until
5
Your program simply invoke the command cc to Compile . The command must be
followed by the name of the (C) program you wish to compile it.
cc program.c
If there are obvious errors in your program (such as mistypings, misspelling one of the
key words or omitting a semi-colon), the compiler will detect it and report them.
If the compiler option -o is used : the file listed after the -oor when the compiler has
successfully digested your program, the compiled version, or executable, is left in a file
called a.out
cc -o program program.c
which puts the compiled program into the file program ( any file you name following the
"-o" argument) instead of putting it in the file a.out .
This executes your program able to print any results to the screen. At this stage there
may be run-time errors, such as it may become evident that the program has produced
incorrect output or division by zero.
If so, you must return to edit your program source, and compile it again, and run it
again.
level language provides a set of instructions you can recombine creatively and give to the
imaginary black boxe of the computer. The high-level language software will then
translate these high-level instructions into the low-level machine language instructions
Characteristics of C
We briefly list some of C's characteristics that have lead to its popularity as a
programming language and define the language. Naturally we will be studying many of
these aspects throughout our tutorial.
C has now become a widely used professional language for various reasons.
The main drawback of c is that it has poor error detection which can make it off putting
to the beginner. However diligence in this matter can pay off handsomely since having
learned the rules of the C we can break them. Not all languages allow this. This if done
carefully and properly leads to the power of C programming.
C Program Structure
A C program basically has the following form:
• Preprocessor Commands
• Function prototypes -- declare function types and variables passed to function.
• Type definitions
• Variables
• Functions
C assumes that function returns an integer type,if the type definition is omitted. NOTE:
This can be a source of the problems in a program
7
/* Sample program */
main()
{
printf( ``I Like C \n'' );
exit ( 0 );
}
NOTE:
4. exit() is also a standard function that causes the program to terminate. Strictly
speaking it is not needed here as it is the last line of main() and the program will
terminate anyway.
Variables in C
Variables in C
1. Variables in C are memory locations with help of which we can be assigned values
and are given names .
2. To store data in memory for later use,we use variables.
3. In C, a variable must have to be declared before it can be used.
4. You can declare Variables at the start of any block of code, but most are found at
the start of each function.
5. Most local variables are destroyed on return from that function and created when
the function is called.
6. A declaration begins with the type, followed by the name of one or more than one
variables.
8
C keeps a small set of keywords for its own use only.These keywords are given below:
Identifiers in C
Identifiers" or "symbols" are the names you supply for variables, types,labels, and
functions in your program. Identifier names must differ in case and spelling from any
keywords. You cannot use keywords as the identifiers; they are reserved for special use
only. You create an identifier by specifying it in the declaration of a variable,function,or
type. In this example which is given below result is an identifier for an integer variable,
and printf and main are identifier names for functions.
o Functions
o Function parameters
o Macros and macro parameters
o Type definitions
o Objects
o Labels
o Enumerated types and enumerators
#include <stdio.h>
int main()
{
int result;
if ( result != 0 )
printf_s( "Bad file handle\n" );
}
9
Variable declarations
Variables are of three different types which are as follows:
1. Global Variable
2. Local Variable
3. Static Variable
Global Variable:
Local Variable:
Inside the specific function that creates them,these variables only exist. They are
unknown to to the main program and to the other functions. In this case,they are
normally implemented using a stack. Local variables cease to exist once if the
function that created them is completed. Each time a function is executed or
called,they are recreated.
o At the start of any block delimited by curly braces only. Such variables are
exist only when the containing function is active (bounded extent) and
visible only within the block (local scope again). The convention in C is
generally to declare all such local variables at the top of a function; this
is different from the convention in C++ or Java, which encourage variables
to be declared when they are first time used
main()
{
counter++; /* global because it has not been declared within this block */
printf("counter is %2d before the call to func\n", counter);
int func(void)
{
int counter = 10; /* local variable because it has declared within this block */
*/ printf("counter is %2d within func\n", counter);
}
#include <stdio.h>
main()
{
Test();
}
function Test()
{
int a = 0;
printf("a is %d within func\n", a)
a++;
}
Since every time the function is called it sets a to 0 and prints "0",this function is quite
useless . The a++ which increments the variable serves no purpose since as soon as the
function exits then a variable disappears. The a variable is declared static to make a
useful counting function which will not lose track of the current count:
#include <stdio.h>
main()
{
Test();
}
function Test()
{
static int a = 0;
printf("a is %d within func\n", a)
11
a++;
}
Basic types
There are 4 basic types of variable in C; they are: char, int, double and float
Type
Meaning
name
The most basic unit addressable by the machine; typically a single octet.
char
This is an integral type.
The most natural size of integer for the machine; typically a whole 16, 32
int
or 64 bit addressable word.
float A single-precision floating point value.
double A double-precision floating point value.
Operators in C
/= a /= b a divided by b (assigned to a)
%= a %= b Remainder of a/b (assigned to a)
>>= a >>= b a, right-shifted b bits (assigned to a)
<<= a <<= b a, left-shifted b bits (assigned to a)
&= a &= b a AND b (assigned to a)
|= a |= b a OR b (assigned to a)
^= a ^= b a XOR b (assigned to a)
, e1,e2 e2 (e1 evaluated first)
Precedence of C Operators
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Branching Statement in C
Branching
The C language programs follows a sequential form of execution of statements. Many
times it is required to alter the flow of sequence of instructions. C language provides
statements that can alter the flow of a sequence of instructions. These statements are
called as control statements. To jump from one part of the program to another,these
statements help. The control transfer may be unconditional or conditional. Branching
14
1. If Statement
2. The If else Statement
3. Compound Relational tests
4. Nested if Statement
5. Switch Statement
If Statement
If statement is the simplest form of the control statement. It is very frequently used in
allowing the flow of program execution and decision making.
if(condition)
statement;
The command says that if the condition is true then perform the following statement or If
the condition is fake the computer skips the statement and moves on to the next
instruction in the program
{
int numbers; // Declare the variables
printf ("Type a number:"); // message to the user
scanf ("%d", & number); // read the number from standard input
if (number < 0) // check whether the number is a negative
number
number = - number; // If it is negative then convert it into
positive.
Printf ("The absolute value is % d \n", number); // print the value
}
If (condition)
Program statement 1;
Else
Program statement 2;
Nested if Statement
The if statement may itself contain another if statement is called as nested if statement.
The syntax of the Nested if Statement is as follows
if (condition1)
if (condition2)
statement-1;
else
statement-2;
else
statement-3;
16
Switch Statement
The switch-case statement is a multi-way decision making statement. Unlike the
multiple decision statement that can be created using if-else, the switch statement
evaluates the conditional expression and tests it against the numerous constant
values.During execution,the branch corresponding to the value that the expression
matches is taken.
The value of the expressions in a switch-case statement must have to be an ordinal type
i.e. integer, char, short, long, etc.Double and Float are not allowed.
switch( expression )
{
case constant-expression1: statements1;
[case constant-expression2: statements2;]
[case constant-expression3: statements3;]
[default : statements4;]
}
O/P:
#include<stdio.h>
main()
{
int n=7;
17
switch(n) {
case 0:
printf("You typed zero.\n");
break;
case 3:
case 5:
case 7:
printf("n is a prime number\n");
break;
case 2: printf("n is a prime number\n");
case 4:
case 6:
case 8:
printf("n is an even number\n");
break;
case 1:
case 9:
printf("n is a perfect square\n");
break;
default:
printf("Only single-digit numbers are allowed\n");
break;
}
}
Looping Statement in C
Looping
By using special loop keywords,you can loop (jumping for those assembly junkies)
through your code. These include following categories:
1. for loop
2. while loop
3. do while.
For Loop
The for statement allows for the controlled loop. The syntax for for loop is as follows:
#include <stdio.h>
int main(void)
{
int count;
printf(\n);
return 0;
}
O/P:
1 2 3 4 5 6 7 8 9 10
While Loop
For repeating C statements whiles a condition is true,the while provides a the necessary
mechanism. The syntax for while loop is as follows:
while (condition)
program statement;
The foollowing program shows the use of while loop which prints number from 0 to 10
#include <stdio.h>
int main(void)
{
int loop = 0;
return 0;
}
19
do {
/* do stuff */
} while (statement);
#include <stdio.h>
int main(void)
{
do
{
r_digit = value % 10;
printf("%d", r_digit);
value = value / 10;
} while (value != 0);
printf(\n);
return 0;
}
C Storage Class
Storage Class
Storage classes include following categories:
20
1. auto
2. extern
3. register
4. static.
auto
The auto keyword is used to place the specified variable into the stack area of memory.
In most variable declaration,this is usually implicit one, e.g. int i;
extern
The extern keyword is used to specify variable access the variable of the same name
from some other file. In modular programs,this is very useful for sharing variables.
register
The register keyword gives suggest to the compiler to place the particular variable in the
fast register memory located directly on the CPU. Most compilers these days (like gcc)
are so smart that suggesting registers could actually make your program more slower.
static
It is also used to declare the variables to be private to a certain file only when declared
with global variables. static can also be used with functions, making those functions
visible only to file itself.The static keyword is used for extending the lifetime of a
particular variable. The variable remains even after the function call is long gone (the
variable is placed in the alterable area of memory),if you declare a static variable inside a
function,. The static keyword can be overloaded.
Functions in C
What is a Function?
A function is a block of statement that has a name and it has a property that it is
reusable i.e. it can be executed from as many different points in a C Program as required.
A function is a self contained block of statements that perform a coherent task of the
same kindFunction helps to groups a number of program statements into a unit and gives
21
it a name. This unit can be invoked from the other parts of a program.It is not possible
by computer program to handle all the tasks by it self. Instead its requests other
program like entities - called functions in C - to get its tasks done.
Structure of a Function
There are two main parts of the functions. The function header and the function body.
function body
Function Header
int sum(int x, int y)
Function Body
What ever is written with in { } is the body of the function.
The following example shows the use of functions which prints factorial of a number:
#iinclude <stdio.h>
int I, factorial_number = 1;
int main(void)
{
int number = 0;
printf("Enter a number\n");
scanf("%d", &number);
calc_factorial (number);
return 0;
}
The C Preprocessor
The C Preprocessor
• All preprocessor lines always begin with #. This listing is from Weiss pg. 104. The
unconditional directives are as follows:
o #define - Define a preprocessor macro
o #include - Insert a particular header from another file
o #undef - Undefine a preprocessor macro
#define MAX_ARRAY_LENGTH 20
The above code will tell the CPP to replace instances of MAX_ARRAY_LENGTH with 20. To
increase readability,use #define for constants.
#include <stdio.h>
#include "mystring.h"
The above code tells the CPP to get stdio.h from System Libraries and add the text to this
file. The next line tells CPP to get mystring.h from the local directory and then add the
text to the file.
#undef MEANING_OF_LIFE
#define MEANING_OF_LIFE 42
The above code tells the CPP to undefine MEANING_OF_LIFE and define it for 42.
#ifndef IROCK
#define IROCK "You wish!"
#endif
The above code tells the CPP to define IROCK only if IROCK isn't defined already.
#ifdef DEBUG
24
Thed above code tells the CPP to do the following statements if DEBUG is defined.If you
pass the -DDEBUG flag to gcc,this is useful .
Input/Output Functions in C
#include <stdio.h> near start of the program file. If you do not do this, the compiler may
complain about undefined datatypes or functions.
1. getchar
2. putchar
getchar
getchar always returns the next character of keyboard input as an int. The EOF (end of
file) is returned,if there is an error . It is usual to compare this value against EOF before
using it. So error conditions will not be handled correctly,if the return value is stored in a
char, it will never be equal to EOF.
The following program is used to count the number of characters read until an EOF is
encountered. EOF can be generated by typing Control - d.
#include <stdio.h>
main()
25
{ int ch, i = 0;
putchar
putchar puts its character argument on the standard output (usually the screen).
The following example program converts any typed input into capital letters.It applies the
function toupper from the character conversion library ctype.h to each character in turn
to do this.
main()
{ int ch;
while((ch = getchar()) != EOF)
putchar(toupper(ch));
}
1. printf
2. scanf
printf
This offers more structured output than the putchar. Its arguments are, in order; a
control string, which controls what get printed, followed by a list of values to be
substituted for entries in the control string. The prototype for the printf() is:
To print,printf takes in a formatting string and the actual variables . An example of printf
is:
int x = 5;
char str[] = "abc";
char c = 'z';
float pi = 3.14;
With the use of the formatting line,you can format the output.You can change how the
particular variable is placed in output,by modifying the conversion specification, . For
example
printf("%10.4d", x);
The . allows for the precision.To floats as well,this can be applied.The number 5 is on the
tenth spacing as the number 10 puts 0005 over 10 spaces. You can also add - and +
right after % to make the number explicitly output as +0005. Note that the value of x
does not actually change. In other words,you will not get output using %-10.4d will not
output -0005. %e is useful for outputting floats using the scientific notation. %le for
doubles and %Le for the long doubles.
To grab things from input,scanf() is used. Beware though, scanf isn't greatest function
that C has to offer. Some people brush off the scanf as a broken function that shouldn't
be used often. The prototype for scanf is:
Last example will create a rectangle with rounded corner:
To read of data from the keyboard,scanf allows formatted . Like printf it has a control
string,followed by the list of items to be read. However scanf wants to know the address
of items to be read, since it is a function which will change that value. Therefore the
names of variables are preceeded by the & sign. Character strings are an exception to
this. Since a string is already a character pointer, we give the names of the string
variables unmodified by a leading &. Control string entries which match values to be read
are preceeded by the percentage sign in a similar way to their printf equivalent. Looks
similar to printf, but doesn't completely behave like the printf does. Take the example:
scanf("%d", x);
For grabbing things from input. Beware though, scanf isn't the greatest function that C
has to offer,scanf() is used. The following is the example which shows the use of scanf:
int x, args;
for ( ; ; ) {
printf("Enter an integer bub: ");
if (( args = scanf("%d", &x)) == 0) {
printf("Error: not an integer\n");
continue;
} else {
if (args == 1)
printf("Read in %d\n", x);
27
else
break;
}
}
FILE *output_file;
fopen takes in the path to the file as well as the mode and to open the file with. Take for
the following example:
For reading,this will open the file in /home/johndoe/input.dat . You will usually use fopen
as given below:
fopen takes two arguments, both are strings, the first is the name of the file to be
opened, the second is an access character, which is usually one of the following:
6. "a+"-open for the appending and reading (file may or may not exist)
The following code fragmentis used to get the text from the first <title> element:
FILE *output_file;
fgets stores it into *s pointer and reads in size - 1 characters from the stream. The string
is always automatically null-terminated. If it reaches an EOF or newline,fgets stops
reading in characters.
sscanf takes a character pointer instead of a file pointer and works much like fscanf.
Instead of scanf/fscanf,using the combination of fgets/sscanf you can avoid the
"digestion" problem (or bug, depending on who you talk to :)
fprintf takes in a special pointer called a file pointer, signified by the FILE *. It then
accepts argument and a formatting string and. The only difference between printf and
fprintf is that fprintf can redirect output to a particular stream. These streams can be
stderr,stdout,or a file pointer. More on the file pointers when we get to fopen. An
example is given below:
If the program crashes, sometimes the stream isn't written. You can do this by using
fflush() function. Sometime it is necessary to forcefully flush a buffer to its stream. The
prototype for fflush is as follows:
The program which is given below displays use of a file operations. The the program
writes it and data enter through the keyboard. Character by character, to file input. The
end of the data is indicated by entering an EOF character, which is control-z. the file input
is closed at this signal only.
main()
{
file *f1;
printf("Data input output");
f1=fopen(Input,w); /*Open the file Input*/
30
Pointers in C
What is Pointer?
In c,a pointer is a variable that points to or references a memory location in which data is
stored. In the computer,each memory cell has an address that can be used to access that
location so a pointer variable points to a memory location we can access and change the
contents of this memory location via the pointer.
Pointer declaration:
A pointer is a variable that contains the memory location of another variable in shich data
is stored. Using pointer,you start by specifying the type of data stored in the location.
The asterisk helps to tell the compiler that you are creating a pointer variable. Finally you
have to give the name of the variable. The syntax is as shown below.
Address operator:
Once we declare a pointer variable then we must point it to something we can do this by
assigning to the pointer the address of the variable you want to point as in the following
example:
ptr=#
The above code tells that the address where num is stores into the variable ptr. The
variable ptr has the value 21260,if num is stored in memory 21260 address then
31
main()
{
int *ptr;
int sum;
sum=45;
ptr=&sum
printf ("\n Sum is %d\n", sum);
printf ("\n The sum pointer is %d", ptr);
}
y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;
1. Call by reference
2. Call by value.
Call by value:
We have seen that there will be a link established between the formal and actual
parameters when a function is invoked. As soon as temporary storage is created where
the value of actual parameters is stored. The formal parameters picks up its value from
storage area the mechanism of data transfer between formal and actual parameters
allows the actual parameters mechanism of data transfer is referred as call by value. The
corresponding formal parameter always represents a local variable in the called function.
The current value of the corresponding actual parameter becomes the initial value of
formal parameter. In the body of the actual parameter,the value of formal parameter
may be changed. In the body of the subprogram,the value of formal parameter may be
changed by assignment or input statements. This will not change the value of the actual
parameters.
void main()
{
int x,y;
x=20;
y=30;
printf("\n Value of a and b before function call =%d %d",a,b);
fncn(x,y);
printf("\n Value of a and b after function call =%d %d",a,b);
}
fncn(p,q)
int p,q;
{
p=p+p;
q=q+q;
}
Call by Reference:
The address should be pointers,when we pass address to a function the parameters
receiving . By using pointers,the process of calling a function to pass the address of the
variable is known as call by reference. The function which is called by reference can
33
Pointer to arrays:
an array is actually very much similar like pointer. We can declare as int *a is an
address,because a[0] the arrays first element as a[0] and *a is also an address the form
of declaration is also equivalent. The difference is pointer can appear on the left of the
assignment operator and it is a is a variable that is lvalue. The array name cannot appear
as the left side of assignment operator and is constant.
struct products
{
34
char name[30];
int manufac;
float net;
item[2],*ptr;
this statement ptr as a pointer data objects of type struct products and declares item as
array of two elements, each type struct products.
Pointers on pointer
A pointer contains garbage value until it is initialized. Since compilers cannot detect the
errors may not be known until we execute the program remember that even if we are
able to locate a wrong result,uninitialized or wrongly initialized pointers it may not
provide any evidence for us to suspect problems in pointers. For example the expressions
such as
*ptr++, *p[],(ptr).member
Arrays in C
What is an Array?
• Arrays are collection of similar items (i.e. ints, floats, chars) whose memory is
allocated in a contiguous block of memory.
Declaration of arrays
Arrays must be declared before they are used like any other variable. The general form of
declaration is:
type variable-name[SIZE];
The type specify the type of the elements that will be contained in the array, such as
int,float or char and the size indicate the maximum number of elements that can be
stored inside the array.
float height[50];
Declares the height to be an array containing the 50 real elements. Any subscripts 0 to
49 are all valid. In C the array elements index or subscript begins with the number zero.
So height [0] refers to first element of the array. (For this reason, it is easier to think of
it as referring to element number zero, rather than as referring to first element). The
declaration int values[10]; would reserve the enough space for an array called values
that could hold up to 10 integers. Refer to below given picture to conceptualize the
reserved storage space.
values[0]
values[1]
values[2]
values[3]
values[4]
values[5]
values[6]
values[7]
values[8]
values[9]
Initialization of arrays:
We can initialize the elements in an array in the same way as the ordinary variables when
they are declared. The general form of initialization off arrays is:
The values in the list care separated by commas, for example the statement
int number[3]={0,0,0};
scanf(%d,&n);
printf("Enter the elements of the array\n");
for I=0;I < n;I++)
scanf(%d,&a[I]);
for(I=0;I < n;I++)
{
if(a[I]< 0)
count_neg++;
else
count_pos++;
} printf("There are %d negative numbers in the array\n",count_neg);
printf("There are %d positive numbers in the array\n",count_pos);
}
data_type array_name[row_size][column_size];
int m[10][20];
The following program illustrate addition two matrices & store the results in the 3rd
matrix
/* example program to add two matrices & store the results in the 3rd matrix */
#include< stdio.h >
#include< conio.h >
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;
clrscr();
printf("enter the order of the matrix\n");
scanf("%d%d",&p,&q);
if(m==p && n==q)
{
printf("matrix can be added\n");
printf("enter the elements of the matrix a");
for(i=0;i < m;i++)
for(j=0;j <n;j++)
scanf(%d,&a[i][j]);
printf("enter the elements of the matrix b");
for(i=0;i < p;i++)
for(j=0;j <q;j++)
scanf(%d,&b[i][j]);
printf("the sum of the matrix a and b is");
for(i=0;i <m;i++)
for(j=0;j <n;j++)
c[i][j]=a[i][j]+b[i][j];
for(i=0;i < m;i++)
{ for(j=0;j <n;j++)
37
printf(%d\t,&a[i][j]);
printf(\n);
}
}
It is wasteful when dealing with array type structures to allocate so much space when
it is declared
1. sizeof()
2. malloc()
3. calloc()
4. realloc()
5. free()
sizeof()
The sizeof() function returns the memory size of requested variable. This call should be
used in the conjunction with the calloc() function call, so that only the necessary memory
is allocated, rather than a fixed size. Consider the following,
struct date {
int hour, minute, second;
};
int x;
malloc()
A block mf memory may be allocated using the function called malloc. The malloc
function reserves a block of memory of specified size and return a pointer of type void.
This means that we can assign it to any type of the pointer. It takes the following form:
ptr=(cast-type*)malloc(byte-size);
ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of
memory with the size byte-size. The following is the example of using malloc function
x=(int*)malloc(100*sizeof(int));
calloc()
Calloc is another memory allocation function that is normally used to request the multiple
blocks of storage each of same size and then sets all bytes to zero. The general form of
calloc is:
ptr=(cast-type*) calloc(n,elem-size);
The above statement allocates contiguous space for n blocks each size of the elements
size bytes. All bytes are initialized to zero and a pointer to the first byte of allocated
region is returned. If there is not enough space a null pointer is also returned.
realloc()
The memory allocated by using calloc or malloc might be insufficient or excess sometimes
in both the situations we can change the memory size already allocated with the help of
the function called realloc. This process is called the reallocation of memory. The general
statement of reallocation of memory is :
39
ptr=realloc(ptr,newsize);
free()
Compile time storage of a variable is allocated and released by the system in accordance
with its storage class. With the dynamic runtime allocation, it is our responsibility to
release the space when it is not required at all.When the storage is limited,the release of
storage space becomes important . When we no longer need the data we stored in a
block of memory and we do not intend to use that block for the storing any other
information, Using the free function,we may release that block of memory for future use.
free(ptr);
Strings in C
What is a String?
• A string is combination of characters.
Initializing Strings
The initialization of a string must the following form which is simpler to the one
dimension array
Note:
Character string always terminated by a null character ‘\0’. A string variable is always
declared as an array & is any valid C variable name. The general form of declaration of a
string variable is
char address[15];
scanf(%s,address);
41
strlen() function:
This function counts and returns the number of characters in a particular string. The
length always does not include a null character. The syntax of strlen() is as follows:
n=strlen(string);
Where n is the integer variable which receives the value of length of the string.
strcat() function:
when you combine two strings, you add the characters of one string to the end of the
other string. This process is called as concatenation. The strcat() function is used to joins
2 strings together. It takes the following form:
strcat(string1,string2)
string1 & string2 are the character arrays. When the function strcat is executed string2 is
appended to the string1. the string at string2 always remains unchanged.
42
strcmp function:
In c,you cannot directly compare the value of 2 strings in a condition like
if(string1==string2) Most libraries however contain the function called strcmp(),which
returns a zero if 2 strings are equal, or a non zero number if the strings are not the
same. The syntax of strcmp() is given below:
Strcmp(string1,string2)
strcmpi() function
This function is same as strcmp() which compares 2 strings but not case sensitive.
Strcmp(string1,string2)
strcpy() function:
To assign the characters to a string,C does not allow you directly as in the statement
name=Robert; Instead use the strcpy() function found in most compilers the syntax of
the function is illustrated below.
strcpy(string1,string2);
strlwr () function:
This function converts all characters in a string from uppercase to lowercase
The syntax of the function strlwr is illustrated below
strlwr(string);
strrev() function:
This function reverses the characters in a particular string. The syntax of the function
strrev is illustrated below
strrev(string);
What is a Structure?
• Structure is a method of packing the data of different types.
• When we require using a collection of different data items of different data types
in that situation we can use a structure.
To holds the details of four fields namely title, author pages and price,the keyword struct
declares a structure. These are the members of the structures. Each member may belong
to same or different data type. The tag name can be used to define the objects that have
the tag names structure. The structure we just declared is not a variable by itself but a
template for the structure. We can declare the structure variables using the tag name
any where in the program. For example the statement, struct lib_books
book1,book2,book3; declares the book1,book2,book3 as variables of type struct
lib_books each declaration has four elements of the structure lib_books. The complete
structure declaration might look like this
The complete structure declaration might look like this
struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};
The node list has a useful property called the length. The length property return the
number of node in a node list.
The following code fragment get the number of <title> elements in "bookdetails.xml":
struct lib_books { char title[20]; char author[15]; int pages; float price; }; struct
lib_books, book1, book2, book3;
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}newstudent;
printf("Enter the student information");
printf("Now Enter the student id_no");
scanf(“%d”,&newstudent.id_no);
printf(“Enter the name of the student”);
scanf(“%s”,&new student.name);
printf(“Enter the address of the student”);
scanf(“%s”,&new student.address);
Union:
However the members that we compose a union all share the same storage area within
the computers memory where as each member within a structure is assigned its own
unique storage area. Thus unions are used to observe memory. They are useful for the
application involving multiple members. Where values need not be assigned to all the
members at any time. Unions like structure contain members whose individual data types
may differ from one another also. Like structures union can be declared using the
keyword union as follows:
Last example will create a rectangle with rounded corner:
union item
{
int m;
float p;
char c;
}
code;
The notation for accessing a union member that is nested inside a structure remains the
same as for the nested structure.In effect,a union creates a storage location that can be
used by one of its members at a time. When a different number is assigned to a new
value the new value supercedes the previous members value. Unions may be used in all
the places where a structure is allowed.
46
DisplayInfo(Int val = 1)
{
Printf("%d ", val);
if(val == 100)
return;
else
DisplayInfo(++val);
}
Contact Author
for(i=1;i<=100;i++)
{
printf(/n"%d",i);
}
Contact Author
DisplayInfo(Int val = 1)
{
Printf("%d ", val);
if(val == 100)
return;
else
DisplayInfo(++val);
}
Contact Author
int a=1;
l:if(a<=100)
{
printf("%d",a);
goto a;
}
int a;
int *p;
int p=&a;
tihs is initialization n if its not initialized itscalled as dangling pointer
========================================
in this it is initialised as
ptr=&x;
main()
{
int *a;//declaration of pointer variable
printf("%d",sizeof(a));
}
Assigning the address of a variable to the the pinter variable is nothing but the initialisation of
pointer.
eg. int x=10,*p = &x; or
int x=10, *p;
p = &x;
=========================================================
int *p,a=1;
p=&a;
The pointer must have same data type as that of variable whose address is stored into it.