Sie sind auf Seite 1von 34

RESOURCE MATERIAL FOR C

Rules for Constructing Integer Constants

1. An integer constant must have at least one digit.


2. It must not have a decimal point.
3. It can be either positive or negative.
4. If no sign precedes an integer constant it is assumed to be positive.
5. No commas or blanks are allowed within an integer constant.

Rules for Constructing Floating Point constants.

1. A real constant must have at least one digit.


2. It must have a decimal point.
3. It could be either positive or negative.
4. Default sign is positive.
5. No commas or blanks are allowed within a real constant.

Rules for Constructing Character Constants

1. A character constant is a single alphabet, a single digit or a single special symbol


enclosed within single inverted commas. Both the inverted commas should point to the
left. Eg: ’A’ is a valid character constant whereas ‘A’ is not.
2. The maximum length of a character constant can be 1 character.

3. Facts about Characters:


1. Characters are internally represented by their ASCII values.
2. There can be more than one character in double quotes but not in single quotes.

Rules for Constructing Variable Names

1. A variable name is any combination of 1 to 31 alphabets, digits or underscores. It would


be safer to stick to the rule of 31 characters.
2. The first character in the variable name must be an alphabet or an underscore.
3. No commas or blanks are allowed within a variable name.
4. No special symbol other than an underscore can be used in a variable name.

Declaring constants and variable:

int a; //a is declared as integer type variable.


const int d; //d is declared as a an integer type which will have a constant value.
float b; //b is declared as character type variable.
char ch; //ch is declared as character type variable.

(a=a+7 is valid, while d=d+7 is an error since d is declared as a constant)


Semicolon is a statement terminator in C. Every statement must end with a semicolon.
Ex:
int a;
a=b+c;

Initializing of a variable:
syntax:data_type variable_name=intialized_value;
ex:int x=25;
char ch='g';

Comments
Comments in C are enclosed :
1. by slash/star pairs: /* .. comments .. */ which may cross multiple lines or
2. by two slashes and extending to the end of the line: // comment until the line end. This
comments only one line. C doesn’t support nested comments.

Operators in C:
Assignment Operator( =)
The assignment operator is the single equals sign (=).
ex: i = 6;
i = i + 1;
The assignment operator copies the value from its right hand side to the variable on its left hand
side. The assignment also acts as an expression which returns the newly assigned value. Some
programmers will use that feature to write things like the following.
y = (x = 2 * x); // double x, and also put x's new value in y

Truncation
The opposite of promotion, truncation moves a value from a type to a smaller type. In that case,
the compiler just drops the extra bits. It may or may not generate a compile time warning of the
loss of information. Assigning from an integer to a smaller integer (e.g.. long to int, or int to
char) drops the most significant bits. Assigning from a floating point type to an integer drops the
fractional part of the number.
char ch;
int i;
i = 321;
ch = i;
// truncation of an int value to fit in a char
// ch is now 65
The assignment will drop the upper bits of the int 321. The lower 8 bits of the number 321
represents the number 65 (321 - 256). So the value of ch will be (char) 65 which happens to be
'A'.
The assignment of a floating point type to an integer type will drop the fractional part of the
number. The following code will set i to the value 3. This happens when assigning a floating point
number to an integer or passing a floating point number to a function which takes an integer.
double pi;
int i;
pi = 3.14159;
i = pi;
// truncation of a double to fit in an int
// i is now 3

Mathematical Operators

Using parenthesis liberally to avoid any bugs due to a misunderstanding of precedence. The
operators are sensitive to the type of the operands. So division (/) with two integer arguments
will do integer division. If either argument is a float, it does floating point division. So (6/4)
evaluates to 1 while (6/4.0) evaluates to 1.5 -- the 6 is promoted to 6.0 before the division.
+Addition
- Subtraction
/ Division
* Multiplication
% Remainder (mod)

Unary Increment Operators: ++ --

The unary ++ and -- operators increment or decrement the value in a variable. There are
"pre" and "post" variants for both operators which do slightly different things (explained below)
var++ increment "post" variant
++var increment "pre" variant
var-- decrement "post" variant
--var decrement "pre" variant

int i = 42;
i++;
// increment on i
// i is now 43
i--;
// decrement on i
// i is now 42

Pre and Post Variations


The Pre/Post variation has to do with nesting a variable with the increment or decrement
operator inside an expression -- should the entire expression represent the value of the variable
before or after the change?
int i = 42;
int j;
j = (i++ + 10);
// i is now 43
// j is now 52 (NOT 53)
j = (++i + 10)
// i is now 44
// j is now 54

Relational Operators

These operate on integer or floating point values and return a 0 or 1 boolean value.
== Equal
!= Not Equal
> Greater Than
< Less Than
>= Greater or Equal
<= Less or Equal

To see if x equals three, write it as:


if (x == 3) ...

Pitfall

An absolutely classic pitfall is to write assignment (=) when you mean comparison (==). This
would not be such a problem, except the incorrect assignment version compiles fine because the
compiler assumes you mean to use the value returned by the assignment. This is rarely what you
want.

if (x = 3), this does not test if x is 3. This sets x to the value 3, and then returns the to if for
testing. 3 is not 0, so it counts as "true" every time. This is probably the single most common
error made by beginning C programmers. The problem is that the compiler is no help -- it thinks
both forms are fine, so the only defence is extreme vigilance when coding.

