You are on page 1of 47

1

Introduction to C Programming

1. In 1972, C was developed at Bell Laboratories by Dennis Ritchie.

2. C is a simple programming language with a relatively simple to


understand syntax and few keywords.

3. C is useless.C itself has no input/output commands, doesn't have


support for strings as a fundamental data type. There is no useful
math functions built in.

4. C requires the use of libraries as C is useless by itself. This


increases the complexity of the C.The use of ANSI libraries and
other methods,the issue of standard libraries is resolved.

C Programming :: A Quick Hellow World Program


Let's give a simple program that prints out "Hello World" to standard out. We'll call our
program as hello.c.

#include <stdio.h>

main() {
printf("Hello, world!\n");
return 0;
}

Explanation of The Above Code:

• #include <stdio.h> -This line tells the compiler to include this header file for
compilation.

o What is header file?They contain prototypes and other compiler/pre-


processor directive.Prototypes are also called the basic abstract function
definitions.

o Some common header files are stdio.h,stdlib.h, unistd.h and math.h.

• main()- This is a function, in particular it is the main block.

• { } - 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?

• return 0-What is this? Who knows what is this

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.

• What about the documentation? We should probably document some of our


code so that other people can understand what we are doing. Comments in the
C89 standard are noted by this: /* */. The comment always begins with /* and
ends with */.

An Improved Code of The Above Example


#include <stdio.h> #include <stdlib.h>

/* 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 has many advantages:

• Before C,machine-language programmers criticized high-level languages


because,with their black box approach,they shielded the user from the working
details of all its facilities and the computer. To give access to any level of the
computer down to raw machine language,however, C was designed and because
of this, it is perhaps the most flexible high-level language.

• To organize programs in a clear,easy,logical way,C has features that allow the


programmer.For example,C allows meaningful names for variables without any
loss of efficiency, yet it gives a complete freedom of programming style,a set of
flexible commands for performing tasks repetitively (for, while,do) and including
flexible ways of making decisions.

• 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 C Compilation Model


4

Creating, Compiling and Running Your Program


Creating the program
First create a file containing the complete program, such as the above example. You can
use any ordinary editor to create the file. One such editor is textedit which is available
on most UNIX systems.

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

and unless otherwise stated.

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.

The compilation command is:

cc program.c

where program.c is name of the file.

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.

It may possible that the compiler cannot detect logical errors.

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

It is convenient to use a -o and filename in the compilation as in

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 .

Running the program


The next stage is to run your executable program.You simply type the name of the file
containing it, in this case program (or a.out),to run an executable in UNIX.

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.

C is a High Level Language

C is also called as a high-level language. To give a list of instructions (a computer


program) to a computer,the high-level computer language is used. The native language
of the computer is a stream of numbers called machine level language. As you might
expect, the action resulting from a single machine language instruction is very primitive,
and many thousands of them can be required to do something like substantial. A high-
6

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.

• Extensive use of function calls


• Small size
• Loose typing -- unlike PASCAL
• Structured language
• Low level (BitWise) programming readily available
• Pointer implementation - extensive use of pointers for memory, array, structures
and functions.

C has now become a widely used professional language for various reasons.

• It has high-level constructs.


• It produces efficient programs.
• It can handle low-level activities.
• It can be compiled on a variety of computers.

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

We must have a main() function

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:

1. printf is a standard C function -- called from main.


2. C requires a semicolon at the end of the every statement.
3. \n signifies newline. Formatted output -- more later.

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

C has the following simple data types

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

The following code describe the declaration of variable:


int main()
{
int a;
char b;
return 0;
}

C keeps a small set of keywords for its own use only.These keywords are given below:

auto break case char const continue default do


double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while

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.

Identifiers provide names for the given language elements:

o Functions
o Function parameters
o Macros and macro parameters
o Type definitions
o Objects
o Labels
o Enumerated types and enumerators

o Structure and union names

#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:

These variables can be accessed by any function of the program. By associating


memory locations with variable names,they are implemented. If the function is
recalled,they do not get recreated . Declare it outside of all the functions if you
want to declare a global variable. The function will use the variable that was
declared within it and ignore the global one,if a variable of the same name is
declared both within a function and outside of it.

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.

Variable declarations show up in three places:

o Outside a function. These declarations declare global variables which are


visible throughout the program (i.e. they have global scope). Use of
global variables is always a big mistake.
o In the header of a function in the argument list . These variables are the
parameters to the function. They are only visible inside the function body
and their local scope), exist only from when the function is called to
when the function returns (bounded extent---note that this is different
from what happens in some garbage-collected languages like Scheme),
and get their initial values from the arguments to the function when it is
called.

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

The following program demonstrate the use of global and


local variables.
#include <stdio.h>
10

int counter = 0; /* global because we are outside all blocks.*/