Logical Operators

The value 0 is false, anything else is true. The operators evaluate left to right and stop as soon
as the truth or falsity of the expression can be deduced. (Such operators are called "short
circuiting")
! Boolean not (unary)
&& Boolean and
|| Boolean or

Bitwise Operators

C includes operators to manipulate memory at the bit level. This is useful for writing low-
level hardware or operating system code where the ordinary abstractions of numbers,
characters, pointers, etc... are insufficient -- an increasingly rare need. Bit manipulation
code tends to be less "portable". Code is "portable" if with no programmer intervention it
compiles and runs correctly on different types of computers. The bitwise operations are
typically used with unsigned types. In particular, the shift operations are guaranteed to
shift 0 bits into the newly vacated positions when used on unsigned values.
~ Bitwise Negation (unary) – flip 0 to 1 and 1 to 0 throughout
& Bitwise And
| Bitwise Or
^ Bitwise Exclusive Or
>> Right Shift by right hand side (RHS) (divide by power of 2)
<< Left Shift by RHS (multiply by power of 2)

Do not confuse the Bitwise operators with the logical operators. The bitwise connectives
are one character wide (&, |) while the Boolean connectives are two characters wide (&&,
||). The bitwise operators have higher precedence than the Boolean operators. The
compiler will never help you out with a type error if you use & when you meant &&. As
far as the type checker is concerned, they are identical-- they both take and produce

integers since there is no distinct boolean type.

Other Assignment Operators

In addition to the plain = operator, C includes many shorthand operators which represents

variations on the basic =. For example "+=" adds the right hand side to the left hand side.

x = x + 10; can be reduced to x += 10;.


Here's the list of assignment shorthand operators...

+=, -= Increment or decrement by RHS

*=, /= Multiply or divide by RHS

%= Mod by RHS

>>= Bitwise right shift by RHS (divide by power of 2)

<<= Bitwise left shift RHS (multiply by power of 2)

&=, |=, ^=

Bitwise and, or, xor by RHS

Precedence Order of Operators in C:


Operator Description
Associativity
() Parentheses (function call) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement
++ -- Prefix increment/decrement right-to-left
+ - Unary plus/minus
! ~ Logical negation/bitwise complement
(type) Cast (change type)
* Dereference
& Address
sizeof Determine size in bytes

* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-
right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment

main()
Every C program must contain a main function.It is not possible to write a C program without a
mian function,although it can be compiled.The main function serves as the starting point for
program execution. It usually controls program execution by directing the calls to other
functions in the program. A program usually stops executing at the end of main, although it can
terminate at other points in the program for a variety of reasons. At times, perhaps when a
certain error is detected, you may want to force the termination of a program. To do so, use the
exit function.

printf()
printf function is used to Format and print data.
Ex::
int x=25;
printf(“hii”);
printf(“value of x=%d”,x);

output will be like: hii value of x=25

Format Specifiers
There are many format specifiers defined in C. Take a look at the following list:

Format
Data type
specifier
%i or %d int
%c char
%f float
%lf double
String
%s

Hexadecimal
%x
number
%o Octal number

Commonly used escape sequences are:


 \n (newline)
 \t (tab)
 \v (vertical tab)
 \f (new page)
 \b (backspace)
 \r (carriage return)
 \n (newline)
the string format conversion reacts very different from number format conversions.
 The printf(“:%s:\n”, “Hello, world!”); statement prints the string (nothing special
happens.)
 The printf(“:%15s:\n”, “Hello, world!”); statement prints the string, but print 15
characters. If the string is smaller the “empty” positions will be filled with “whitespace.”
 The printf(“:%.10s:\n”, “Hello, world!”); statement prints the string, but print only 10
characters of the string.
 The printf(“:%-10s:\n”, “Hello, world!”); statement prints the string, but prints at least
10 characters. If the string is smaller “whitespace” is added at the end. (See next
example.)
 The printf(“:%-15s:\n”, “Hello, world!”); statement prints the string, but prints at least
15 characters. The string in this case is shorter than the defined 15 character, thus
“whitespace” is added at the end (defined by the minus sign.)
 The printf(“:%.15s:\n”, “Hello, world!”); statement prints the string, but print only 15
characters of the string. In this case the string is shorter than 15, thus the whole string is
printed.
 The printf(“:%15.10s:\n”, “Hello, world!”); statement prints the string, but print 15
characters.
If the string is smaller the “empty” positions will be filled with “whitespace.” But it will
only print a maximum of 10 characters, thus only part of new string (old string plus the
whitespace positions) is printed.
 The printf(“:%-15.10s:\n”, “Hello, world!”); statement prints the string, but it does the
exact same thing as the previous statement, accept the “whitespace” is added at the end.
Scanf()
scanf is a function that reads data with specified format from a given string stream source.The
scanf function is found in C, in which it reads input for numbers and other datatypes from
standard input.
ex::

printf("Enter a number:");
scanf("%d",&myvariable); //the value given by the user will be stored in
variable “myvariable”
printf("%d",myvariable);

library functions()
A header file is a file containing C declarations and macro definitions to be shared between
several source files. You request the use of a header file in your program by including it, with the
C preprocessing directive `#include'. System header files declare the interfaces to parts of the
operating system. You include them in your program to supply the definitions and declarations
you need to invoke system calls and libraries.
Both user and system header files are included using the preprocessing directive
`#include'. It has two variants:
#include <file>
This variant is used for system header files. It searches for a file named
file in a standard list of system directories. You can prepend directories
to this list with the -I option (see Invocation).
#include "file"
This variant is used for header files of your own program. It searches for
a file named file first in the directory containing the current file, then
in the quote directories and then the same directories used for <file>.
preprocessor directives
The preprocessing step happens to the C source before it is fed to the compiler. The two most
common preprocessor directives are #define and #include...
#define

The #define directive can be used to set up symbolic replacements in the source.#define is
extremely unintelligent -- it just does textual
replacement without understanding.
#define statements are used as a crude way of
establishing symbolic constants.

#define MAX 100

#define SEVEN_WORDS that_symbol_expands_to_all_these_words

Later code can use the symbols MAX or SEVEN_WORDS which will be replaced by the

text to the right of each symbol in its #define.

#include
:Discussed above,in the library functions
typecasting
Conversion of one data type to a different data type is known as Type casting .It is of 2 types:
1.Implicit typecasting
2.Excplicit typecasting

Implicit typecasting Explicit Typecasting


Typecasting is done by the system Typecasting is done by the programmer
Ex: Ex:
int a=10.8 //10.8 is converted into integer char x=100;
value float p=3.678;
the value 10 gets stored in a. printf("%d\n",(int) p); //3
Char ch=65 //corresponding ASCII
character(A) printf("%f\n",(float) x); //100.00
gets stored in ch.
It has permanent effect on the variable. It has temporary effect on the variable.Only
during the time in which that particular
statement is executed.

REFER:http://msdn.microsoft.com/en-
US/library/d3d6fhea%28v=VS.80%29.aspx

Control Structures

Curly Braces {}

C uses curly braces ({}) to group multiple statements together. The statements execute in

order.

If Statement

Both an if and an if-else are available in C. The <expression> can be any valid expression. The
parentheses around the expression are required, even if it is just a single variable.
if (<expression>) <statement>// simple form with no {}'s or else clause
if (<expression>)
{ // simple form with {}'s to group statements
<statement>
<statement>

}
if (<expression>)
{ // full then/else form
<statement>
}
else
{
<statement>
}

Conditional Expression -or- The Ternary Operator

The conditional expression can be used as shorthand for some if-else statements. The

general syntax of the conditional operator is:

<expression1> ? <expression2> : <expression3>

This is an expression, not a statement, so it represents a value. The operator works by


evaluating expression1. If it is true (non-zero), it evaluates and returns expression2 .
Otherwise, it evaluates and returns expression3.
The classic example of the ternary operator is to return the smaller of two variables.
Every once in a while, the following form is just what you needed. Instead of...
if (x < y)
{
min = x;
}
else
{
min = y;
}

You just say...


min = (x < y) ? x : y;

Switch Statement

The switch statement is a sort of specialized form of if used to efficiently separate different
blocks of code based on the value of an integer. The switch expression is evaluated, and then
the flow of control jumps to the matching const-expression case. The case expressions are
typically int or char constants. The switch statement is probably the single most syntactically
awkward and error-prone features of the C language.
switch (<expression>)
{
case <const-expression-1>:
<statement>
break;
case <const-expression-2>:
<statement>
break;
case <const-expression-3>:
case <const-expression-4>:
<statement>
break;
// here we combine case 3 and 4
default:// optional
<statement>

Each constant needs its own case keyword and a trailing colon (:). Once execution has
jumped to a particular case, the program will keep running through all the cases from that
point down -- this so called "fall through" operation is used in the above example so that
expression-3 and expression-4 run the same statements. The explicit break statements
are necessary to exit the switch. Omitting the break statements is a common error -- it
compiles, but leads to inadvertent fall-through behaviour.

While Loop
The while loop evaluates the test expression before every loop, so it can execute zero
times if the condition is initially false. It requires the parenthesis like the if.

while (<expression>)
{
<statement>
}

Do-While Loop

Like a while, but with the test condition at the bottom of the loop. The loop body will always
execute at least once. The do-while is an unpopular area of the language, almost everyone tries
to use the straight while if at all possible.

do
{
<statement>
} while (<expression>)

For Loop
The for loop in C is the most general looping construct. The loop header contains three parts:
an initialization, a continuation condition, and an action.
for (<initialization>; <continuation>; <action>)
{
<statement>
}

The initialization is executed once before the body of the loop is entered. The loop continues to
run as long as the continuation condition remains true (like a while). After every execution of the
loop, the action is executed. The following example executes 10 times by counting 0..9. Many
loops look very much like the following...
for (i = 0; i < 10; i++)
{
<statement>
}
C programs often have series of the form 0..(some_number-1). It's idiomatic in C for the
above type loop to start at 0 and use < in the test so the series runs up to but not equal to the
upper bound. In other languages you might start at 1 and use <= in the test.
Each of the three parts of the for loop can be made up of multiple expressions separated
by commas. Expressions separated by commas are executed in order, left to right, and represent
the value of the last expression.
Break
The break statement will move control outside a loop or switch statement. Sometimes you are
forced to use a break
because the test can occur only somewhere in the midst of the statements in the loop
body.
while (<expression>)
{
<statement>
<statement>
if (<condition which can only be evaluated here>)
break;
<statement>
<statement>
}// control jumps down here on the break

The break does not work with if. It only works in loops and switches. Thinking that a break
refers to an if when it really refers to the enclosing while has created some high quality bugs.
When using a break, it's nice to write the enclosing loop to iterate in the most straightforward,
obvious, normal way, and then use the break to explicitly catch the exceptional, weird cases.

Continue
The continue statement causes control to jump to the bottom of the loop, effectively skipping
over any code below the continue. As with break, this has a reputation as being vulgar, so use it
sparingly. You can almost always get the effect more clearly using an if inside your loop.

while (<expression>)
{

...if (<condition>)
continue;
...// control jumps here on the continue
}
ARRAYS
An array in C Programing Language can be defined as number of memory locations, each of
which can store the same data type and which can be references through the same variable
name.
Declaration of an Array
Arrays must be declared before they can be used in the program. Standard array declaration is
as:
type variable_name[lengthofarray];

Here type specifies the variable type of the element which is going to be stored in the array. In
C programmin language we can declare the array of any basic standard type which C language
supports. For example:
double height[10];
char name[20];

In C Language, arrays starts at position 0. The elements of the array occupy adjacent locations
in memory.
Any item in the array can be accessed through its index, and it can be accesed any where from
with in the program. So
m=height[0];

variable m will have the value of first item of array height.


Initializing arrays:
Initializing of array is very simple in c programming. The initializing values are enclosed within
the curly braces in the declaration and placed following an equal sign after the array name. Array
can also be initialized after declaration
int myArray[5] = {1, 2, 3, 4, 5}; //declare and initialize the array in one statement
int studentAge[4];
studentAge[0]=14;
studentAge[1]=13;
studentAge[2]=15;
studentAge[3]=16;

Multi dimensional Arrays:

Often there is a need to store and manipulate two dimensional data structure such as matrices &
tables. Here the array has two subscripts. One subscript denotes the 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]
Here m is declared as a matrix having 10 rows( numbered from 0 to 9) and 20 columns(numbered
0 through 19). The first element of the matrix is m[0][0] and the last row last column is m[9][19]

Elements of multi dimension arrays:


A 2 dimensional array marks [4][3] is shown below figure. The first element is given by marks
[0][0] contains 35.5 & second element is marks [0][1] and contains 40.5 and so on.
marks [0][0] Marks [0][1] Marks [0][2]
35.5 40.5 45.5

marks [1][0] Marks [1][1] Marks [1][2]


50.5 55.5 60.5

marks [2][0] Marks [2][1] Marks [2][2]

marks [3][0] Marks [3][1] Marks [3][2]

Initialization of multidimensional arrays:


Like the one dimension arrays, 2 dimension arrays may be initialized by following their
declaration with a list of initial values enclosed in braces

Example:
int table[2][3]={0,0,0,1,1,1};
Initializes the elements of first row to zero and second row to 1. The initialization is done row by
row. The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}}

STRINGS
In C language Strings are defined as an array of characters or a pointer to a portion of memory
containing ASCII characters. A string in C is a sequence of zero or more characters followed by
a NULL '\0' character:
 It is important to preserve the NULL terminating character as it is how C defines and
manages variable length strings. All the C standard library functions require this for
successful operation.
 If you were to have an array of characters WITHOUT the null character as the last
element, you'd have an ordinary character array, rather than a string constant.
 String constants have double quote marks around them, and can be assigned to char
pointers as shown below. Alternatively, you can assign a string constant to a char array -
either with no size specified, or you can specify a size, but don't forget to leave a space
for the null character!
char *string_1 = "Hello";
char string_2[] = "Hello";
char string_3[6] = "Hello";

One possible way to read in a string is by using scanf. However, the problem with this, is that if
you were to enter a string which contains one or more spaces, scanf would finish reading when it
reaches a space, or if return is pressed. As a result, the string would get cut off. So we could use
the gets function
A gets takes just one argument - a char pointer, or the name of a char array, but don't forget to
declare the array / pointer variable first! What's more, is that it automatically prints out a
newline character, making the output a little neater.
We can also use scanf for inputting a string.
scanf(“%s”,string); //input terminates with a space
scanf(“%[^\n]”,string); //input terminates with a \n(new line)
scanf(“%[^.]”,string); //input terminates with a full stop.
A puts function is similar to gets function in the way that it takes one argument - a char pointer.
This also automatically adds a newline character after printing out the string. Sometimes this can
be a disadvantage, so printf could be used instead.