int func(void);

main()
{
counter++; /* global because it has not been declared within this block */
printf("counter is %2d before the call to func\n", counter);

func(); /* call a function. */


printf("counter is %2d after 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);
}

Using static variables


Another important feature of the variable scoping is the static variable. In a local function
scope,a static variable exists only , but it does not lose its value when program execution
leaves this scope. Consider the example which is given below:

#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

Overview of the C Operators


The C operators fall into the following categories:

• Postfix operators, which follow a single operand only.


• Unary prefix operators, which precede with a single operand.
• Binary operators, which take two operands and perform a variety of logical and
arithmetic operations.
• The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of
the first expression only.
• Assignment operators, which only assign a value to a variable.

• The comma operator, which gives guarantees left-to-right evaluation of comma-


separated expressions.

To create more complex expressions,variables and constants can be used in conjunction


with C operators. The following tables describes different operators available in c
12

Operator Example Description/Meaning


() f() Function call
[] a[10] Array reference
-> <S->A td <> Structure and union member selection
. s.a Structure and union member selection
+ [unary] +a Value of a
- [unary] -a Negative of a
* [unary] *a Reference to object at address a
& [unary] &a Address of a
~ ~a One's complement of a
++ [prefix] ++a The value of a after increment
++ [postfix] a++ The value of a before increment
- - [prefix] -a The value of a after decrement
- - [postfix] a- The value of a before decrement
sizeof sizeof (t1) Size in bytes of object with type t1
sizeof sizeof e Size in bytes of object having the type of expression e
a +b a plus b
+ [binary]
a -b a minus b
- [binary]
a *b a times b
* [binary]
a /b a divided by b
/%
a %b Remainder of a/b
>> a >> b a, right-shifted b bits
<< a << b a, left-shifted b bits
< a <b 1 if a < b; 0 otherwise
> a >b 1 if a > b; 0 otherwise
<= a <= b 1 if a <= b; 0 otherwise
>= a >= b 1 if a >= b; 0 otherwise
== a == b 1 if a equal to b; 0 otherwise
!= a != b 1 if a not equal to b; 0 otherwise
& [binary] a&b Bitwise AND of a and b
| a|b Bitwise OR of a and b
^ a^b Bitwise XOR (exclusive OR) of a and b
&& a && b Logical AND of a and b (yields 0 or 1)
|| a || b Logical OR of a and b (yields 0 or 1)
! !a Logical NOT of a (yields 0 or 1)
Expression e1 if a is nonzero;
?: a ? e1 : e2
Expression e2 if a is zero
= a =b a, after b is assigned to it
+= a += b a plus b (assigned to a)
-= a -= b a minus b (assigned to a)
*= a *= b a times b (assigned to a)
13

/= 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

Unary + - ! ~ ++ - - (type) * & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

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

Statemnt are of following categories:

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.

The If structure has the following syntax

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

The following program calculate the absolute value of an


integer using if statement:
Calculate the absolute value of an integer */
# include < stdio.h > //Include the stdio.h file
void main ( ) // start of 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
}

The If else Statement


The if else is actually just an extension of the general format of if statement. If the result
of the condition is true, then program statement 1 is executed else program statement 2
15

will be executed. The syntax of the If else statement is as follows:

If (condition)

Program statement 1;
Else
Program statement 2;

The following program find whether a number is negative


or positive using if statement:
#include < stdio.h > //include the stdio.h header file in your program
void main ( ) // Start of the main
{
int num; // declare variable num as integer
printf ("Enter the number"); //message to the user
scanf ("%d", &num); // read the input number from keyboard
if (num < 0) // check whether number is less than zero.
Printf ("The number is negative") // If it is less than zero then it is negative.
Else // else statement.
Printf ("The number is positive"); //If it is more than zero then the given
number is positive.
}

Compound Relational tests