Stdlib.h:
This library supports a function which converts a string of digits into their integer values.
The function is of the form:
x=atoi(string);

string.h
The string library (string.h or strings.h) has some useful functions for working with strings, like
strcpy, strcat, strcmp, strlen, strcoll, etc.
Important: Don’t forget to include the library string.h (or on some systems strings.h) if you want
to use one of these library functions.

strcpy
This library function is used to copy a string and can be used like this: strcpy(destination,
source). (It is not possible in C to do this: string1 = string2). Take a look at the following
example:

str_one = "abc";
str_two = "def";
strcpy(str_one , str_two); // str_one becomes "def"

Note: strcpy() will not perform any boundary checking, and thus there is a risk of overrunning
the strings.

strcmp
This library function is used to compare two strings and can be used like this: strcmp(str1, str2).
 If the first string is greater than the second string a number greater than null is returned.
 If the first string is less than the second string a number less than null is returned.
 If the first and the second string are equal a null is returned.
Take look at an example:

printf("Enter you name: ");


scanf("%s", name);
if( strcmp( name, "jane" ) == 0 )
printf("Hello, jane!\n");

Note: strcmp() will not perform any boundary checking, and thus there is a risk of overrunning
the strings.

strcat
This library function concatenates a string onto the end of the other string. The result is
returned. Take a look at the example:

printf("Enter you age: ");


scanf("%s", age);
result = strcat( age, " years old." ) == 0 )
printf("You are %s\n", result);

Note: strcat() will not perform any boundary checking, and thus there is a risk of overrunning
the strings.

strlen
This library function returns the length of a string. (All characters before the null termination.)
Take a look at the example:

name = "jane";
result = strlen(name); //Will return size of four.

STRUCTURES AND UNIONS


Arrays are used to store large set of data and manipulate them but the disadvantage is that all
the elements stored in an array are to be of the same data type. If we need to use a collection of
different data type items it is not possible using an array. When we require using a collection of
different data items of different data types we can use a structure. Structure is a method of
packing data of different types. A structure is a convenient method of handling a group of related
data items of different data types.
the keyword struct declares a structure to holds the details of four fields namely title, author
pages and price. These are members of the structures. Each member may belong to different or
same data type. The tag name can be used to define objects that have the tag names structure.
The structure we just declared is not a variable by itself but a template for the structure.
book1,book2,book3 are declared as variables of type struct lib_books each declaration has four
elements of the structure lib_books.

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

struct lib_books, book1, book2, book3;


book1=book2 ; //used to copy entire data in book 2 to book1

the keyword struct declares a structure to holds the details of four fields namely title, author
pages and price. These are members of the structures. Each member may belong to different or
same data type. The tag name can be used to define objects that have the tag names structure.
The structure we just declared is not a variable by itself but a template for the structure.
book1,book2,book3 are declared as variables of type struct lib_books each declaration has four
elements of the structure lib_books. structures do not occupy any memory until it is associated
with the structure variable such as book1. the template is terminated with a semicolon.

We can also combine both template declaration and variables declaration in one statement, the
declaration

struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
} book1,book2,book3;
is valid. The use of tag name is optional for example
struct
{



}

book1, book2, book3 declares book1,book2,book3 as structure variables representing 3 books


but does not include a tag name for use in the declaration.
A structure is usually defines before main along with macro definitions. In such cases the
structure assumes global status and all the functions can access the structure.

Giving values to members:


As mentioned earlier the members themselves are not variables they should be linked to
structure variables in order to make them meaningful members. The link between a member and
a variable is established using the member operator ‘.’ Which is known as dot operator or
period operator.

For example:

Book1.price

Is the variable representing the price of book1 and can be treated like any other ordinary
variable. We can use scanf statement to assign values like

scanf(“%s”,book1.file);
scanf(“%d”,& book1.pages);

Or we can assign variables to the members of book1

strcpy(book1.title,”basic”);
strcpy(book1.author,”Balagurusamy”);
book1.pages=250;
book1.price=28.50;

Initializing structure:
Like other data type we can initialize structure when we declare them. As for initalization goes
structure obeys the same set of rules as arrays we initalize the fields of a structure by the
following structure declaration with a list containing values for weach fileds as with arrays these
values must be evaluate at compile time.

Example:

Struct student newstudent


{
“Book For C-Language “;
“XYZ” ;
320;
19;
};
this initializes the title field to Book For C-Language, the author field to XYZ, the pages to 320
and the price field to 19.

Functions and structures:


We can pass structures as arguments to functions. Unlike array names however, which always
point to the start of the array, structure names are not pointers. As a result, when we change
structure parameter inside a function, we don’t effect its corresponding argument.

Passing structure elements to functions:


A structure may be passed into a function as individual member or a separate variable.
A program example to display the contents of a structure passing the individual elements to a
function is shown below.

# include <stdio.h>
void main()
{
int emp_id;
char name[25];
char department[10];
float salary;
};

static struct emp1={125,”sampath”,”operator”,7500.00};


/* pass only emp_id and name to display function*/
display(emp1.emp_id,emp1.name);
}
/* function to display structure variables*/
display(e_no,e_name)
int e_no,e_name;
{
printf(“%d%s”,e_no,e_name);

in the declaration of structure type, emp_id and name have been declared as integer and
character array. When we call the function display() using display(emp1.emp_id,emp1.name);
we are sending the emp_id and name to function display(0);
it can be immediately realized that to pass individual elements would become more tedious as the
number of structure elements go on increasing a better way would be to pass the entire
structure variable at a time.

Passing entire structure to a function:


In case of structures having to having numerous structure elements passing these individual
elements would be a tedious task. In such cases we may pass whole structure to a function as
shown below:

# include <stdio.h>
struct employee{
int emp_id;
char name[25];
char department[10];
float salary;
};

void main()
{
static struct employee emp1=
{
12,
“sadanand”,
“computer”,
7500.00
};

/*sending entire employee structure*/


display(emp1);
}

/*function to pass entire structure variable*/


display(empf)
struct employee empf
{
printf(“%d%s,%s,%f”, empf.empid,empf.name,empf.department,empf.salary);
}

Arrays of structure:
It is possible to define a array of structures for example if we are maintaining information of all
the students in the college and if 100 students are studying in the college. We need to use an
array than single variables. We can define an array of structures as shown in the following
example:

structure information
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}
student[100];