To perform compound relational tests,C language provides the necessary mechanisms. A
compound relational test is simple one or more simple relational tests joined together by
either the the logical OR operators or logical AND. These operators are represented by
character pairs && // respectively. To form complex expressions in C,the compound
operators can be used. The syntax of the Compound Relational tests is as follows:

a> if (condition1 && condition2 && condition3)


b>if (condition1 // condition2 // condition3)

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

The following example print the given numbers along with


the largest number using nested if statement.
#include < stdio.h > //includes the stdio.h file to your program
main ( ) //start of main function
{
int a,b,c,big; //declaration of variables
printf ("Enter three numbers"); //message to the user
scanf ("%d %d %d", &a, &b, &c); //Read variables a,b,c,
if (a>b) // check whether a is greater than b if true then
if(a>c) // check whether a is greater than c
big = a ; // assign a to big
else big = c ; // assign c to big
else if (b>c) // if the condition (a>b) fails check whether b is
greater than c
big = b ; // assign b to big
else big = c ; // assign C to big
printf ("Largest of %d,%d&%d = %d", a,b,c,big);
}
//print the given numbers along with the largest number.

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.

The syntax of switch statement is as follows :

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:

for (start condition; continue condition; re-evaluation)


program statement;

The foollowing program shows the use of for loop which


18

prints number from 0 to 10


* Sample program using a for statement */

#include <stdio.h>

int main(void)
{
int count;

for (count = 1; count <=10; count = count + 1)


printf("%d", 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

/* Sample program including the while loop */

#include <stdio.h>

int main(void)
{

int loop = 0;

while (loop <=10)


{
printf("%d", loop);
++loop
}

return 0;

}
19

The do while statement


The do {} while statement allows a loop to continue whilst a condition evaluates as TRUE
(non-zero value). The loop will exacute at least once The syntax is as follows

do {
/* do stuff */
} while (statement);

The following program reverse a number using do while


loop
/* Demonstration of the do..while loop */

#include <stdio.h>

int main(void)
{

int value, r_digit;

printf(Enter a number to be reversed.\n);


scanf(%d, &value);

do
{
r_digit = value % 10;
printf("%d", r_digit);
value = value / 10;
} while (value != 0);
printf(\n);
return 0;
}

Difference between while and do while loop


The do statement is similar to the while statement except that its termination condition is
at the end of the body of the loop only. Thus, you want to use a do statement,if you want
to perform the body of the loop at least once, regardless of the condition.

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.

In a C Program,the name of the function is unique and is Global. It meams that a


function can be accessed from any location with in a C Program.when the function is
called,we pass information to the function called arguments specified.And the function
either returns some values to the point it was called from or returns nothing

Structure of a Function
There are two main parts of the functions. The function header and the function body.

The following syntax shows th syntax of using function in c:

return_ data_type function name (arguments, arguments)


data _type _declarations of arguments;
{

function body

Function Header
int sum(int x, int y)

It has three main parts

1. The function name i.e. sum


2. The parameters of the function enclosed in the paranthesis

3. Return value type of the function i.e. int

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:

* Program to calculate a specific factorial number */

#iinclude <stdio.h>

void calc_factorial (int); // ANSI function prototype


22

void calc_factorial (int i)


{

int I, factorial_number = 1;

for (I=1; I <=n; ++i)


factorial_number *= I;
printf("The factorial of %d is %d\n", n, factorial_number);
}

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 is a separate step in the compilation process,


but not part of the compiler.

• C Preprocessor is just a text substitution tool and we'll refer to the


C Preprocessor as the CPP.

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

The conditional directives are as follows:

o #ifndef - If this macro is not defined


o #ifdef - If this macro is defined
o #if - Test if a compile time condition is true
o #elif - #else an #if in one statement
23

o #else - The alternative for #if


o #endif - End preprocessor conditional

Other directives include:

o ## - Token merge, creates a single token from two adjacent ones

o # - Stringization, replaces a macro parameter with a string constant

Some examples of the above is given below:

#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

/* Your debugging statements here */


#endif

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

The Standard Input Output File


To perform,input and output to files or the terminal,UNIX supplies a standard package.To
use them,this contains most of the functions which will be introduced in this section,along
with definitions of the datatypes required.Your program must include these definitions by
adding the line to use these facilities.

#include <stdio.h> near start of the program file. If you do not do this, the compiler may
complain about undefined datatypes or functions.

Character Input / Output


If you will not press the return key then they'll not start reading any input, and they'll not
print characters on the terminal until there is a whole line to be printed. This is the lowest
level of output and input. It provides very precise control, but is usually too fiddly to be
useful also. Most computers perform buffering of inputs and outputs. These include :

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;

while((ch = getchar()) != EOF)


i ++;
printf("%d\n", i);
}

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.

#include <ctype.h> /* For definition of toupper */


#include <stdio.h> /* For definition of getchar, putchar, EOF */

main()
{ int ch;
while((ch = getchar()) != EOF)
putchar(toupper(ch));
}

Formatted Input / Output


These includes following:

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:

int printf(const char *format, ...);


26

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;

printf("\t%d %s %f %s %c\n", x, str, pi, "WOW", c);

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:

int scanf( const char *format, ...);

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 I/O Functions in C

C File Handling - File Pointers


Use a new datatype called a file pointer to with C files . This type is written as FILE *, and
defined within stdio.h. A file pointer called output_file is declared in a statement is as
follows:

FILE *output_file;

Function Name Operation


Creates a new file for use
fopen()
Opens a new existing file for use
fclose Closes a file which has been opened for use
getc() Reads a character from
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads a integer from a file
putw() Writes an integer to the file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file
rewind() Sets the position to the begining of the file

Opening a file pointer using fopen()


To open streams,fopen() is used.For opening files for input, this is most often used.
Before it can access it,your program must open a file . This function returns the required
file pointer. The value NULL will be returned,if the file cannot be opened for any reason.
fopen's prototype is as follows:

FILE *fopen (const char *path, const char *mode);


28

fopen takes in the path to the file as well as the mode and to open the file with. Take for
the following example:

iFILE *Fp; Fp = fopen("/home/johndoe/input.dat", "r");

For reading,this will open the file in /home/johndoe/input.dat . You will usually use fopen
as given below:

if ((output_file = fopen("output_file", "w")) == NULL)


fprintf(stderr, "Cannot open %s\n", "output_file");

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:

1. "r"-Opening the file for reading


2. "a"-Opening the file for appending
3. "w"-Opening the file for writing
4. "w+"-open for the writing and reading (existing file will be overwritten)
5. "r+"-open for the reading and updating (file must already exist)

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;

Closing a file pointer using fclose()


You would use fclose() to close the stream, . The prototype for fclose is given below:

int fclose( FILE *stream );

File I/O :: fgets()


The alternatives to scanf/fscanf is fgets. The prototype is as follows:

char *fgets(char *s, int size, FILE *stream);

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.

File I/O :: sscanf()


The sscanf library call is handy to scan a string for a format.The prototype is as follows:
29

int sscanf(const char *str, const char *format, ...);

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 :)

File I/O :: fprintf()


 It is sometimes useful also to output to the different streams.
 fprintf() allows us to do exactly the same thing
 The prototype for fprintf is as follows:

int fprintf(FILE *stream, const char *format, ...);

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:

fprintf(stderr, "ERROR: Cannot malloc enough memory.\n");

This output the error message to standard error.

File I/O :: fscanf()


fscanf() is basically a streams version of the scanf. The prototype for fscanf is as follows:

int fscanf( FILE *stream, const char *format, ...);

File I/O :: fflush()

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:

int fflush(FILE *stream);

Not very difficult to use, specify the stream to fflush.

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.

#include< stdio.h >

main()
{
file *f1;
printf("Data input output");
f1=fopen(Input,w); /*Open the file Input*/
30

while((c=getchar())!=EOF) /*get a character from key board*/


putc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/
printf("\nData output\n");
f1=fopen(INPUT,r); /*Reopen the file input*/
while((c=getc(f1))!=EOF)
printf("%c",c);
fclose(f1);
}

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.

type * variable name

The following example illustrate the declataion of pointer


variable
int *ptr;
float *string;

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=&num;

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

The following program illustrate the pointer declaration


/* A program to illustrate pointer declaration*/

main()
{
int *ptr;
int sum;
sum=45;
ptr=&sum
printf ("\n Sum is %d\n", sum);
printf ("\n The sum pointer is %d", ptr);
}

Pointer expressions & pointer arithmetic:


In expressions,like other variables pointer variables can be used. For example if p1 and
p2 are properly initialized and declared pointers, then the following statements are valid.

y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;

C allows us to subtract integers to or add integers from pointers as well as to subtract


one pointer from the other. We can also use short hand operators with pointers p1+=;
sum+=*p2; etc., By using relational operators,we can also compare pointers like the
expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed.

The following program illustrate the pointer expression


and pointer arithmetic
/*Program to illustrate the pointer expression and pointer arithmetic*/
#include< stdio.h >
main()
{ int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 6;
y=6*- *ptr1/ *ptr2 +30;
printf("\nAddress of a +%u",ptr1);
printf("\nAddress of b %u",ptr2);
printf("\na=%d, b=%d",a,b);
printf("\nx=%d,y=%d",x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf("\na=%d, b=%d,"a,b);
}
32

Pointers and function:


In a function declaration,the pointer are very much used . Sometimes,only with a pointer
a complex function can be easily represented and success. In a function definition,the
usage of the pointers may be classified into two groups.

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.

/* Include< stdio.h >

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

change the value of the variable used in the call.

/* example of call by reference*?

/* Include< stdio.h >


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;
}

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.

/* A program to display the contents of array using pointer*/


main()
{
int a[100];
int i,j,n;
printf("\nEnter the elements of the array\n");
scanf(%d,&n);
printf("Enter the array elements");
for(I=0;I< n;I++)
scanf(%d,&a[I]);
printf("Array element are");
for(ptr=a,ptr< (a+n);ptr++)
printf("Value of a[%d]=%d stored at address %u",j+=,*ptr,ptr);
}

Pointers and structures


We know the name of an array stands for address of its zeroth element the same concept
applies for names of arrays of structures. Suppose item is an array variable of the struct
type. Consider the following declaration:

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.

• Pointers and arrays have a special relationship. To reference memory


locations,arrays use pointers. Therefore, most of the times, array and pointer
references can be used interchangeably.

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.

The following example illustrate the use of array:


35

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:

type array_name[size]={list of values};

The values in the list care separated by commas, for example the statement

int number[3]={0,0,0};

The initialization of arrays in c suffers two drawbacks

1. There is no convenient way to initialize only selected element.

2. There is no shortcut method to initialize large number of element

The following program to count the no of positive and


negative numbers
/* Program to count the no of positive and negative numbers*/
#include< stdio.h >
void main( )
{
int a[50],n,count_neg=0,count_pos=0,I;
printf("Enter the size of the array\n");
36

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);
}

Multi dimensional Arrays:


Often there is a need to store and manipulate two dimensional data structure such as the
matrices & tables. Here array has two subscripts. One subscript denotes row & the other
the column. The declaration of two dimension arrays is as follows:

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);
}
}