An array of structures can be assigned initial values just as any other array can. Remember that
each element is a structure that must be assigned corresponding initial values

Structure within a structure:


A structure may be defined as a member of another structure. In such structures the declaration
of the embedded structure must appear before the declarations of other structures.

struct date
{
int day;
int month;
int year;
};
struct student
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
structure date def;
structure date doa;
}oldstudent, newstudent;

the sturucture student constains another structure date as its one of its members.

Union:
Unions like structure contain members whose individual data types may differ from one another.
However the members that 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 conserve memory. They are useful for application involving
multiple members. Where values need not be assigned to all the members at any one time. Like
structures union can be declared using the keyword union as follows:
union item
{
int m;
float p;
char c;
}
code;

this declares a variable code of type union item. The union contains three members each with a
different data type. However we can use only one of them at a time. This is because if only one
location is allocated for union variable irrespective of size. The compiler allocates a piece of
storage that is large enough to access a union member we can use the same syntax that we use
to access structure members. That is

code.m
code.p
code.c

are all valid member variables. During accessing we should make sure that we are accessing the
member whose value is currently stored.
For example a statement such as

code.m=456;
code.p=456.78;
printf(“%d”,code.m);

Would produce erroneous result.

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 a new value the new value supercedes the previous
members value. Unions may be used in all places where a structure is allowed. The notation for
accessing a union member that is nested inside a structure remains the same as for the nested
structure.