Dynamic Memory Allocation in C

What is Dynamic Memory Allocation?


 Dynamic Memory Allocation is defined as the dynamically allocation of space for
variables at runtime.

 It is wasteful when dealing with array type structures to allocate so much space when
it is declared

Five ANSI Standartd Function Used in Dynamic Memory


Allocation
ANSI C provides five standard functions that will help you allocate memory on the heap
which are as follows:

1. sizeof()
2. malloc()
3. calloc()
4. realloc()

5. free()

The following table describe the five different standard


functions that helps you allocate memory dynamically
Function Task
sizeof The sizeof() function returns the memory size of the requested variable
Allocates memory requests size of bytes and returns a pointer to the Ist
malloc
byte of allocated space
Allocates space for an array of elements initializes them to zero and returns
calloc
a pointer to the memory
free Frees previously allocated space
38

realloc Modifies the size of previously allocated space.

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;

x = sizeof( struct date );

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);

ptr is a pointer that has been created by using calloc or malloc.

The following program illustrate the reallocation of


memory using realloc() and malloc()
/*Example program for reallocation*/

#include< stdio.h >


#include< stdlib.h >
define NULL 0
main()
{
char *buffer;
/*Allocating memory*/
if((buffer=(char *) malloc(10))==NULL)
{
printf("Malloc failed\n");
exit(1);
}
printf("Buffer of size %d created \n",_msize(buffer));
strcpy(buffer,Bangalore);
printf(\nBuffer contains:%s\n,buffer);
/*Reallocation*/
if((buffer=(char *)realloc(buffer,15))==NULL)
{
printf("Reallocation failed\n");
exit(1);
}
printf("\nBuffer size modified".\n);
printf("\nBuffer still contains: %s\n",buffer);
strcpy(buffer,Mysore);
printf("\nBuffer now contains:%s\n",buffer);
/*freeing memory*/
free(buffer);
}
40

Strings in C

What is a String?
• A string is combination of characters.

• Any set or sequence of characters defined within double quotation symbols is a


constant string.

• In c it is required to do some meaningful operations on the strings

Initializing Strings
The initialization of a string must the following form which is simpler to the one
dimension array

char month1[ ]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’};

The following example shows the use of string:


/*String.c string variable*/
#include < stdio.h >
main()
{
char month[15];
printf ("Enter the string");
gets (month);
printf ("The string entered is %s", month);
}

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

Reading Strings from the terminal:


The function scanf with %s format specification is needed to read the character string
from the terminal itself. The following example shows how to read strings from the
terminals:

char address[15];
scanf(%s,address);
41

String operations (string.h)


language recognizes that strings are terminated by null character and is a different class
of array by letting us input and output the array as a unit. To array out many of the
string manipulations,C library supports a large number of string handling functions that
can be used such as:

1. Length (number of characters in the string).


2. Concatentation (adding two are more strings)
3. Comparing two strings.
4. Substring (Extract substring from a given string)

5. Copy(copies one string over another)

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.

The following program shows to find the length of the


string using strlen() function
/*writr a c program to find the length of the string using strlen() function*/
#include < stdio.h >
include < string.h >
void main()
{
char name[100];
int length;
printf("Enter the string");
gets(name);
length=strlen(name);
printf("\nNumber of characters in the string is=%d",length);
}

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);