FUNCTIONS
A function is a self-contained block of statements that performs a coherent task of some kind.
A C program consists of one or more function definitions, including exactly one that must be
called main.
A function can return a value to the calling program: When a program calls a function, the
statements in it are executed. A function returns information back to the calling program in the
following ways:
‰ return (constant);
‰ return (variable);
‰ return (expression);
return;
A function consists of the following parts:
1) Function prototype declaration: A declaration merely provides a function prototype. It
includes the return type and the list of parameters.
Syntax: return_type function_name (argument 1, argument 2…);
Example: int sum(int val1, int val2);
2) Function definition: The definition of a function includes both the function prototype and
the function body, i.e. its implementation.
Syntax:
return_typ function_name(argument 1,argument 2….)
{
/* statements;
return statement;
}
Example:
int sum(int val1, int val2)
{ int val3;
val3 = val1 + val2;
return val3;
}
#default return type will be int.
#the return type must be void if no value is being returned
#to indicate empty parameter list,the word void is used.
Function parameters:
There are two types of function parameters:
1) Formal parameters: Appear in the definition of function.
2) Actual parameters: Appear in a call to the function
TYPES OF FUNCTIONS
• Functions with no arguments and no return value
• Functions with arguments and no return value
• Functions with arguments and one return value
• Functions with no arguments but return a value
• Function that return a multiple value (using pointers)

Passing Arguments to a Function

1) Pass by value:
Single value is passed to a function via an actual argument.
The value of actual argument is copied into a function.
The value of corresponding argument can be altered within the function.
The value of the actual argument within the calling routine will not be changed.
2) Pass by reference:
Single value is passed to a function via an actual argument.
The address of actual argument is passed into a function.
The value of corresponding argument can be altered within the function.
The value of the actual argument within the calling routine will also be changed.
STORAGE CLASSES
Storage Classes in C indicate:
- Where the variable would be stored
- What will be the initial value of the variable
- What is the scope of the variable
- What is the life time of the variable

Classification of storage classes:


1) Automatic variable:
Key word auto is used in the declaration
Storage – Memory
Default initial value – Garbage value
Scope – Local to the block in which it is defined
Life – Till the control remains within the block in which the variable is defined

2) Register variable:
Key word register is used in the declaration Eg: register int count;
Frequently used variables are declared as register variables such as counters.
Storage – CPU registers.
Default initial value – Garbage value
Scope – Local to the block in which it is defined
Life – Till the control remains within the block in which the variable is defined

3) Static variable:
Key word static is used in the declaration. Eg: static int x;
The difference between auto and static variable is that static variables does not
disappear when the function is no longer active. Their value persists.
Storage – Memory
Default initial value – Zero
Scope – Local to the block in which it is defined
Life – value of the variable persists between different function calls.

4) External variable:
Alive and active throughout the entire program
Also known as global variables
Declared outside the function
In case a local and global variable have same name, the local variable will have
precedence over the global variable in the function where it is declared.
Storage – Memory
Default initial value – Zero
Scope – Global
Life – As long as the programs execution doesn’t come to an end.

POINTERS
A pointer is a variable which stores an address.
In the declaration int i=3;
i= location name
3= value at location
65524 = location number ie &i

& Address operator


* Value at address operator or indirection operator

Declaration of pointers:
Int * i here i is a pointer to an integer
float * j here j is a pointer to a float value
int **k here k is a pointer to an integer pointer
int ***l here l is a pointer to a pointer to an integer pointer
and so on.

Initialization of pointer variables:


int i;
int *p;
p=&i;
the first line declares i as an integer variable. p is an integer pointer and is initialized
with the address of i.
The above example can also be merged and written as:
int i;
int *p=&i; //make sure that i is declared before this step.
Accessing a variable through its pointer:
int i, n;
int *p;
p=&i;
n=*p;
the first line declares i and n as integer variables. p is an integer pointer and is
initialized with the address of i. The value stored at address in p is assessed through
the * operator.

POINTER EXPRESSIONS:
p1 and p2 are properly declared and initialized variables.
The following expressions are valid:
y=*p1 * *p2;
sum=sum + *p1;
z=5* - *p1 / *p2; //space between / and * to be noted
*p2 = *p2 +10;
p1++;
p1-p2;
the following expressions are invalid:
p1 / p2; //pointers cannot be used in multiplication and division.
p1 * p2;

POINTERS AND ARRAYS


The elements of an array are stored in contiguous memory locations.
Eg: int a[5]={ 1,2,3,4,5 };

Here a[0]=1 1 is stored at address 1000


a[1]=2 2 is stored at address 1002
a[2]=3 3 is stored at address 1004
a[3]=4 4 is stored at address 1006
a[4]=5 5 is stored at address 1008
The name of an array is a constant pointer to the zeroth element of the array.
So if we declare p as an integer pointer; then we can make pointer p point to the
array a by the assignment
p=a which is equivalent to p=&a[0]
Now we can access every value of x using p++ to move from one element to other.
The relationship between p and x is as follows:
p=&a[0] (1000)
p+1=&a[1] (1002)
p+2=&a[2] (1004)
p+3=&a[3] (1006)
p+4=&a[4] (1008)
While handling arrays, instead of using array indexing, we can use pointers to access
array elements. Note that *(p+3) gives the value of x[3].

Pointers can be used to manipulate 2-D arrays as well.


x[i][j] in an array is equivalent to *(*(p+i)+j)
in a 2-D array,
p points to 1st row,
p+i points to ith row,
*(p+i) points to the 1st element in ith row,
*(p+i)+j points to the jth element in ith row,
*(*(p+i)+j) is the value stored in cell (i,j).

POINTERS AND CHARACTER STRINGS


Strings are treated like character arrays . They are declared and initialised as follows;
char str[5]=”good”
here str is the name of the array.
But if we write, char *str=”good”; this creates a string for the literal and then stores
its address in the pointer variable str. Initially the pointer str points to the first
character of the string,i.e,str[0].
The following is valid:
char *string1;
string1=”good”;
Here the assignment string1=”good” is valid because this is not string copy and
string1 is a pointer rather than a string.

ARRAY OF POINTERS
It is very difficult to handle an array of strings by using a 2-D array of characters. So
an array of pointers is used for dealing with multiple strings.
Char *names[3]={ “sita”,”rita”,”geeta”};
This is an array of 3 pointers to characters, each pointer pointing to a particular
element.
names[0] points to sita
names[1] points to rita
names[2] points to geeta
The following statements will print out these names:
for(i=0;i<=2;i++)
printf(“%s\n”,names[i]);

To access the jth character in the ith name, use *(name[i]+j)


Remember the following:
*p[3] is an array of 3 pointers while
(*)p[3] is a pointer to an array of 3 elements.

POINTERS AND STRUCTURES


Eg: struct matter
{ char city[20];
int p;
float price;
} product[2], *ptr;
The above statements declare product as an array of 2 elements, each of type struct
matter and ptr as a pointer to data objects of the type struct matter.
The assignment ptr=product; would assign the address of the zeroth element of
product to ptr. That is ptr will now point to product[0].Its members can be accessed
by using the arrow operator ->
ptr -> city
ptr -> p
ptr -> price
if ptr is incremented by 1, then ptr points to product[1].
Remember: To access structure elements by the name of structure, use dot( . )
operator.
Eg: product[0].city; or (*ptr).city; the parenthesis around *ptr are necessary as ‘.’
Has higher precedence than *
To access structure elements by using a pointer, use arrow operator( -> )
Eg: ptr->city

POINTERS AS FUNCTION ARGUMENTS:

Pointers can be used to pass the addresses of variables to a funtion.This process o


calling a funtion using pointers to pass the addresses of variables is known as 'call by
reference'.the function which is called by 'reference' can change the value of the
variable used in the call.
FUNCTIONS RETURNING POINTERS:

for a function to return multiple values pointers are used.

Example:

int *function_name (int *,float *)

the above mention function takes 2 pointers(one of int type,and other of float) and the
above function also return a pointer of int type.

Point to be noted:

the following 2 decalarations are different:

int *function_name() //declares it as a function returning pointer


type

int (*function_name) () //declares a pointer to the funtion.

DYNAMIC MEMORY ALLOCATION


Dynamic memory allocation permits us to allocate memory space at run time. There
are four library functions used for allocating and freeing memory during program
execution.These are as follows:
1) malloc: The malloc function reserves a block of memory of specified size and
returns a pointer of type void. This means we can assign it to any type of pointer.
Syntax : ptr=(cast-type*) malloc(total byte size)
Malloc allocates a block of contiguous bytes. The allocation can fail if the space
in the
heap is not sufficient to satisfy the request. If it fails it returns NULL.

2) calloc: While malloc allocates a single block of storage space, calloc


allocates multiple blocks of storage, each of the same size and then sets all bytes
to zero.
Syntax : ptr=(cast-type*) calloc(n, size of element)
A pointer to the first byte of allocated region is returned. If there is not enough
space, a NULL pointer is returned.
3) Free: It releases the space when it is not required.
Syntax : free(ptr)
ptr is a pointer to a memory block which has already been created by malloc or
calloc. Use of an invalid pointer in the call may create problems and cause system
crash.
Remember it is not the pointer that is being released, but rather what it points to.
To release an array of memory that was allocated by calloc, we only need to
release the pointer once. It is an error to attempt to release elements individually.

4) realloc: It is used if previously allocated memory is not sufficient and we need


additional space for more elements.
Syntax : ptr = realloc(ptr,newsize)
If the function is unsuccessful in locating additional space, it returns a NULL
pointer.

Command Line Arguments:


It is possible to pass arguments to C programs when they are executed. The brackets which
follow main are used for this purpose. argc refers to the number of arguments passed, and argv[]
is a pointer array which points to each argument which is passed to mainA simple example
follows, which checks to see if a single argument is supplied on the command line when the
program is invoked.
#include <stdio.>h
main( int argc, char *argv[] )
{
if( argc == 2 )
printf("The argument supplied is %s\n", argv[1]);
else if( argc > 2 )
printf("Too many arguments supplied.\n");
else
printf("One argument expected.\n");
}

Note that *argv[0] is the name of the program invoked, which means that *argv[1] is a pointer to
the first argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc
will be one. Thus for n arguments, argc will be equal to n + 1. The program is called by the
command line:
$myprog argument1

More clearly, Suppose a program is compiled to an executable program myecho and that the
program is executed with the following command.
$myeprog aaa bbb ccc

When this command is executed, the command interpreter calls the main() function of the
myprog program with 4 passed as the argc argument and an array of 4 strings as the argv
argument.
argv[0] - "myprog"
argv[1] - "aaa"
argv[2] - "bbb"
argv[3] - "ccc"

String Manipulation Functions


 char *strcpy (char *dest, char *src);
Copy src string into dest string.
 char *strncpy(char *string1, char *string2, int n);
Copy first n characters of string2 to stringl .
 int strcmp(char *string1, char *string2);
Compare string1 and string2 to determine alphabetic order.
 int strncmp(char *string1, char *string2, int n);
Compare first n characters of two strings.
 int strlen(char *string);
Determine the length of a string.
 char *strcat(char *dest, const char *src);
Concatenate string src to the string dest.
 char *strncat(char *dest, const char *src, int n);
Concatenate n chracters from string src to the string dest.
 char *strchr(char *string, int c);
Find first occurrence of character c in string.
 char *strrchr(char *string, int c);
Find last occurrence of character c in string.
 char *strstr(char *string2, char string*1);
Find first occurrence of string string1 in string2.
 char *strtok(char *s, const char *delim) ;
Parse the string s into tokens using delim as delimiter.

Memory Management Functions


 void *calloc(int num elems, int elem_size);
Allocate an array and initialise all elements to zero .
 void free(void *mem address);
Free a block of memory.
 void *malloc(int num bytes);
Allocate a block of memory.
 void *realloc(void *mem address, int newsize);
Reallocate (adjust size) a block of memory.

Buffer Manipulation
 void* memcpy(void* s, const void* ct, int n);
Copies n characters from ct to s and returns s. s may be corrupted if objects overlap.
 int memcmp(const void* cs, const void* ct, int n);
Compares at most (the first) n characters of cs and ct, returning negative value if cs<ct,
zero if cs==ct, positive value if cs>ct.
 void* memchr(const void* cs, int c, int n);
Returns pointer to first occurrence of c in first n characters of cs, or NULL if not found.
 void* memset(void* s, int c, int n);
Replaces each of the first n characters of s by c and returns s.
 void* memmove(void* s, const void* ct, int n);
Copies n characters from ct to s and returns s. s will not be corrupted if objects overlap.

Character Functions
 int isalnum(int c);
The function returns nonzero if c is alphanumeric
 int isalpha(int c);
The function returns nonzero if c is alphabetic only
 int iscntrl(int c);
The function returns nonzero if c is a control chracter
 int isdigit(int c);
The function returns nonzero if c is a numeric digit
 int isgraph(int c);
The function returns nonzero if c is any character for which either isalnum or ispunct
returns nonzero.
 int islower(int c);
The function returns nonzero if c is a lower case character.
 int isprint(int c);
The function returns nonzero if c is space or a character for which isgraph returns
nonzero.
 int ispunct(int c);
The function returns nonzero if c is punctuation
 int isspace(int c);
The function returns nonzero if c is space character
 int isupper(int c);
The function returns nonzero if c is upper case character
 int isxdigit(int c);
The function returns nonzero if c is hexa digit
 int tolower(int c);
The function returns the corresponding lowercase letter if one exists and if isupper(c);
otherwise, it returns c.
 int toupper(int c);
The function returns the corresponding uppercase letter if one exists and if islower(c);
otherwise, it returns c.

Error Handling Functions


 void perror(const char *s);
produces a message on standard error output describing the last error encountered.
 char *strerror(int errnum );
returns a string describing the error code passed in the argument errnum.

Das könnte Ihnen auch gefallen