The following program illustrate the use of string


functions:
/* Example program to use string functions*/
43

#include < stdio.h >


#include < string.h >
void main()
{
char s1[20],s2[20],s3[20];
int x,l1,l2,l3;
printf("Enter the strings");
scanf("%s%s",s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{printf("\nStrings are not equal\n");
strcat(s1,s2);
}
else
printf("\nStrings are equal");
strcpy(s3,s1);
l1=strlen(s1);
l2=strlen(s2);
l3=strlen(s3);
printf("\ns1=%s\t length=%d characters\n",s1,l1);
printf("\ns2=%s\t length=%d characters\n",s2,l2);
printf("\ns3=%s\t length=%d characters\n",s3,l3);
}

Structures and Unions in C

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.

• A structure is used as a method of handling a group of related data items of


different data types.

Syntax of Using Structure


structure definition:
general format:
struct tag_name
{
data type member1;
data type member2;
....
...
}
44

Example of Using Structure:


struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};

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;
};

struct lib_books, book1, book2, book3;

Get the Length of a Node List


The node list is always keeps itself up-to-date. If an element is deleted or added, in the
node list or the XML document, the list is automatically updated.

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;

The following program shows the use of structure

/* Example program for using a structure*/


#include< stdio.h >
void main()
{
45

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);

printf(“Enter the cmbination of the student”);


scanf(“%d”,&new student.combination);

printf(Enter the age of the student”);


scanf(“%d”,&new student.age);
printf(“Student information\n”);
printf(“student id_number=%d\n”,newstudent.id_no);
printf(“student name=%s\n”,newstudent.name);
printf(“student Address=%s\n”,newstudent.address);
printf(“students combination=%s\n”,newstudent.combination);
printf(“Age of student=%d\n”,newstudent.age);
}

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

How to print 1 to 100 without using any conditional loop?


Recursion is solution of this problem.

DisplayInfo(Int val = 1)
{
Printf("%d ", val);
if(val == 100)
return;
else
DisplayInfo(++val);
}

Posted by: Paresh

Contact Author
for(i=1;i<=100;i++)
{
printf(/n"%d",i);
}

Posted by: amitabh ranjan

Contact Author
DisplayInfo(Int val = 1)
{
Printf("%d ", val);
if(val == 100)
return;
else
DisplayInfo(++val);
}

Posted by: Saktipada Upadhyaya

Contact Author
int a=1;
l:if(a<=100)
{
printf("%d",a);
goto a;
}

Posted by: mani krishna

How pointer variables are intialised?

int a;
int *p;
int p=&a;
tihs is initialization n if its not initialized itscalled as dangling pointer

========================================

pointer variable is initialised as datatype *variablename (declaration


eg:int *ptr,x;
47

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.

You might also like