c

C-LANGUAGE NOTES
Some words about Computer Programming languages
Naturally a language is the source of communication between two persons, and also between person to machine like computer. The languages we can use to communicate with the computer are known as Computer programming languages.
Generally there are two major types of languages are available are as follows:
  1. Low level languages
  2. The set of commands available in low level is complex and not easy to understandable. In this category " Assembly " and " machine codes " are available. Assembly programs are faster than other high-level language programs.
  3. High level languages
·  The set of commands available in high level language is very simple and easy to understandable.
High level languages are further divided into two major categories.
  1. Procedure Oriented language
In this category we are able to create our project or programs using procedural approach means in this type we can able to divide our big project/program into small subroutines or procedures. After making procedures we can able to call a ‘procedure’ one or more places.
The lists of procedural languages are as follows:
C language
C++ (Object Oriented)
Java (Objected Oriented)
Smalltalk (Objected Oriented)
Pascal language
  1. Non-Procedural Languages: This category also known as ‘Problem Oriented languages’. In this type of languages we can able to make program only at specific range like database. The followings are the examples of Non procedural languages
  1. SQL (Structured Query Language)
  2. SNOBOL (String processor)
 C LanguageHistory
  • Developed at Bell Laboratories. first standard version release in 1972.
  • Developed by Dennis Richee.
  • Before c a Programming language is very popular in those days the name of the language is B-Language so the developers decided the name of ‘C’ language because C is next to B.
Editors :
UNIXC
TURBOC
AT&T C
BORELANDC


The Integrated Development Environment (IDE):
Turbo c features as integrated Development environment, or IDE,. It is also referred to as the programmer’s platform.) in IDE you can able to write/save/open your programs or code, compile using short cut keys, and also perform code debugging very easily.
IDE
Common Short cut Keys Description
F2 press to Save current work
F3 press to open an existing file
ALT-F3 press to close current
ALT-F9 press to compile only
ALT-F5 press to view the desired output of the program.
CTRL-F9 press to compile+run
ALT-X or ALT-F-X press to exit from TC IDE
·  C Programs Skeleton (General)
< Global Variable (on your demand)>
main () (Necessary)
{ statements }
< function definition>
{ }
Remember Some common rules for writing C program
  • Use all commands or statements in lower or small case.
  • After completion of a statement excluding main() or loops must insert ; (semicolon) as a statement terminator.
  • Don’t use/declare identifier or variable name same as statement name suppose int include; this is a wrong statement because include has a special meaning in the language.
·  Header Files or Preprocessor Directives contains references or links of library functions. That is built-in in the C language.                                                                                                                                            Suppose if you want to use a function clrscr() ; in the main function so must be declared on top # include other wise you could have an prototype error.
Some header files are as follows
Stdio.h
Conio.h
Dos.h
String.h
Stdlib.h
And many more header files are available in C…
void main(void)
Every C programs consists of one or more functions. No matter how many  functions there are in a C program , main is the one to which control is passed  from the operating system when the program is run ; it is the first function  executed. The word "void" preceding "main" specifies that the function main()  will not return a value. The second "void," in parenthesis , specifies that the  unction takes no arguments.
printf()
printf() is built-in function we can display with printf() any message, variable  value on screen/file/printer.
In printf() we can use many escape sequences and format specifies.
Escape sequences are special notations through which we can display our data Variety of ways:
Some escape sequences and their functions are as follows:
Escape Sequence
Description
Example
\n
Perform line feed & Carriage return operation
printf("A\nB");
\t
Prints a tab sequence on screen
printf ("A\tb");
\’
Prints a single quote character on screen
printf ("\’a\’");
\"
Prints a double quote character on Screen
printf ("\"a\"");
\r
Perform carriage return operation
printf ("a\rb");
\b
Remove one character from left



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


printf ("a\bHi!" );
Example Program #1
  #include
#include
void main()
{
printf( " Example Program (Escape Sequence) \n");
printf( " -----------------------------------------------\n");
printf( "Escape sequnce \t Meaning\n");
printf( " -------------------------------------------------\n");
printf(" \\\\ \t \\" \n");
printf(" \\\’ \t \’ \n");
              printf(" \\\" \t \" \n");
 printf(" \\n \t line feed & carriage return\n ");
printf(" \\t \t Tab characters or eigth spaces\n");
printf(" \\b \t Erase one char from right to left\n");
printf(" \\r \t perform only line feed\n");
getch();
}
This program produces following output
Example Program (Escape Sequence)                                                                                                                 --------------------------------------------                                                                                                                                Escape Sequence Meaning                                                                                                                                                    ------------------------------------------
\\ \
\’ ‘
\" \"
\n line feed & carriage return
\t Tab Characters or eight spaces
\b Erase one char from right to left
\r perform only line feed



Example Program #2
 #include
#include
void main(void)
{
clrscr();
printf( " \" India ZindaBad\" \n");
getch();
}
This program produces following output
"India ZindaBad"
Description : in the above we use a escape sequence \" this will produce " on screen after that a message Pakistan ZindaBad is appear after the message another " ( double quotation) appear on screen because of \"
1. Program to print text
# include
# include
main()
{
clrscr();
printf(“HELLO WELCOME TO WINGS TECHNOLOGYS”);
printf(“DSNR   HYD”);
getch();

}


CHARACTERISTICS OF ‘C’ LANGUAGE/MAIN FEATURES

1. Modularity.
2. Portability.
3. Extendibility.
4. Speed.
5. Flexibility.
Modularity: Ability to breakdown a large module into manageable sub modules called as modularity, that is an important feature of structured programming languages.
Advantages:
1. Projects can be completed in time.
2. Debugging will be easier and faster.
Portability:
The ability to por/t i.e. to install the software in different platform is called portability.
Highest degree of portability: ‘C’ language offers highest degree of portability i.e., percentage of changes to be made to the sources code are at minimum when the software is to be loaded in another platform. Percentage of changes to the source code is minimum. The software that is 100% portable is also called as platform independent software or architecture neutral software. Eg: Java.
Extendability: Ability to extend the existing software by adding new features is called as extendability.
SPEED:
‘C’ is also called as middle level language because programs written in ‘c’ language run at the speeds matching to that of the same programs written in assembly language so ‘c’ language has both the merits of high level and middle level language and because if this feature it is mainly used in developing system software.
Flexibility: Key words or reverse words
ANSIC has 32 reverse words
‘C’ language has right number of reverse words which allows the programmers to have complete control on the language.
‘C’ is also called as programmer’s language since it allows programmers to induce creativeness into the programmers.

 

Chapter-1

*What is c?
*Character set
*Constants
*Variable
*Data Types
*Declaring a variable
*Assigning Values
*Symbolic Constants
*Basic Structure of a C program
What is c?
C is a programming language developed at AT & T's Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie.
Character Set:
            C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and certain special characters as building blocks to form basic program elements (eg: constants, variables, operators, expressions, etc.).
Alphabets
A, B, ….., Y, Z
a, b, ……, y, z
Digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
~ ‘ ! @ #  % ^ & * ( ) _ - + =| \ { } [ ] : ;  “ ‘ < > , . ? /
Constants:
Constants in C refer to fixed values that do not change during the execution of a program. The following are the different types of constants.
            1.Integer constants
            2.real constants
            3.character constants
            4.string constants
1.Integer constants:
An integer constant is an integer-valued number.  Thus it consists of a sequence of digits. Integer constants can be written in three different number system:
a) decimal (base 10)
b) octal (8)
c) hexadecimal (base 16). 
a) decimal (base 10):
A decimal integer constant can consist of any combination of digits taken from the set 0 through 9.  If the constant contains two or more digits, the first digit must be something other than 0.



Ex: The following decimal integer constants are written incorrectly for the reasons stated.
12,245             illegal character (,)
36.0                       Illegal character (.)
10 20 30          Illegal character (blank space).
123-45-6789     Illegal character (-)
900                        The first digit cannot be a zero.
b) octal (base 8):
An octal integer constant can consist of any combination of digits taken from the set 0 through 7.  However the first must be 0, in order to identify the constant as an octal number.
Ex: Several valid octal integer constants are shown below.
            0          01        0743    077777
Ex: The following octal integer constants are written incorrectly for the reasons stated.
743                        Does not begin with 0.
05280              Illegal digit (8).
777.777               Illegal character(.).
c) hexadecimal (base 16):
            A hexadecimal integer constant must begin with either 0x or 0X. It can then be followed by any combination of digits taken from the sets 0 through 9 and a through f(either upper or lower case). The letters A through F represent the decimal quantities 10 through 15, respectively.
            Ex: the following are the valid hexadecimal integer constants.
                        0x        0x1      0x7FFF           0xabcd
                        The following are the hexadecimal integer constants written incorrectly for the reasons stated.
                        0x12.34                       illegal character(.).
                        0BE38                         Does not begin with 0X or 0x
                        0x.4bff                         Illegal character(.)
                        0XDEFG                     illegal character(G).
Note: The magnitude of an integer constant can range from zero to 32767.
d) Unsigned and Long Integer Constants:
            Unsigned integer constants may exceed the magnitude of ordinary integer constants by approximately a factor of 2. An unsigned integer constant can be identified by appending the letter U to the end of the constant.
            Long integer constants may exceed the magnitude of ordinary integer constants, but require more memory within the computer.  To create a long integer constant by appending the letter L to the end of the constant.
            An unsigned long integer may be specified by appending the letters UL to the end of the constant.  The letters may be written in either upper or lowercase. However the U must precede the L.
            Ex: Several unsigned and long integer constants are shown below.
Constant                                              number system
                        50000U                                               decimal(unsigned)
                        123456789L                                        decimal(long)
                        123456789UL                                     decimal(unsigned long)
                        0123456L                                            octal(long)
                        0777777U                                           octal(unsigned)
                        0X50000U                                           hexadecimal(unsigned)
                        0XFFFFFUL                                        hexadecimal(unsigned long)



2) Real constants or Floating-point constants:
            A floating-point constant is a base-10 number that contains either a decimal point or an exponent (or both).
            Ex: several valid floating-point constants are shown below.
                        0.                     1.                     0.2                   827.602
                        50000.             0.000743         12.3                 315.0066
                        2E-8                0.006e-3          1.6667E+8      .12121212e12
                  The following are not valid floating-point constants for the reasons stated.
1                              Either a decimal point or an exponent must be present.
1,000.0            Illegal character (,)
2E+10.2          The exponent must be an integer quantity
3E 10               Illegal character (blank space) in the exponent.
Ex: The quantity 3 * 10 5 can be represented in C by any of the following floating-point constants.
                        300000.           3e5                  3e+5                3E5                  3.0e+
                        .3e6                 0.3E6               30E4                30.E+4                        300e3
            Integer and floating point constants represent numbers.  They are often referred to collectively as numeric-type constants.


 The following rules apply to all numeric-type constants.
1.Commas and blank spaces connot be included within the constant.
2.The constant can be preceded by a minus(-) sign if desired. (Actually the minus sign is an operator that changes the sign of a positive constant, though it can be thought of as apart of the constant itself.)
3.The value of a constant cannot exceed specified minimum and maximum bounds.  For each type of constant, these bounds will vary form one C compiler to another.
3) Character Constants:
            A character constant is a single character, enclosed in apostrophes (i.e., single quotation marks). Character constants have integer values that are determined by the computers. Those integer values are called ASCII values. (American Standard Code for Information Interchange).
            Ex: Several character constants are shown below.
                        ‘A’                    ‘X’                    ‘3’                     ‘?’
            Ex: Several character constants and their corresponding values, as defined by the ASCII character set, are shown below.
            Constant                                  value
                ‘A’                                        65
                ‘x’                                         120
    ‘3’                                         51
    ‘?’                                         63
   ‘ ‘                                           32                  
4) String Constants:
            A string Constant consists of any number of consecutive characters (including none), enclosed in (double) quotation marks.
            Ex: several string constants are shown below.
            “green”                        “ vasavi college of Eng.”                     “270-32-3456”
            “$19.95”           “THE CORRECT ANSWER IS:”       “2*(I+3)/J”

            “           “           “ “                                                         “A”





Variable:

            A variable is a data name that may be used to store a data value.  Unlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during execution.
            A variable name can be chosen by the programmer in a meaningful way so as to reflect its function or nature in the program.           
Ex: average, height, total, counter_1,class_strength
            A variable names may consist of letters, digits, and the underscore(_) character, subject to the following conditions:
            1.Thye must begin with a letter.  Some systems permit underscore as the first character.
            2.The variable name should not be a keyword.
            3.Special characters are not allowed, except _(underscore).
            4.Uppercase and lowercase are significant.  That is, the variable Total is not the same as total or TOTAL.
            5.ANSI standard recognizes a length of 31 characters. However, the length should not be normally more than eight characters, since only the first eight characters are treated as significant by many compilers.
            Ex: The following names are valid identifiers
                        X                      y12                  sum_1             _temperature
                        Names                        area                 tax_rate           TABLE

                   The following names are not valid variables for the reasons stated.

                        4th                   the first character must be a letter     
                        “x”                    illegal characters(“)
                        order-no          illegal character(-)
                        error flag         illegal character(blank space).

Declaration of variables:
            After designing suitable variable names, we must declare them to the compiler.  Declaration does tow things:
            1.It tells the compiler what the variable name is.
            2.It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.

            Syntax:
                       
Datatype      variblename-1, varaiblename-2,…………….,variablename-n;

Variables are separated by commas.  A declaration statement must end with a semicolon.

            Ex:       1) int  count;
                        2) int  number, total;
                        3) double  ratio;

Note: The declarative statement must be the first statement for all C programs.

Assigning values to Variables:

            Variables are created for use in program statements such as

            Value=amount + inrate * amount;
           
            In the first statement, the numeric value stored in the variable ‘inrate’ is multiplied by the value stored in ‘amount’ and the product is added to ‘amount’.  The result is stored in the variable value.  This process is possible only if the variables ‘amount ‘ and ‘inrate’ have already been given values.  The variable ‘value’ is called the target variable.  While all the variables are declared for their type, the variables that are used in expressions (on the right side of equal (=) sign of a computational statement) must be assigned values before they are encountered in the program. 

            Values can be assigned to variables using the assignment operator = as follows:

Variable_name=constant;
                       
Ex:
            1) initial_vale = 0;
            2) final_value = 100;
            3) balance = 75.84;
            4) yes = ‘x’;
It is also possible to assign a value to a variable at the time the variable is decalred.  This takes the following form:
    Datatype variable-name=constant;
Ex:       1) int final_value=100;
            2) char yes = ‘x’;
            3) double balance = 75.84.

The process of giving initial values to variables is called initialization. C permits the initialization of more than one variable in one statement using multiple assignment operators.  For example the statement
                       
                        P=q=s=0;
                        X=y=z=Max;
are valid.

Keywords:

            There are certain reserved words, called keywords that have standard, predefined meaning in C. These keywords can be used only for their intended purpose; they cannot be used as programmer-defined variable names.
            The standard keywords are:
            auto                extern             szieof             
            break              float                static
            case                for                   struct
            char                goto                switch
            const              if                      typedef
            continue         int                    union
            default            long                unsigned
            do                    register           void
            double            return             volatile
            else                 short               while
            enum              signed
Note that the keywords are all lowercase. Since uppercase and lowercase characters are not equivalent.




Data types:
            The following are the four primary data types in C
            1.char
            2.int
            3.float
            4.double
1.char:        The keyword char is useful to declare character type variables.  character type variables Requires 1                       byte of memory.
2.int:            The keyword int is useful to declare integer type variables. Integer type variables requires 2 byes of memory.
3.float:         The keyword float is useful to declare real type or float type variables. Float type variables requires 4 bytes of memory.
4.double:        Double is similar to float. It is also representing the real type variables. Double type variables requires 8 bytes of memory.  Double type variables store bigger real numbers compared to float type variables.
Qualifiers:
The basic data types can be augmented by the use of the data type qualifiers
                                    a) short
b) long
c) signed
d) unsigned.


Type
Size
Range
char or signed char
8
-128 to 127
unsigned char
8
0 to 255
int or signed int
16
-32,768 to 32,767
unsigned int
16
0 to 65535
short int or signed short int
8
-128 to 127
unsigned short int
8
0 to 255
long int or signed long int
32
-2,147,483,648 to 2,147,483,647
unsigned long int
32
0 to 4,294,967,295
Float
32
3.4E-38 to 1.7E+308
Double
64
1.7E-308 to 1.7E+308
long double
80
3.4E-4932 to 1.1E+4932.


Chapter-2

Input-output functions

                                                *getchar()
                                *putchar()
                                *scanf()
                                *printf()
                                *gets()
                                *puts()
                                *Library Functions
Introduction:
            One of the most important aspects of any programming language is its ability to handle input and output.  A large portion of most programs is normally associated with getting data from the user and providing information back to the user in a meaningful fashion.  In most of the computer languages, input and output are done through statements.  But in C, these operations are carried out through its built-in functions.  All the functions which are used of I/O operations are collectively called standard I/O Library. Each program that uses I/O functions must contain the statement #include at the beginning.  Stdio.h is an abbreviation of standard input output header file.
            There are three types of I/O library function.  They are
1) getchar() and putchar() for I/0 of single character
2) gets() and puts() for I/O of string data
3) scanf() and printf() for I/O formatted, general I/O.
Single Character I/O:
Single character Input: getchar():
            The getchar() function reads a single character from the keyboard.  It takes no parameters, and it’s returned value is the input character.
            The general form of this function is
            Variable=getchar();
Example:
            char c;
            c=getchar();
            getchar() reads a character from the keyboard and assigns it to c.
Single Character Output:  putchar():
            The putchar() function displays a single character on the screen.

            The general form of putchar() is

                        putchar(variable);

Example:
            putchar(c);
            putchar(‘\n’);




Formatted Input/Output:

            C provides tow functions that gives formatted I/O: scanf() and printf()

scanf() function:

            This function reads character, strings as well as numeric values form the standard input.

            The general from of this function is

                        scanf(“format string”, argument list);

            The format string contains the format codes and determines the number of arguments that follows it.  It should be given within double quotes.  The argument list contains a slit of variables.  An ampersand (&) symbol should precede each numeric and character type variables by which the addresses of the variables are denoted.  In the case of string and array variable, the ampersand sign (&) should not be given.

            Each format code starts with the character %.  A format code consists of the % sign followed by one of the following codes, which specify the data type for conversion.

           
Code
meaning of the corresponding argument
%d
%o
%x
%u
%h
%c
%s
%f
decimal integer
Octal integer
Hexadecimal integer
unsigned integer
short ineger
character
string
floating point

            The input form the keyboard should be given in either of the following two ways.

i) Value of each argument separated from the previous one by a space.
ii) Value of each argument should be ended by pressing the EINTER KEY i.e. each argument in a separate line.
Example:
            1.scanf(“%d”, &x);
                        Here x is an integer variable

            2.scanf(“%d %f %c”, &basic, &da, &sex);
Formatted Input:
            The input statement can have format specifications.
Format for Integer input:
            The general form is %wd
            W is the width or number of digits.
Example:
            scanf(“%3d %3d %3d”,&a,&b,&c);
i)      When the input data length is lesser than the given length, the given values are unaltered and stored in variables,
Let the input data are entered as
            1          2          3
            then a=1,         b=2,     c=3

ii) When input data length is equal to the given length, the given values are unaltered and stored in variables.
                        Let the input data are entered as
                        123      456      789 then
                        a=123,             b=456,             c=789
iii) When the input data length is more than the given length, the given values are altered and stored in variables.
            Let the input for the above scanf function is
            1234     5678     9 then a=123, b=4 and c=567
Format for Floating point input:
            The general form is
            %w.d f ---------- d is the number of digits after the decimal point, w represents total width which includes the digits before, after decimal place and the decimal point.
            When the input data length is less than or equal to the given length, the given values are unaltered and stored in variables. When the input data is more than the given length, the given values are altered and stored in variables.
Example:
            scanf(“%4.1f %6.2f”, &p, &q);
            If the data items are entered as
            14.1    48.93 then p=14.1   and q=48.93
            if the data items are entered as
14.732    6748.92 then p=14.7 q=32.0
Format for string input:
            %ws-------w is the total number of characters in a string.
Example:
            scanf(“%20s”,address);
Note:   Normally the %S format reads strings till it encounters the first white space character.  Suppose we want to read a string including blank spaces then we have to use [^/n] in the format code.
            Example: scanf (“%[^/n]”, address);
The printf Function:
            The printf function is used to display values or results at the terminal.  This function can be used to output any combination of numerical values, single characters and strings.
            The general form of this function is
                        printf(“format string”, argument list);
            The format string can contain:
            *Characters that are simply printed as they are
*Conversion specification that begins with % sign
*Escape sequences that begin with a \sign.
            The argument list may contain constants, variables, expressions or even functions.
Conversion Characters:
            The following is the list of conversion characters that can be used with the pring() function.
Code
meaning
            %c
            %d
            %e
            %f
            %g
            %o
            %u
            %x
Character
Integer
Scientific notation
decimal floating point
Uses %e or %f     which ever is shorter
Octal
Unsigned decimal           
Hexa decimal



Formatted output:
Format for integer:
The general form is
            %wd
            w is the width or number of digits
            When output data length is lesser than, equal to or more than the given length, the values are displayed without alteration.
Examples:
            I=2345;
            printf(“%4d”,i);  output:2345
            printf(’%8d”,i); output: bbbb2345
            printf(“%2d”,i); output: 2345
            printf(“%d”, i); output:2345
            printf(“%-8d”,i); output: 2345bbbb
            printf(“%08d”,i); output: 00002345
Formatted for floating point output:
            The general form is
            w.df-------d is the number of digits after the decimal point; w represents total width including the decimal point.
            When output data is lesser than, equal to or more than the given length, the values are displayed without alteration before the decimal point and truncation takes place after the decimal point.
Example:
            printf(“%7.4f”, 98.7654); output:  98.7654
            printf(“%8.2f”,123.456); output:  bbb123.46
            printf(“%4.2f”,123.456); output: 123.46
            printf(“%10f”,345.678); output: bbb345.678000
                        (by default 6 digits after the decimal point)
            printf(‘%3f”,345.678); output: 345.678000
            printf(“%-7.2f”,98.7654); output:98.77bb
            printf(“%16e”,345.678); output:bbbb3.456780 e + 02
Format for String output:
            The general form is w.ks or WS
            W is the total number of characters in the string K and dot , k are optional.  If present, k number of characters with leading w-k blanks of the string is expected.
Examples:
            printf(“%5c”,’A’); output:  bbbbA
            printf(“%-5c”,’A’); output: Abbbb
            printf(“%s\n”,”Television”); output:Televsion
            printf(“%3 S\n”,”Television”);  output: Television
            printf(“%12 s\n”,”Television”); output: bbtelevison
            printf(“%-12S\n”,”Television”); output: bbbbbbTelevi
                        (Truncated to 6 characters printed in a field of 12)
            printf(“%12.6S\n”, “Television”); output: Televibbbbbb









String input and output functions:

            We have already learnt to read and write string data using the %s in scanf and printf functions. Additionally C provides tow special library functions for string input and string output.  They are gets() and puts() functions.

The gets() function:

            The gets() function is used to read a string from the keyboard until a carrigage return key is pressed.  The string can have embedded blanks also.
            The general form is
            gets(S);
            Where S is the name of the array storing the string.  It is necessary to define S as a array of characters when a character array for a string is declared it must be having space to accommodate for the null character ‘\0’.
Example:
            char name[20];
            gets(name);
Here name is a array of characters.
If we enter,
            Wings tech.
This value will be assigned to name.  A null character ‘\0’ is automatically appended to this string.
The puts() function:

            The puts() function outputs the string of characters stored in a variable on the screen.  This function replaces the null character ‘\0’ at the end of the string with the new line character \n before displaying.  Thus the cursor advances to the next line after displaying on the screen the string stored in the variable.
The general form is
                        Puts(s);
Where s is the name of the variable containing the text to be displayed.
Example:

            1.char name[30];
               gets(name);
               puts(name);
            2.puts(“\n wings techn.\n”);
Library Functions:

            C language has its own set of predefined functions called library functions.  Most of the C compilers support the following standard library facilities.

*input output functions (getchar(), putchar(), scanf(), printf(), gets(), puts(), etc)
*Mathematical operations
*Operations on characters
*Operations on strings

Mathematical Library Functions:

            Mathematical functions such as cos, sin, log, abs etc are frequently used in real life problems.  Most of Compilers supports these functions.  To use any of these functions in a program, we should include the header file: #include .




The following are the functions included in the Math.h header file.
Function
argument type
Meaning
cos(x)
sin(x)
tan(x)
exp(x)
log(x)
log10(x)
pow(x,y)
floor(x)

ceil(x)

sqrt(x)
abs(i)
fabs(x)
acos(x)
asin(x)
atan(x)
cosh(x)
sinh(x)
tanh(x)
double x
double x
double x
double x
doublex
double x
double x,y
double x

double x

double x
integer i
double x
double x
double x
double x
double x
double x
double x
cos x
sin x
tan x
ex
ln(x)-natural log
log10(x)
xy
rounds its argument down to
An integer floor(4.9)=4.0
rounds its argument up to an
Integer ceil(4.9)=5
square root of x.
|i|  - absolute value of i
|x| - absolute value of x
cos -1 (x)
sin -1 (x)
tan –1(x)
cosh (x)
sinh(x)
tanh(x)

Note: whenever angles are involved they are expressed in radians, not in degrees.
Character related library functions:
            Sometimes it may be required to analyze a character type such as alphanumeric, digit, control characters etc.  These facilities are declared in the header file ctype.h.  Hence, this header file should be included in the program if any of this routine is to be involved.  These functions return a non-zero value if the condition is true and zero if the condition evaluates to false.  Some of the functions are given in the following table.
Function
Meaning
            Isalnum
            Isalpha
            Iscntrl
            Isdigit
            Islower
            Isprint
            Ispunct
            Isspace
            Isupper
            Tolower

            Toupper
is it alphanumeric?
is it alphabetic?
is it control character?
is it a digit?
is it a lowercase letter?
is it a printing character?
is it punctuation?
is it a space?
is it an uppercase?
Used to convert a given uppercase letter
Into corresponding lowercase letter
used to convert a given lowercase letter
Into corresponding uppercase letter.







Comments:
            Anything enclosed within a pair of /* and */ is treated as a comment.  These comments are included in C programs wherever some explanation is required for that part of a program.
Examples:
            /* Program for compute sum and average */
            /* The following statement compares two values to find large*/
            *There can be any number of comments in a program
            *A comment can be split over two lines
            *A comment can occur anywhere in a program.
            *Comments cannot be nested.
Statements:
            A statement in a computer program is carryout some action. There are two types of statements used in C. They are
            1.simple statement
            2.compound statement
1.simple statement:
            A simple statement consists of any valid C expression followed by a semicolon.
                        Ex: m = 5;
                              a = b+c;
2.compound statement:
            A number of statements can be grouped together in C by enclosing them within a pair of left and right curly braces {}. Such a group is called a compound statement or a statement block.  These statements are together are equivalent to a single statement.


 Program To Read Two Numbers And Print The Sum Of Given Two Numbers.
# include
# include
main()
{
int a,b, sum;
clrscr ();
printf (“ENTER VALUE FOR A ; “);
scanf (“%d”,&a);
printf(“ENTER VALUE FOR B ;”);
scanf(“%d”,&b);
sum=a+b;
printf(“Sum Of Given Two Numbers are %d”, sum);
getch();
}
Program To Accept Student Roll No, Marks in 3 Subjects and Calculate Total, Average and Print it.
# include
# include
main()
{
int r,b,c,d, tot, avg;
clrscr();
printf (“ENTER STUDENT RNO ; “);
scanf (“%d”,&r);
printf(“ENTER FIRST SUBJECT MARKS ;”);
scanf(“%d”,&b);
printf(“ENTER SECOND SUBJECT MARKS;”);
scanf(“%d”,&c);
printf(“ENTER THIRD SUBJECT MARKS ;”);
scanf(“%d”,&d);
tot=b+c+d;
avg=tot/3;
printf(“\n\n\t\t VIDYARTHI COMPUTERS – HANAMAKONDA \n\n”);
printf(“\t STUDENT RNO ; %d “,r);
printf(“\t FIRST SUBJECT MARKS ;%d “,b);
printf(“\t SECOND SUBJECT MARKS ;%d “,C);
printf(“\t THIRD SUBJECT MARKS ;%d “,d);
printf(“\t AVERAGE MARKS ; %d”, avg);
getch();
}


 Program To Read Three Numbers And Print The Biggest Of Given Three Numbers
# include
# include
main( )
{           int a,b,c,big=0;
clrscr( );
printf(“ENTER VALUE FOR A:”);
scanf(“%d”,&a);
printf(“ENTER VALUE FOR B:”);
scanf(“%d”,&b);
print(“ENTER VALUE FOR C:”);
scanf(“%d”,&c);
if (a>big)
big=a ;
if(b>big)
big=b;
if (c>big)
big=c;
printf (“BIGGEST OF ABOVE GIVEN THREE NUMBER IS %d”,big)
getch( );  }












 Program to accept a character in the uppercase and print in lower case.
# include
# include
main( )
{ char ch,c1;
clrscr( );
prntf(“enter a cha in uppercase”);
ch=getchar();
c1=ch+32;
prntf(“the given char in lowercasecase is”);
putchar(c1);
getch();    }

 Program to accept a character in any case and print in another case.
# include
# include
main( )
{
char ch,c1;
clrscr( );
printf(“enter a char in anycase”);
ch=getchar();
if(ch>=65 && ch<=90)
c1=ch+32;
else
if(ch>=97 && ch<=122)
c1=ch-32;
printf(“the given char in anothercase IS”);
putchar(c1);
getch();
}












 


Chapter-3

Operators

1.  Arithmetic operators
2.  Relational operator
3.  Logical operators
4.  Assignment operator
5.  Increment & decrement operators
6.  Conditional operator
7.  Bitwise operators
8.  Special operators
Def:     An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables.  They usually form a part of the mathematical of logical expressions.
            C operators can be classified into a number of categories.  They include:
1)  Arithmetic operators
2)  Relational operators
3)    Logical operators
4)    Assignment operators
5)    Increment and decrement operators
6)    Conditional operators.
7)    Bitwise operators
8)    Special operators
1.Arithimetic Operators:
            There are five arithmetic operators in C. They are
Operator
Meaning
+
-
*
/
%
Addition
subtraction
Multiplication
Division
Remainder after integer division
            The % operator is sometimes referred to as the modulus operator. The remainder operator (%) requires that both operands be integers and the second operand be nonzero.  Similarly, the division operator (/) requires that the second operand be nonzero
            Division of one integer quantity by another is referred to as integer division.  This operation always results in a truncated quotient i.e. the decimal portion of the quotient will be dropped.  On the other hand, if a division operation is carried out with tow floating-point numbers, or with one floating-point number and one integer, the result will be a floating-point quotient.
Ex:  Suppose that ‘a’ and ‘b’ are integer variables whose values are 10 and 3, respectively.  Several arithmetic expressions involving these variables are shown below, together with their resulting values.
Expression
value
a+b
a-b
a*b
a/b
a%b
13
7
30
3
1
Ex: Now suppose that v1 and V2 are floating-point variables whose values are 12.5 and 2.0 respectively.  Several arithmetic expressions involving these variables are shown below, together with their resulting values.
Expression
Value
V1+v2
V1-v2
V1*v2
V1/v2
14.5
10.5
25.0
6.25
Def: Combination of some operands, constants with arithmetic operators is called an arithmetic expression.
            Ex 1) a+b*2/c+d*5
2)    x/y*x*2/y*3
The following is the hierarchy of arithmetic operators.
            1.( )                  -----   parenthesis
            2.*   /    %
            3.+    -
Ex: Determine the hierarchy of operations and evaluate the following expression:
            I=2*3/4+4/4+8-2+5/8
            I=6/4+4/4+8-2+5/8
            I=1+4/4+8-2+5/8
            I=1+1+8-2+5/8
            I=1+1+8-2+0
            I=2+8-2+0
            I=10-2+0
I=8+0
I=8
2) Relational Operators:
            We often compare tow quantities, and depending on their relation, take certain decisions.  For example, we may compare the age of two persons, or the price of two items, and so on.  These comparisons can be done with the help of relational operators. 
            The value of a relational expression is either true or false. For example 10 <20 20="" but="" false.="" o:p="" true="">
Operator
Meaning
< 
<=
> 
>=
==
!=
is less than
is less than or equal to
is greater than
is greater than or equal to
is equal to
is not equal to
            A simple relational expression contains only one relational operator and takes the following form:
                        Ae-1   relational operator  ae-2
Ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables or combination of them.
            Ex:  1. 4.5  <=   10                              true
                   2.  4.5   <   -10                              false
                   3.  a+b  ==  c+d                           true
4) Logical Operators:
            In addition to the relational operators, C has the following three logical operators.
                                    &&………logical AND
                                    ||…………logical OR
                                    !………….logical NOT
            The logical operators && and || are used when we want to test more than one condition and make decisions.
            Ex: a>b && x==10
            An expression of this kind which combines tow or more relational expression s is termed as a logical expression or a compound relational expression.  Like the simple relational expressions, a logical expression also yields a value of true or false.
                                    Truth Tables
        &&
Exp1
Exp2
Result

T

T
T
T
F
F
F
T
F
F
F
F
||
Exp1
Exp2
Result

T

T
T
T
F
T
F
T
T
F
F
F
!
Expression
Result
T
 F
F
 T
Ex:
            1.(age>55 && salary<1000 o:p="">
            2.(number<0 nbsp="" number="">100)
4) Assignment Operators:( =)
            Assignment operators are used to assign the result of an expression to variable. The most commonly used assignment operator is =. 
            Syn:    identifier = expression;
Where identifier generally represents a variable, and expression represents a constant , a variable or a more complex expression.
Ex:      1)         a=3;
2)            x=y;
3)            delta=0.001;
4)            sum=a+b;
5)            area = length * width
The right expression to the assignment operator is evaluated first, and that obtained resultant is stored into the left side variable to that assignment operator.
Compound Assignment:
            Consider the following assignment statement
            X=x+a;
            C provides a compact and short-hand form of indicating this operation by compound assignment operator ‘+=’. Thus x=x+a; can be represented by x+=a.
            The general form of compound assignment is
First-operand    compound-assignment-operator    second-operand;




            The forms of compound assignment operators and their corresponding expanded assignment statements are given below.
            Operator
example
equivalent assignment statement
            +=
x+=a
x=x+a
            -=
x-=a
x=x-a
            *=
x*=a
x=x*a
            /=
x/=a
x=x/a
            %=
x%=a
x=x%a
5) Increment and Decrement operators:
            These are very useful operators, generally not found in other programming languages, they are ++ and --.
            The ++ operator increments the value contained in a variable by one.  The general form of this operation is
        Syn:
            Variable++;   ------------------>post increment operator
            Variable--;    ------------------>pre increment operator
            Both are equivalent to
                  Variable=variable+1
            It is important to distinguish between pre-increment and post-increment operations.  The pre-increment operator, first increment and do the operation.  On the other hand in the post increment operator first do the operation and then increment.
            i.e.       a=++b; is equivalent to b=b+1
                                                            a=b;
                        a=b++; is equivalent to a=b;
                                                b=b+1;
Ex:      b=5;
            a=++b; the result will be b=6
                                                    a=6
            a=b++; the result will be a=5
                                                    b=6
In a similar way, C uses – as a decrement operator.
The format of – is
            Variable-- ; --------------- post decrement
            --variable    --------------- pre decrement
Both are equivalent to
Variable =variable – 1;
Ex:      b=5;
            a=--b;  the result will be b=4
                                       a=4
            a=b--; the result will be  a=5
               b=4
6) Conditional Operator (?:):
            This is also known as ternary operator. It is called ternary operator because it uses three expressions.  It is a short form of if-then-else statement.
            The general from is:
(expressio-to-evalueate)? Expression1 : expression2;
If the expression being evaluated is true, expression1 will be performed. If the expression is false, expression 2 will be performed.
            The following example gives the maximum of two numbers x andy.
                        Maximum =(x>y) ?  x   :   y;
            Every thing between the = and; is the conditional expression.  The meaning of the statement is if x is greater than y, then maximum = x; otherwise maximum=y.


7) Bitwise Operators:
One byte is made up of 8 bits.  A bit stores either 0 or 1. The C language provides facilities similar to assembly language to manipulate at the bit level of integers in addition to operations at the byte level.
            The operators provided for bit manipulation are:
            &          bitwise AND                            |           bitwise OR
            ^          bitwise exclusive OR              ~          bitwise one’s complement operator.
            >>        Right shift operator                 <<        Left shift operator
These can operate on integers only and not on floating point types.
            The bitwise AND operator (&) returns 1 if both the operands are 1 and 0 otherwise.
            The bitwise OR operator(|) returns 1 if at least one of the operand is 1 and 0 when both are 0.
            The bitwise XOR(^) operator returns 0 when both the operands are same and 1 when they are different.
            The bitwise one’s complement operator (~) inverts each bit.  In other words, it converts each 1 bit to 0 and each 0 bit to a 1.
            Suppose the variable a and b have the values 7 and 12 respectively.  The binary representation of these variables are
                        A                      ----00000111
                        B                      ----00001100

                        A&B                 ----00000100
                        A|B                  ----00001111
                        A^B                 ----00001011
                        ~A                   ----11111000
                        ~B                   ----11110011
8) Special Operators:
            There are special operators used in the C language to perform some particular type of operations.  The following are the special operators in C.
Operator
operation
action performed
&

*


sizeof

,


.

-à
Address

indirection




comma


dot
returns address of operand

returns contents of location
whose address is the operand

returns size in bytes of the operand
to separate elements or
expressions in alist


Member of structure or union

pointer to a member of a structure or union.
Type Casting:
            It is possible to force an expression to be o0f specific type by using a construct called cast.  The operator used to force this conversion is called cast and the process is known as casting.  The general form is
            (Type-desired)  expression;
Ex:       1.         a=1
                        c=3.1415.
                        b=(int ) c ; here b=3
                        d=(float) a/(float)b = 0.333
Ex:       2.         char ch;
                        Int x;
                        X=(int) ch;
Ex        3.         (double)(4*3/7)




 Individual Digits
# include
# include
main( )
{int a,b,c,d;
clrscr( );
printf ( “ Enter a two digit number :”);
scanf (“ %d”, &a);
b=a/10;
c=a%10;
d=b+c;
printf (“sum of individual digits of given numbers id %”, d);
getch( );}
 Program to accept a three digit number and print the sum of individual digits.
# include
# include
main( )
{int a,b,c,n, sum;
clrscr( );
printf (“ Enter a Three Digit Number:“);
scanf (“%d”,&n);
a=n/100;
b=( (n%100)/10);
c=n%10;
sum=a+b+c;
printf (“ Sum of Individual Digits of Given Numbers is %d”, Sum);
getch( );}
9. Program to accept a number and check the given number is Armstrong or not.
# include
# include
main( )
{int n, a, b, c, d;
clrscr( );
printf (“ Enter a Three Digit Number: “);
scanf (“%d”, &n);
a=n/100;
b=((n/10)%10);
c=n%10;
d=a*a*a*+b*b*b +c*c*c;
if (n= =d)
printf (“The Given Number is Armstrong number”);
else
printf (“The Given Number is Not Armstrong number”);
getch( );}
21. Program to find biggest of two no by using ternary numbers
# include
# include
main( )
{      int a,b,big;
clrscr( );
printf(“enter value a”);
scanf(“%d”,&a);
printf(“enter the value of b”);
scanf(“%d”,&b);
big=(a>b)?a:b;
printf(“biggest of the given numbers IS %d”,big);
getch();    }
 Program to find biggest of four no by using ternary numbers
# include
# include
main( )
{     int a,b,c,d,big;
clrscr( );
printf(“enter value a”);
scanf(“%d”,&a);
printf(“enter the value of b”);
scanf(“%d”,&b);
printf(“enter the value of c”);
scanf(“%d”,&c);
printf(“enter the value of d”);
scanf(“%d”,&d);
big=(a>b)?(a>c)?(a>d)?a:d:(c>d)?c:d:(b>c)?(b>d)?b:d:(c>d)?c:d;
printf(“biggest of the given 4 numbers IS %d”,big);
getch();    }
 Program to print smallest of four no by using ternary operators
# include
# include
main( )
{  int a,b,c,d,small;
clrscr( );
printf(“enter value a”);
scanf(“%d”,&a);
printf(“enter the value of b”);
scanf(“%d”,&b);
printf(“enter the value of c”);
scanf(“%d”,&c);
printf(“enter the value of d”);
scanf(“%d”,&d);
small=(a
printf(“smallestof the given 4 numbers IS %d”,small);
getch();
     }





Chapter-4

Control Structures

µConditional Control Structures
              *if
              *if-else
              *nested if-else

µMultiple Branching Control Structure
              *switch-case

µLoop Control Structures
              *while
              *do-while
              *for

µJump Control structures
              *break
              *continue
              *goto
              *exit















Introduction:

            Usually Computer executes the instructions or statements of a program one by one in a sequential manner.  There are many situations in which this sequential execution need to be altered with a few instructions being executed only when a condition is satisfied.  There may also be occasions when it may be necessary to execute a group of instructions repeatedly for a fixed number of times or until some condition is satisfied.  Under such situations programmer may require to include control statements in his program.  These control statements allow him to alter the sequential order of execution.

            The control constructs in C can be classified under the following four groups.

1.Conditional control structures
            Here the condition is tested for whether the result is true or false and the action is taken according to these tow results.  There are three structures available under this group.
            a) if
            b) if-else
            c) nested if-else

2.Multiple branching control structure
            In this case a selection is made from several alternatives available, and a group of instructions pertaining to the selected alternative only executed.  There is only one type under this group using tow keywords.
a)    switch-case

3.Loop Control structures
            This is for repeated execution of group of instructions till a condition evaluates to a true.  There are three types available under this group.
            a) while
            b) do-while
c)    for

4.Jump Control structures
            These statements cause the control to pass to any desired location in the program.  They are:
            a) break
            b) continue
            c) goto
            d) exit

1.Conditional Control structures:

a) if:
            syn:
                        if(condition)
                        {
                                    Statements;
                        }

            The condition must be placed within parentheses and the statement end with a semicolon.  The construct is executed in two steps.  First, the condition is evaluated.  In the second step, a statement or a group of statements are executed if the evaluation is true.

            If the condition evaluates false the statement or the entire block of statement within the braces is skipped without execution.

Ex:1     if(qty>=1000)
                        {
                                    dis=10;
                        }
                       
            Ex:2     if(sal>=3000)
                        {
                                    da=10;
                                    hra=20;
                                    pf=5;
                        }
                                   

b) if-else:
            syn:
                        if(condition)
                        {
                                    Statements;
                        }
                        else
                        {
                                    Statements;
                        }

            First the condition is evaluated. If it is true, then the statements with in if block are executed. If it is false, then the statements with in else block are executed. The if block is called True block and the else block is called false block.

Ex:1)   if(num%2 == 0)
                        {
                                    printf(“the number is even”);
                        }
                        else
                        {
                                    printf(“the number is odd”);
                        }

Ex:2)   if(cmarks>=35)
            {
                                    printf(“u r result is pass”);
            }
            else
            {
                                    printf(“u r result is fial”);
            }


c) Nested If-Else:

            When a serried of decisions are involved, we may have to use more than one if…else statement in nested form.

            Syn:1   if(condition)
                        {
                                    if(condition)
                                    {
                                                Statements;
                                    }
                                    else
                                    {
                                                Statements;
                                    }
                        }
                        else
                        {
                                    if(condition)
                                    {
                                                Statements;
                                    }
                                    else
                                    {
                                                Statements;
                                    }
                        }

Syn:2   if(condition)
                        {
                                    if(condition)
                                    {
                                                Statements;
                                    }
                                    else
                                    {
                                                if(condition)
                                                {
                                                            Statements;
                                                }
                                                else
                                                {
                                                            Statements;
                                                }
                                    }
            }          
5. Program To Read A Number And Find Whether The Given Number Is Even Or Odd.
# include
# include
main()
{  int n,r;
clrscr();
printf(“ENTER A NUMBER ;”);
scanf(“%d”, &n);
r=n%2;
if(r= = 0)
printf(“the above given number is even number”);
else
printf(“the above given number is odd number”);
getch();
}
6. Program to accept a year and check whether the given year IS leap year or not.
# include
# include
main( )
{     int y;
clrscr( );
printf(“enter a year:”);
scanf(“%d”,&y);
if(y%4==0& &y%100!=0|| y%400==0);
printf(“the above given year IS a leap year”);
else
printf(“the above given year IS not a leap year”);
getch();    }
2) Multiple Branching Control Structure:
a) Switch-case:
            Syn:
                        switch(expression)
                        {
                                    case value1:
                                                Statements;
                                    case value2:
                                                Statements;
                                    case value3:
                                                Statements;
                                            
                                                .
                                                .
                                                .
                                                .
                                    default:
                                                Statements;
                        }
            The if is the single-selection structure and the if-else double-selection structure.
            Switch is a multiple-selection structure to handle decision-making. The switch structure consists of a series of case labels, and an optional default case. 
            The switch-case statement tests the value of a given variable against a list of case values and when a match is found, a block of statements associated with that  case is executed. 
            The expression is an integer expression or characters.  Value1,value2,…..are constants or constant expressions and are known as case labels.  Each of these values should be unique within a switch statement.  Block1,block2,…….are statements lists and may contain zero or more statements.  There is no need to put braces around these blocks.  Note that case labels end with a colon (:).
            When the switch is executed, the value of the expression is successively compared against the values value1, value2,……. If a case is found whose value matches with the value of the expression, then the block of statements that follows the case are executed.
            The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transferring the control to the statement-x following the switch.
            The default is an optional case. When present, it will be executed if the value of the expression does not match with any of the case values.  If not present, no action takes place if all matches fail and the control goes to the statements after the switch-case statement.
3) Loop control structures:
            The loop control structures are useful to execute a statement or a set of statements for a particular number of times.
            The following are the loop Control structures:

            1) while
            2) do-while
            3) for

a) while:
            syn:
                                   
            while(condition)
            {
                        Statements;
            }
-
The condition is first evaluated and if the condition is true, then the body of the loop is executed.  After execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again.  This process of repeated execution of the body continues until the test-condition finally becomes false and the control is transferred out of the loop.  On exit, the program continues with the statement immediately after the body of the loop.

The body of the loop may have one or more statements.  The braces are needed only if the body contains tow or more statements.  However, it it’s a good practice to use braces even if the body has only one statement.

            Ex:       while(I<=10)
                        {
                                    printf(“%d”,I);
                        }

b) do-while:

            syn:
                                                           
                        do
                        {
                                    Statements;
                        }
                        while(condition);

           
            In do-while first the control directly enters into the loop and execute the statements once, after that it checks the condition. If it is true the statements are executed once again. So, that the statements are executed repeatedly until the condition becomes false.
            Ex: 1) do
                        {
                                    printf(“%d”,I);
                        }
                        while(I<=10);


Differences Between While and do-while:
            In while loop, if the condition becomes false at first checking the statements are not executed at least once.
            In do-while, the statements are executed at least once, what ever may be the condition, because in do-while, the control directly enters into the loop and execute the statements once, after that it checks the condition.


27. Program to natural number from 1 to 10 by using while loop.
# include
# include
main( )
{     int a=0;
clrscr();
while( a<10 o:p="">
{     a=a+1;
printf(“%d\n”,a);
} getch(); }
28. Program to accept a string and print it by using the while loop.
# include
# include
main( )
{    char ch;
clrscr();
printf(“enter a string”);
while(( ch=getchar( ))!=’\n’)
putchar(ch);
getch();    }
29. Program to accept a string in upper case and print it by lower case.
# include
# include
main( )
{    char ch,c;
clrscr();
printf(“enter a string in upper case:”);
while(( ch=getchar( ))!=’\n’)
{
c=ch+32;
putchar(c);
}
printf(“ is in lower case”);
getch( );
}
30. Program to accept a string in any case and print it by another case .
# include
# include
main( )
{
char ch;
clrscr( );
printf(“enter a string :”);
while(( ch=getchar( ))!=’\n’)
{
if(ch>=’A’ && ch<=’Z’)
putchar(ch+32);
else
if(ch>=’a’ && ch<=’z’)
putchar(ch-32);
else
putchar(ch);
}
printf(“ is the string”);
getch( );
}
31. Program to accept a string print each word in new line.
# include
# include
main( )
{
char ch;
clrscr( );
printf(“enter a string :”);
while(( ch=getchar( ))!=’\n’)
{
putchar(ch);
if(ch= =’ ‘)
printf(“\n”);
}
getch( );
}



c) for loop:

            Syn:
                        for(expression1;expression2;expression3)
                        {
                                    Statements;
                        }
Here expression1 is called initialization expression, expression 2 is called conditional statements, and expression3 is called incrementation or decrementation statement.
1) The first component of the for, initialization expression is used ot set initial value before the loop begins.
2) The second component, the loop condition that determines the condition that must be satisfied for the looping to continue.  It is evaluated before each iteration.  Looping continues as long as this condition is satisfied. When the loop condition is evaluated as false, execution of the loop is terminated and execution continues with a statement following the for loop.
3) The third component, increment defines how the init expression will change each time to the loop is repeated. 

Ex:1)   For(I=1;I<=10;I++)
            {
                        printf(“%d”,I);
            }
Ex:2) for(count=0;count<=5;count++)
         {
                cum_value=cum_value+count;
                printf(“%d %d”, count,cum_value);
            }

Ex:3) for(n=1;n<=10;n++)
            {
                        sqr=n*n;
                        cube=n*sqr;
                        printf(“%d %d %d”,n,sqr,cube);
            }



Remarks:
            1.The body of the loop in for statement need not contain any statement at all.  In that case, it becomes a do nothing loop or time delay loop.
            Ex: for(I=1;I<=2000;I++);
            This loop executes 2000 times, without doing anything.

            2.The condition check can be a compound expression made up of various relational expression connected by logical AND , OR operators.  Also the loop testing need not be limited only to the loop control variable.
            Ex: for(I=1;I<20 amp="" i="" o:p="" sum="">
                        {
                                    sum=sum+I;
                                    printf(“%d %d\n”,I,sum);
                        }

            3.In the for construct, the presence of two semicolon within the parenthesis is compulsory.  But nay or all the three parts, my be blank.  The initialization can be done outside the loop.  The incrementing step can be incorporated within the loop.

            Ex:       init I=0;
                        for( ;I<=4;   )
                           printf(“%d”,I++);
            4.If the test condition is omitted, the for statement sets up an infinite loop.  Such loop can broken using break statement.
            Ex:       init I=1;
                        for( ;  ;  )
                        {
                                    if(I>10)
 break;
                                    else
                                                printf(“%d”,I++);
                        }
            5.the for statement will never be executed if the test condition fails at the beginning itself.
            Ex: for(x=10;x<10 x="x-1)<o:p">
                                    printf(“%d”,n);                                                                                               


10. Program to print ODD numbers from 1 to 10
# include
# include
main( )
{
int i;
clrscr( );
for (i=1; i<=10; i+=2)
printf(“%d\n”,i);
getch( );
   11. Program to print natural numbers from 1 to 10 in Reverse
# include
# include
main( )
{
int i;
clrscr( );
for (i=10; i>=1; i--)
printf(“%d\n”,i);
getch( );
}
12. Program to print sum of the natural numbers from 1 to 10.
# include
# include
main( )
{
int n,sum=0,i;
clrscr( );
for (i=1; i<=10; i++)
sum=sum+i;
printf(“sum of natural numbers from 1 to 10 is %d\n”,sum);
getch( );
}
13. Program to accept a number and print mathematical table of the given no.
# include
# include
main( )
{  int i,t;
clrscr( );
printf(“which table u want:”);
scanf(“%d”,&t);
for (i=1; i<=10; i++)
printf(“\n%d*%d=%d”,t,i,i*t);
getch( );        }
14. Program to print 1 to 10 mathematical tables .
# include
# include
main( )
{
int i,j;
clrscr( );
for (i=1; i<=10; i++)
for(j=1;j<=10;j++)
printf(“\n%d*%d=%d”,i,j,i*j);
getch( );             }
15. Program to print fibonacci series .
# include
# include
main( )
{
int a=0,b=1,c=0,i;
clrscr( );
printf(“%d”,a);
printf(“\n%d”,b);
for (i=1; i<=10; i++)
{
c=a+b;
printf(“\n%d”,c);
a=b;
b=c;
}getch( );
}
16. Program to print numeric pyramid
# include
# include
main()
{int i,j;
clrscr( );
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf(“%d”,j);
printf(“\n”);
}
getch();
}
17. Program to print numerical pyramid.
# include
# include
main( )
{       int i,j ,l,k=40;
clrscr( );
for(i=1;i<=9;i+=2)
{   for(l=1;l<=k;l++)
printf(“ “ );
for(j=1;j<=i;j++);
printf(“%d”,j);
printf(“\n”);
k=k-2;
}getch( );}



18. Program to print numerical diamond.
# include
# include
main( )
{  int i,j,l,n,s,k=40;
clrscr( );
for(i=1;i<=9;i+=2)
{ for(l=1;l<=k;l++)
printf(“ “);
for(j=1;j<=i;j++)
printf(“\n”);
k=k-2;
}k=k+4;
for(n=7;n>=1;n-=2)
{   for(i=1;i<=k;i++)
printf(“ “);
for(s=1;s
printf(“%d”,s);
printf(“\n”);
k=k+2;
}
getch( )
;    }
19. Program to print character pyramid.
# include
# include
main( )
{
char i,j;
clrscr();
for(i=65;i<=70;i++)
{    for(j=65;j<=i;j++)
printf(“%c”,j);
printf(“\n”);
}getch( );
}












20. Program to print character diamond.
# include
# include
main( )
{
char i,j,n,r;
int s,sp=40;
clrscr( );
for(i=65;i<=75;i+=2)
{    for(s=1;s<=sp;s++)
printf(“ “);
for(j=65;j
printf(“%c”,j);
printf(“\n”);
sp=sp-2;
}  sp=sp+4;
for(n=73;n>=65;n-=2)
{      for(s=1;s<=sp;s++)
printf(“ “);
for(r=65;r<=n;r++)
printf(“%c”,r);
sp=sp+2;
}
getch( );
}


Comma Operator:

            More than one variable can be initialized / incremented a time in the for statement using comma operator.  That is, we may have more than one expression in place of the first and third expressions of the for loop.
t
Ex:       for(I=0,j=9;I<9 j--="" o:p="">
            {
                        printf(“%d%d”,I,j)
            }

            Here both I and j are initialized and modified here.

Nested loops:
            The above three loop structures can be nested with one another.

Ex:       for(I=1;I<=20;I++)
            {
                        for(j=1;j<=10;j++)
                        {
                                    printf(“%d %d”,I,j);
                        }
            }
4) Jump Constructs:
a) break:
            The break statement causes an immediate exit from the do, for, switch or while statement in which it appears.  The program continues executing with the next program statement following the do, for, switch or while statement block.
            The general form is,
                        break;
Break Statement in nested loops:
            If the break statement occurs in a nested loop, the exit is only from the innermost do, for, while or switch statement which includes the break.  The program continues executing with the next program statement following the do, for, switch or while statement.

Ex: 1) for(count=0;count<20 count="" o:p="">
            {                       if(count==10)
                        {
                                    break;
                        }           }

Ex: 2) for(I=1;I<=10;I++)
            {
                        for(j=1;j<=5;j++)
                        {
                                    if(j>=3)
                                    {
                                                break;
                                    }
                                    printf(“%d %d”,I,j);
                        }
            }


b) The continue Statement:
            The continue statement is used with the loop statements do, for, and while.  It transfers program control to the place in the program where the next iteration of the loop begins.

            Unlike the break statement, the continue statement does not exit the loop entirely, but courses only the particular iteration to be skipped.  The next iteration of the loop is continued.

            Execution of the continue statement in a do while loop causes the execution to resume with the test part of the loop statement.  Execution of the continue statement in a for loop causes execution to resume with the increment part of the for statement.
Ex:  for(I=0;I<10 o:p="">
            {
                        scanf(“%d”,&num);
                        if(num<0 o:p="">
                            continue;
                        else
                            sum=sum+num;
            }
c) The goto Statement:
            This is an unconditional branching statement and its use is discouraged in structured programming.  But C does allow use of goto statement.  In a language that provides the various loop statements like for, while and do while as well as the switch statement, there is normally no need to use the goto statement.  A complicated situation can be managed with break and continue statements.  If we want to come out of several nested loops at one stroke, the use of goto statement may be useful.
            The general form of got statement is
                        goto label;
            Here label is an identifier which identifies the statement to which is to be passed.  Control can be passed to any part of the current function in which the got appears.
d) exit() function:
            exit () is a function in standard C library; calling this function from anywhere in a program causes termination of entire program and return to the operating system.






            34. Program to print prime numbers between 1 to 100
# include
# include
main( )
{
int n, i, check;
clrscr();
for(i=1;i<=100;i++)
{
check=1;
for(n=2;n<=i/2;n++)
if(i%n= =0)
{
check=0;
break;
}
if(check= =1)
printf(“\n %d is a prime”,i);
else
printf(“\n %d is not a prime”,i);
}
getch( );
}

























Chapter-5
Arrays
               *One dimensional arrays
*Multi dimensional arrays

Introduction:

            An array is a list of elements or data of the same type. All the elements together are referred to by single name. This is the name of the array. The elements of the array are differentiated from one another by their positions within the array. The position of these elements can be indicated by means of a subscript or index.

            C supports single and multi – dimensional arrays. Single dimensional arrays are represented as vectors containing several rows of values. Multi dimensional arrays can be viewed as tables containing several rows and columns of data.

One – dimensional arrays:

            A one-dimensional array is a list of values of the same data type. A one-dimensional array contains only one subscripts. A typical pictorial representation of an array is given below
mark
48
56
85
18
45
93
0                      1                      2                      3                        4                       5
This illustrates integers stored in consecutive cells of an array named mark, where the contents of each cell are accessible through the name of the array and the subscript or index of the cell. Note that in C the subscript of the first cell is zero. Thus the contents of mark [0] are 48,mark [1] is 56,mark [2] is 85 etc.

Declaration:

            Like any other variable, arrays must be declared before they are used. The general form of the dimensional array declaration is
            Data-type variable-name [size];
            The type can be int, char, float, double or any other data types available in C. The only condition is that all the elements of an array must be of the same type.
            The size of an array represents the total number of elements in the array. The name of the array can be user – defined similar to any other variable.
For example, the declaration for the above array is
int mark[6];

Examples:

            int age [10]; declares age as an array to contain maximum 10 integers.

            float height [20]; declarers age as an array containing the maximum of 20 float numbers.

            Char name[20]; declares the name as a character array containing the maximum of 20 characters.
Initialization of arrays:
            We can initialize the elements of arrays in the same way as the ordinary variables when they are declared.
The general form is,
Type array-name [size]={value list};
The value list is a comma-separated list of constants.
Examples:
            int values[6]={1,2,3,4,5,6};
float a[5]={1.1,2.2,3.3,4.4,5.5};
char name[6]={‘v’,’s’,’v’,’a’,’v’,’i’};

Note:

1.If the initialization values are fewer than cells in the array then the remaining cells are initialized to zero.

Example:

            Float sum [5]={6.5,7.3,2.5};
Here the last two elements will set to zero automatically.

2. The declaration of the maximum number of cells in the array can be omitted if the initialization values are present.
Int mark[]={45,56,78,89};

Processing with arrays:

            An easy way to read values to an array is by using a for loop.         

Example:

            The contents of the array can be accessed and printed as follows
            for (i=0;i<6 d="" i="" mark="" o:p="" scanf="">
            The contents of the the array can be accessed and printed as follows
            for(i=0;i<6 d="" i="" mark="" n="" o:p="" printf="">

Note:

            C does not require that the range of the subscript is checked. If the index was allowed to go out of range then the result will be unpredictable when the program is executed.
Multidimensional arrays:
Two-dimensional arrays:
            Multi dimensional   arrays are repetitive structures. For example a two-dimensional array is a repetition of one-dimensional arrays. (i.e.) A two dimensional array is composed from one-dimensional arrays.

Example:        matrix

                                    0              1                 2                      
0
28
32
51
1
12
89
10
2
54
15
19


            In the example given above.  Matrix is the name of the two dimensional array. It contains 3 rows and 3 columns. Since multidimensional arrays are stored in memory as one-dimensional arrays the above matrix is stored in memory as
matrix [0][0]
matrix [0][1]
:
:
:
matrix[2][2]

Declaration:

            Two-dimensional arrays are declared as follows:
Type array-name[row-size][col-size];
Note that C requires that each subscript can be written within its own separate pair of brackets.

Example:

            1.int value[10][10]; declares value as an integer array having 10 rows and 10 columns.
Initialization:

            Contents of the two-dimensional array can be initialized in a similar way to one-dimensional array.

            The elements are to be initialized one by one.

            a [3][2]={1,2,3,4,5,6};

            Alternatively, elements of each row can be enclosed within pair of braces with each row separated from the next by a comma, as follows

a[3][2]={{1,2},{3,4},{5,5}};

            If a row of initialization values does not contain enough values then the remaining elements are set to zero. Thus the following two assignments are equivalent:

a [3][2]= {{1,2},{3},{4}};

            Similarly if there are not enough rows of initialization values then the remaining rows in the array  are set to zero.

            When all the elements are to be initialized to zero the following method may be used

            int m[3][5]={{0},{0},{0}};
Here the first element of each row is explicitly initialized to zero. while  other elements are automatically initialized to zero.

Processing with 2 dimensional arrays:

Nested loops are useful when dealing with 2 dimensional arrays. Elements of a two-dimensional array can be read, accessed and printed using a nested loop, as follows.

Reading a 2 dimensional array:

for(row=0;row<3 o:p="" row="">
{
    for(col=0;col<3 col="" o:p="">
            scanf (“%d”,&matrix[row][col] );        
}
Printing a two dimensional array in matrix form:
for(row=0;row<3 o:p="" row="">
{
    for(col=0;col<3 col="" o:p="">
            printf(“%d”,matrix [row][col] );
            printf(“\n”);
}

Three – dimensional arrays:

            The following definition pertains to a three-dimensional array P.

            Int p[3][4][2];

            This can be logically thought of as comprising three two dimensional arrays, each of size 4*2. This is equivalent to the three tables each containing four rows and two columns. Thus there are 3*4*2=24 elements. This three dimensional array is stored in memory as

P[0][0][0]
P [0][0][1]
P [0][1][0]
P [0][1][1]
P [0][2][0]
P [0][2][1]
:
:
:
:
P [2][3][1]


42.Program to accept values into 3 dimensional array and print .
# include
# include
main( )
{
int a[3][3],i,j;
clrscr( );
for(i=0;i<=2;i++)
for(j=0;j<=2;j++)
{
printf(“ enter the value for a[%d][%d] :”,i,j);
scanf(“%d”,&a[i][j]);
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
printf(“ %d:”,a[i][j]);
printf(‘\n”);
}
getch( );
}



43. Program to print upper triangle .
# include
# include
main( )
{
int a[4][4],i,j,c;
clrscr( );
printf(“ enter which no u want”);
scanf(“%d”,&c);
for(i=0;i<4 i="" o:p="">
for(j=0;j<4 j="" o:p="">
if(i
a[i][j]=c;
else
a[i][j]=0;
for(i=0;i<4 i="" o:p="">
for(j=0;j<4 j="" o:p="">
{
printf(“ %d:”,a[i][j]);
printf(‘\n”);
}
getch( );
}

44. Program to accept two 3 dimensional array and store addition of those into arrays into the third array .
# include
# include
main( )
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr( );
for(i=0;i<3 i="" o:p="">
for(j=0;j<3 j="" o:p="">
{
printf(“enter the two values for a[%d][%d] & b[%d][%d]”, i,j,i,j);
scanf(“%d%d”,&a[i][j],&b[i][j]);
}
for(i=0;i<3 i="" o:p="">
{    for(j=0;j<3 j="" o:p="">
{ c[i][j]=a[i][j]+b[i][j];
printf(“%d”,c[i][j]);
}
printf(“\n”);
} getch( );  }
45. Program to accept a string and find the length of the given string by using functions
# include
# include
int getline(char str[]);
main( )
{
char str[80];
int length;
clrscr( );
printf(“ enter a string”);
length=getline(str);
printf(“length of the given string is %d”,length);
getch ( );
}
int getline(char str[])
{
int i;
for(i=0;i<80 amp="" getchar="" i="" n="" o:p="" str="">
if(str[i]= =’\n’)
str[i]=’\0’;
return i;
}
46. Program to count the number of words, characters, alphabets, vowels, consonants and digit in a line of text.
#include
#include
main( )
{                                                                                       
int noa=0,nob=0,noc=0,nov=0,now=0,noch=0,l,I;
char ch,s[100];
clrscr( );
printf(“enter 2 lines of text”);
gets(s);
l=strlen(s);
for(i=0;i<1 i="" o:p="">
{  switch(s[i])
{     case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ‘u’:
case ‘A’:
case ‘E’:
case ‘I’:
case ‘O’:
case ‘U’:
nov++;
break;
}
if(isalpha(s[i]))
noa++;
if(isdigit(s[i]))
nod++;
if(noa[i]==’ ‘) && (noa[i+1]!=’ ‘)
now++;
}
noch=l-nob;
noc=noa-nov;
printf(total no of words %d”,now);
printf(total no of characters(without blanks)%d”,noch);
printf(total no of characters(including blanks)%d”,l);
printf(total no of alphabets %d”,noa);
printf(total no of vowels                      %d”,nov);
printf(total no of characters %d”,noc);
printf(total no of digits %d”,nod);
getch( );
}


Chapter-6

String Handling
                        *String Declaration
*Reading
*Writing
*String Handling Functions

Introduction:

A string is an array of characters. Any group of characters defined between double quotation marks is a string constant.
Example:       
“Welcome to wings techn”

declaring and initializing string variables:


A string variable is any valid C variable name and is always declared as an array. The general form of declaration of a string variable is

Syntax:
            char string-name [size];

The size determines the number of characters in the string-name.

Example:
            char city[10];
char name[20];

            Character array may be initialized when they are declared.

            For example, the forms of initialization are:
           
            char name[6]={‘c’,’o’,’l’,’o’,’r’,’\0’};

            The null character will be added automatically provided the enough space should be there to accommodate this character.

            C also permits to declare a character array without specifying the number of elements.  For example, the declaration statement,

            Char name[]={‘c’,’o’,’l’,’o’,’r’,’\0’}

            Is array of string with six elements.

 

Reading strings from terminal:


Reading words:

The familiar input function scanf can be used with %s format specification to read in a string of characters.

Example:
            char address[15];
            scanf(“%s”, address);

Note that unlike previous scanf() calls, in the cased of character arrays, the ampersand (&) is not required before the variable name. The name of the character array itself indicates the address. The scanf function automatically terminates the string that is read with a null character and therefore the character array should be large enough to hold the input string plus the null character.

Reading a line of Text:

In many text-processing applications, we need to read in an entire line of text from the terminal. It is not possible to use scanf function to read a line containing more than one word. This is because the scanf terminates reading as soon as a space is encountered in input.

To overcome above disadvantage C provides a string input function called gets( ) which will not treat single or multiple blank spaces as end of the string till we are going to give new-line character (\n).

Example:
            char name[20];
            gets (name);

The equivalent output function for gets( ) is puts() , which is used to to display the strings on to the output screen.

Example:
            puts(name);

writing strings to screen:


We have to use printf function with %s format to print strings to the screen. The format %s can be used to display an array of characters that is terminated by the null character (‘\0’).

Example

            printf(“%s”,name);

string – handling functions:

C library supports a large number of string – handling functions that can be used to carry out many of the string manipulations. Following are the most commonly used string – handling functions

Function

Action

strlen()
Finds the length of the string
strrev()
Reverse the given string
strcpy()
Copies one string over another
strcmp()
Compares the two strings
Strcat()
Concatenates two strings
a)strlen() :
This function counts and returns the number of characters in a string.
n=strlen(string);
Where ‘n’ is an integer variable, which receives the value of the length of the string. The argument may be a string constant. The counting ends at the first null character.

b)strrev():

This function is used to reverse the given string. Reversed string will be placed at the same location.
 strrev(name):
now variable ‘name’ is consisting of  reverse of the original string.

c)strcpy():

The strcpy function works almost like a string-assignment operator. It takes the form
                                    strcpy(string1, string2);
The above function assigns the contents of string2 to string1.string2 may be a character array variable or a string constant. for example
                                    strcpy(city, “Delhi”);
will assign the string “Delhi” to the string variable city. Similarly the statement
strcpy(city1,city2);
will assign the contents of the string variable city2 to the string variable city1. The size of the array city1 should be large enough to receive the contents of city2.
d)strcmp() :
The strcmp function compares two strings identified by the arguments and has a value 0 if they are equal. If they are not, it has the numeric difference between the first non matching characters in the strings. It takes the form
                        strcmp(string1, string2);
string1, string2 may be string variables or string constants. examples are
                                    strcmp(name1.name2);
                                    strcmp(name1,”john”);
                                    strcmp(“their”,” there”);
will return a value of –9 which is the numeric difference between ASCII “i” and ASCII “r”. That is, “i” minus “r” in ASCII code is –9. If the value is negative, string1 is alphabetically above the string2.
e)strcat():
The strcat function joins two strings together. It takes the following from
                                    strcat(string1, string2);
string1,string2 are character arrays. When the function strcat is executed, string2 is appended to string1. It does so by removing the null character at the end of string1 and placing string2 from there. The string2 remains unchanged.

Example:

                        string1=”hello”
                        string2=”welcome”

on execution of the statement

                                                strcat(string1,string2);
will result string1 is “hellowelcome”. That is the string2 is added at the end of string1.so string1 is containing the combined string. C permits the nesting of strcat functions. for
example:
                                                strcat(strcat(string1,string2),string3);
is allowed and concatenates all the three strings together. The result string is stored in string1.

Multidimensional character arrys:

Two dimensional charater arrays:

We often use lists of character strings, such as a list of names of students in a class, list of names of employees in an organization, list of places etc. A list of names can be treated as a table of strings and a two-dimensional character array can be used to store the entire list.

Declaration:

Syntax:
            char string-name[size][size];

Example:

                                    char student[30][15];
is used to store a list of 30 names, each of length not more than 15 characters.

Initialization:

Example:

                                                char city[][]={“hyd”,”delhi”,”Bombay”,”madras”};

to access the name of the ith city in the list, we write
                                                city[i-1]

note that a two-dimensional array is used to store the list of strings. Each string is read using a scanf function with %s format. Remember, if any string containing a white space, then the part of the string after the white space will be treated as another item in the list by the scanf. In such cases, we should read the entire line as a string using a suitable algorithm.

Reading a two – dimensional character array:

Two dimensional character array can be read as follows by using for loop
Example:
            for(i=0;i
                        scanf(“%s”,name[i]);
Writing a two – dimensional character array:
Two dimensional character array can be displayed as follows by using for loop
Example:
for(i=0;i
printf(“%s”,name[i]);




 Program to accept a string and count no of capital letters, no. of small letters and no. of special characters
# include
# include
main( )
{
char ch;
int c=0,s=0,s1=0;
clrscr( );
printf(“enter a string :”);
while(( ch=getchar( ))!=’\n’)
{
if(ch>=’A’&& ch>=’Z’)
c=c+1;
else
if(ch>=’a’&& ch>=’z’)
s=s+1;
else
s1=s1+1;    }
printf(“ no of capital letters are %d”,c);
printf(“ no of smal1 letters are %d”,s);
printf(“ no of special characters are %d”,s1);
getch( );
}














33. Program to accept any single digit number and print it in words .
# include
# include
main( )
{
int n;
clrscr( );
printf(“enter a number :”);
scanf(“%d “,&n);
switch(n)
{
case 0: printf(“ZERO”);
break;
case 1: printf(“ONE”);
break;
case 2: printf(“TWO”);
break;
case 3: printf(“THREE”);
break;
case 4: printf(“FOUR”);
break;
case 5: printf(“FIVE”);
break;
case 6: printf(“SIX”);
break;
case 7: printf(“SEVEN”);
break;
case 8: printf(“EIGHT”);
break;
case 9: printf(“NINE”);
break;
default:
printf(“please enter the number between 0 and 9”);
}
getch( );
}










Chapter-7
User Defined Functions
·       Advantages of using functions

·        Defining a function

·       Return statement
·       Calling a function
·        Types of functions
·       Local and global variables
·       Nesting of functions
·       Recursion
·       Functions and arrays
Introduction:

            Function is a subprogram, which performs well-defined task. A subprogram defined in C is a function, which perform specific task and return results. For example, printf and scanf routines are examples of functions. Similarly sqrt (x), sin (x), cos (x) etc. are all functions supplied by the C compiler known as built in library functions.
            In addition to standard library functions supplied by the system, C permits the programmer to write his own function for a specific work to accomplish. For example, to compute xmay wish to write our own function. Such of the functions written by the user are called user – defined functions.
            Every C program can be thought of as a collection of functions. There must be at least one function called main() where program execution starts. Any function can call any other function as well call itself back.
Advantages of using functions:

            By writing a large C program as a group of functions representing disjoint activity and a main function, gives a modular approach to the program. There by one can locate a distinct process associated with a particular user defined function in the main program. In addition,

  1. Program debugging is easier, if C program contains functions.
  2. Functions allow a larger task to be subdivided into several smaller tasks.
  3. Once a function is closed and debugged, it can be generalized, tested thoroughly and can be placed into a library so that it can be used again and again by many programs.
  4. Functions also allow multiple programmers working on a large project to concentrate on portions of a program separately.
  5. Writing functions avoids rewriting the same code again and again.

Defining a function:

            A function definition consists of three parts
a.    Function header
b.    Declaration list
c.    Function body

The general form of function definition is
Syntax:
Type specifier function – name (argument list)
Argument declarations;
{
     Local declarations;
     Body of the function;
     --------------
     --------------
 return(expression);
}
1) Function header:
            The function header contains a type, the function name and an argument list. The type specifier is the type of the data that the function is expected to return. In the absence of any data type, the type integer is assumed.

            The type specifier is followed by a function – name. The arguments of the function, if any, are given within parentheses after this. If the function takes no arguments, the parentheses still must be included. The function header is not terminated by a semicolon.

2) Declaration list:

            The function header is followed by a declaration list, which declares the type of the arguments (formal parameters). No other variables can be declared at this point. Recent compilers permit including the argument declaration within the parentheses like type – specifier function – name (data type argument 1, data type argument2 ……).

Example:
            1.float average (int a, b, c);
                        or
               float average (a, b, c)
               int a, b, c;

            The data type void may be used for the return type of the function where the function does not return any value.

Example:

            Void printblank(void)
3) Function body:
            After declaring the type of function, function-name, formal arguments, a statement or block of statements is placed between the begin and end braces. The declaration of local variables is required only when any local variables one used in the function.       
Example:
            /* function definition*/
            factorial (x)  /* function header */
            int x
            {
              int i fact=1;
              for (i=1;i <= x; i++)
              fact= fact *i;
              printf (“factorial of given no. is %d”, fact);
}
Return statement:

            The keyword return is used to terminate function and return a value to its caller. The return statement may also be used to exit a function without returning a value. The return statement may or may not include an expression.

The general form of the return statement is
Syntax:
return;
(or)
return (expression);

Example:

maximum (a, b)
float a, b;
{
   if(a>b)
      return (a);
   else
      return (b);
}
A function may have not return statement at all. When the end of the function is reached, control is automatically transferred to the calling point with no return value from the function.
Calling a function:

            A function gets called when the function name is followed by a semicolon. When the function is called, the formal parameters are automatically initialized to the actual parameters used in the function. The number of actual and formal parameters must be equal. Next the function body executed. If a return statement is encountered during execution of the function body, the function terminates execution, returning the value specified in the return statement (if any) as the value of the function.
            A function must always be defined in the global environment; that is a function cannot be defined within another function.
Example:
            F=factorial (n).
The parameter n is called the actual parameter. The actual parameters should match in type, number and sequence with the formal parameters appearing in the function definition. In the absence of any arguments of any arguments, an empty pair of parentheses should be given.
Types of functions:

The used defined functions may be classified into three types.

1.Functions with no arguments and no return values
2.Functions with arguments and no return values
3.Functions with arguments and return values
1) Functions with no arguments and no return values:
            This is the simplest way of writing a user defined function in C. There is no data communication between a calling portion of a program and called function block. No return statement is employed here.

Example:
            main ()
            {
                        void display(); /*function declaration*/
                        display ();
            }

/*function definition*/
void display ()
{
                        char name[20];
            printf (“type ur name”);
                        scanf (“%s”, name);
            printf (“%s\n”, name);
}

2) Function with arguments but no return value:

            The second type of writing user defined function is passing some formal arguments to a function but the function does not return back any value to the caller. It is a one program and the function block.
Example:
#include
main ()
{
            int a,b,c;
            scanf(“%d%d%d”,&a,&b,&c);
big(a,b,c);
}
big(x,y,z)
int x,y,z;
{
     if(x>y && x>z)
       printf(“\n x is biggest”);
     else
       if(y>z)
          printf(“\n y is biggest”);
       else
          printf(“\n z is biggest”);
}












3) Functions with arguments and return values:
            Unlike the two categories discussed earlier, in this type two-way data communication takes place. That is, both the called and calling functions receive and transfer data from each other.
Example:
#include
main()
{
 int i, max, temp;
 printf(“enter a value for n\n”);
 scanf(“%d”,&max );
 printf(“Number square\n”);
 for(i=0;i
{
            temp=square(i);
 }
}
square(n)
int n;
{
   int value;
   value= n* n;
   return (value);
}



Program to accept two numbers and print sum of two numbers by using functions
# include
# include
main( )
{
int a,b,c;
clrscr();
printf(“enter the value for a:”)
scanf(“%d”,&a);
printf(“enter the value for b:”)
scanf(“%d”,&b);
c=add(a,b);
printf(“sum of two numbers is %d”,c);
getch( );
}
int add(int x, int y)
{
int z;
z=x+y;
return z;
}




36. Program to accept a number and find factorial of given number

# include
# include
main( )
{
int n,f;
clrscr( );
printf(“enter a number:”)
scanf(“%d”,&n);
f= fact(n);
printf(“factorial value is %d”,f);
getch();
}

int fact(int n)
{
int i, fa=1;
for(i=n;i>=1;i--)
fa=fa*i;
return fa;
}



37. Program to accept a number and check the given number Armstrong or not
# include
# include
main( )
{
int n,arm;
clrscr();
printf(“enter any 3 digit number:”)
scanf(“%d”,&n);
arm= armstrong(n);
if(arm= =n)
printf(“%d is Armstrong number”,n);
else
printf(“%d not a Armstrong number”,n);
getch( );
}
int Armstrong (int n)
{
int a,b,c,d;
a=n/100;
b=((n/10)%10);
c=n%10;
d=a*a*a+b*b*b+c*c*c;
return d;
}
38. Program to accept a number and print the sum of given and Reverse number
# include
# include
main( )
{
int a,b,n;
clrscr( );
printf(“enter a number:”)
scanf(“%d”,&n);
a=rev(n);
printf(“REVERSE OF A GIVEN NUMBER IS %d”,a);
b=add(n,a);
printf(“\n sum of a given and reverse number is %d”,b);
getch( );
}
int rev( int n)
{
int r,rev=0,s;
while(n>0)
{
r=n%10;
rev=rev*10+r;
n=n/10;
}
return rev;
}
int add(int n, int a)
{
return n+a;
}
39. Program to accept 10 numbers and print first five numbers in original order and print last five numbers in reverse order.
# include
# include
main( )
{
int i,a[10];
for(i=0;i<10 i="" o:p="">
{
printf(“enter value for a[%d]”,i);
scanf(“%d”,&a[i]);
}
for(i=0;i<=4;i++)
printf(“\nA[%d]=%d”,i,a[i]);
for(i=9;i>=5;i--)
printf(“\nA[%d]=%d”,i,a[i]);
getch( );
}









Local and global variables:
Local variables:
            Variables that are defined inside the function block or a statement block are called local variables. The variable name and it contents are known only with in that block. These are not available for reference or use elsewhere in the program. Even other parts of same function cannot access them, if those parts are outside the block where the variable is defined.

            Local variables are created and destroyed with each entry and exit from the block in which they are defined. The same name can be given to different local variables in different function or blocks of the same program without any side effect.

Example

For(I=0;i<4 i="" o:p="">
{
     int j,k;
----------
----------
---------
}
func1( )
{
     int i;/*local variable i is defined inside the function*/
    
     i=15;
     ------------
     -----------
}
Global variables:

            Global variables are created by defining them outside of all functions in the program. The common practice is that that all global variables are defined at the beginning of the program before any function. They can, therefore, be accessed by any function in the program.

            Global variables may, however, be placed any where in the program, prior to their first use, provided they are defined outside of the functions. In this case, the contents of the variables are available for use only by those functions of the program occurring after their definition.
Example:
int a,b; /*global variables defined outside all functions*/
#include
main()
{
----------
-----------
----------
}
fun1( )
{
----------
----------
----------
}

Nesting of functions:
One important advantage of C function is that they can be called from and within another function. There is no restriction in C for calling the number of functions in a program. It is advisable that the complex problem may be decomposed into a small easily manageable part and defines a function. The control will be transferred from calling portion of a program to the called function. If the called function is executed successfully then control will be transferred back to calling portion of a program.
Example
main( )
{
----------
---------
----------
}

function2 ()
{
------------
------------
-------------
}
function1( )
{
-----------
-----------
function3( )
}
function3( )
{
---------------
--------------
function2( );
}
Recursion:
            Recursion is a technique that has been implemented in most high-level languages. A recursive function is one that call itself, but which halts at some definite point to avoid infinite recursion. This concept can be explained by reference to the factorial function in mathematics. Given a positive number n, the factorial of that number can be defined recursively as
n! = 1 if n=1 or 0
                   (n-1)! Otherwise    
For example:
4! =4 * 3!
   =4 * 3 * 2!
   =4 * 3 * 2 * 1!

Now 1! =1
4!=4 * 3 * 2 * 1=24

            In C, a recursive function that calculates a factorial can be written as follows

factorial (n)
int n;
{
if (n= =1)
     return 1;
else
     return (n * factorial(n-1));
}
            In this case the first call f the function factorial the value of (n-1) is passed to the called function. Till the called function returns to value of (n-1)! the calling function cannot evaluate n * (n-1)!. The called function in turn passes the value (n-1) by another call and the process is continued till the value of n becomes 1. There is an if statement in the function block which tests whether n is equal to 1 and if test proves true, return the result of 1 to the previous call. The called functions complete their task one by one in the reverse order in which they were invoked. i.e. the first version finishing last and the last version called finishing first. If the if construct is not present, there will be no return point and the program will hang.
Functions and arrays:
            The entire array can be passed to a function in C. To pass an array, without any array to called function it is sufficient to list the name of the array, without any subscripts or size of the array.
For example the call
            Largest (a, n); will pass the elements contained in the array ‘a’ of size n.
            The largest function header might look like
            foat largest(array, size)
            float array[ ]; /* it is not necessary to specify the size of the array here */
            int size;
the function largest is defined to take tow arguments, the array name and the size of the array to specify the number of elements in the array.


























Chapter-8
Storage Classes
·       auto
·       static
·       extern
·       register
Storage Classes (or) The Scope and Lifetime of Variables:

            Every variable and function in  C is associated with a data type.  In addition to the data type, C associates a storage class with variables and functions.

            A storage class associates with its object (variable or function) certain properties such as scope and lifetime in a program.

            By scope of an object we understand that the portions of the program in which the object can be used. The lifetime of an object is the period of time during which it is allocated storage space in memory.

            The scope and Lifetime of objects are determined by storage class specifications. There are four different class specifiers.

1.auto

2.static

3.extern

4.register
1) Auto storage class:
            All variables with in a function, by default belong to the automatic storage class. The keyword auto identifies a variable as automatic. However, the absence of any storage class specifier defaults to auto and hence we need not explicitly define them.

Example:

main( )
{
auto int i,j;/* same as int i,j */
auto char a[15];
--------------
---------------
}
The scope of automatic variables is confined to the function or block in which they appear. They are created when the function is called and destroyed when the function is exited. Their memory locations get deal located when the function is exited. They are recreated when the function is called again.

            Automatic variables are not initialized to any value when they are created. They usually start with garbage values. Automatic variable have two pleasing aspects. First memory space used economically. Second, their local scope protects us from affecting them inadvertently in other functions. So variable in other function need not necessarily be given different names.
Example:
main( )
{
  auto I=1;
{
            auto int I=2;
{
            auto int I=3;
            printf(“%d\n”,I);
}
printf(“%d\n”,I);
}
printf(“%d\n”,I);
}

output is 3
               2
               1
because there I’s are different since they are defined in different block.
2) Static storage class:
            The static variables are defined with in a function and they have the same scope of  rules of automatic variables but in the case of static variables the contents of the variables will be retained through out the program. Static is a keyword used to define the storage class as static
            In the absence of any initialization , static variables are initialized to zero
Example:
int func(int x)
{
static float a;
static int b[]={1,2,3,4,5};
--------
---------
}
The variables a and the array b have been declared static. They will start with an initial value and their value when the function is exited is retained. Their memory locations are not deal located.
Program:
The following program illustrates the use of static variable to produce a series of 10 numbers divisible by 7 starting with a value of 0.

#include
void main()
{
 int j=0;
while(j<10 o:p="">
{
            seven();
            j=j+1;
}
}

seven()
{
static int i;
i=i+7;
printf(“%d\n”,i);
}

output:
7
14
21
.
.
.
.
.
.
.
70
Global or external static variables:
            Static variable can be declared both inside and outside a function. Static variables declared inside a function are called internal or local, while those outside a function are called ‘external’. External static variables are known only within the module from which they are declared. Internal static variables are known only within the function from which they are declared.

            The difference between a static global variable and simple global variable is that the static global variable is available only within the file it is defined while the simple global variable can be accessed by other files.
Example:
#include
static int I;
main()
{
  int j=0;
 i=28;
While(j<10 o:p="">
{
   seven();
   j=j+1;
}
}
seven()
{
i=i+7;
printf(“%d\n”,i);
}




3) External storage class:

            The variables that are declared before the function main () are globally existing for all the functions inside the program. So these variables are called global variables. The extern declaration of the variables makes the variables to be available even for the external functions that are called from the program.

Example:

#include
int i,j;  //external variables
float x;
main()
{
-------------
-------------
-------------
}


            Here j, x and i are defined outside of all functions, including main. Therefore they are external. However they should not be preceded by the word extern. They are recognized as external by virtue of their position in the program.

            External variables are created when they are defined and are permanently available thereafter. Thus their scope is the entire program and their extent from the time of creation till the termination of the program. When not initialized specifically, they are automatically initialized to zero.

            We have seen that all external variables are declared at the beginning in a program. However they may be declared any where in a program.

Example:

main()
{
----------
----------
----------
}
fun1()
{
---------
---------
---------
}
float c,b;
fun2( )
{
-----------
-----------
-----------
}

            In this example the external variables c and b are declared after two function main() and fun1(). Hence these two functions cannot access these variables. In such situations an external variable referencing declaration should be included in the function which access those variables, yet to be defined.

Example:


main()
{
extern float a,b;//a,b are defined else where in the program
----------
----------
}
fun1( )
{
extern float a,b;//a,b are defined else where in the program
---------
---------
}
float c,b;
fun2( )
{
---------
---------
}

            The keyword extern must appear in an external referencing declaration. It distinguishes a referencing declarations from a definition. When a variable is defined, memory space is created. When it is only declared no, memory space is created.

In a particular program a local variable and a global variable have the same name, the local variable will have precedence over the global one in the function where it is declared.

4) Register storage class:

            All computers have a few memory locations on the microprocessor chip itself. These memory locations are known as registers. Storage and retrieval of data from a register can be done by a program much faster than from a location in the main memory of the computer.

            The normal place of storing the value of variables is the main memory. If however, the storage specifier register qualifies a variable, the contents of the variable defined is stored in one of the registers of the CPU. Register storage can be specified only to local variables not to global variables. Register variables are ideal for use where there is a repeated use of that variable such as in loop.

Example:

            register int a;

            The scope and life of a register variable is similar to that of automatic variables.

            There are some restrictions on register variables. Since a machine register is usually single word, many compilers only allow those variables that fit into a word to be placed in registers. This means that int, char, or pointer variables can only in registers. In addition, most compilers also have a only a few registers available to user programs, usually two or three.

Suppose, some of the variables have been declared as register and if these variables are not the correct data type such as char or int and if there are not enough registers available, then the C compiler will automatically ignore the register data type and it keeps them in the memory. It will be treated as and automatic variable.

Program:
Write a program to display the number and its suare from 0 to 10 using register variables.
Main()
{
            register int x,y,z;
            x=0;
            y=0;
            do
            {
                        z=f(x,y);
                        printf(“%d\n”,x,y);
                        ++x;
                        ++y;
            }
            while(x<=10);
}

f(x,y)
register int x,y;
{
            register int temp;
            temp=x*y;
            return(temp);
}

The various storage classes are summarized as follows

Storage class
Used with
Purpose and usage
Auto
Local variables and formal parameters
Loses value when the function execution ends. Not accessible even by the functions in the same source file. Not initialized automatically. Explicit initialization is necessary
Static
Defined within a function
Initialized to zero automatically. Retains values between calls.
Extern
Defined outside the functions
Accessible by all functions initialized to zero automatically.
Register
Local variables and formal parameters
Number limited. For fast execution of functions in loop control

 

Chapter-9

Structures and Unions

            A structure is a collection of one or more variables, which may be of different types, grouped under a single name. For example, if we consider the student details, we may have to refer students register no, his name, his marks in subjects, and average. Such data are of different types, but they give meaningful information, when grouped together.

            In such environments, the data type ‘stru ct’ (structure) in C is highly helpful. A group of one or more variables of different types organized together under a single variable name is called as a structure.  In other high level languages a structure would be known as a recorded.

Declaration of Structure:

            The general form of structure definition is
            Syntax:
            Struct     < tag-name >
            {
                        data-type member1;
                        data-type member1;
                        data-type member1;

                        .                       .
            };
The keyword struct and the braces are required. The tag-name is usually used, but there are situations in which it is not required. The data – type and members are any valid C data types such as int, char, float.

Example:

struct student
{
int rno;
int age;
char sex;
float height;
float weight;
};

            It is possible to define a structure variable name in the structure type declaration itself.
struct student
{
int rno;
int age;
char sex;
float height;
float weight;
} a,b;
            Now a, b are the two structure variables to be of a type structure student.

Structure Manipulation:

            The structure members can be reference only with the structure name as qualification separated by the period operator. It is referenced as
Structurename.member;
Example:
struct student
{
int rno;
int age;
char sex;
float height;
float weight;
} a,b;
a.rno, a.age, a.height etc.
Assigning values to the member of the structure:
            a.rno=100;
            a.age=24;
            a.sex=’M’;
            a.height=5.5;
            a.weight=60.5;
The C compiler will not read or write an entire structure as a single command.  It will read or write the members of a structure as follows:
            Scanf(“%d”, &a.rno);
            Scanf(“%d”,&a.age);
            Scanf(“%c”,&a.sex);
            Scanf(“%f”,&a.height);
            Scanf(“%f”,&a.weight);
To display the members of a structure
            Printf(“%d”, a.rno);
            Printf(“%d”,a.age);
            Printf(“%c”,a.sex);
            Printf(“%f”,a.height);
            Printf(“%f”,a.weight);

Initia1lizing a structure:

            A structure can be initialized as the way of another data type in C.
For example:
struct student
{
int rno;
int age;
char sex;
float height;
float weight;
};
struct student ={1001,24,’M’, 168.2,48.2};
The compiler will assign the following ways to each of the field
rno=1001
age=24
sex=’M’
height=168.2
weight=48.2

Arrays and Structures:

            Structure arrays can be defined, so that each array element ca be of structure data type. In the following example, the employee info structure is an array of 100 employee info structures named staff
struct employee
{
char name[20];
char sex;
int age;
char designation [16];
float gross_pay;
} staff[100];
This declaration staff to be an array with 100 elements. Each element of this array is structure employee type. Thus staff[0] is an employee structure, staff[1] is another employee structure and so on.
Since staff is an array, we use the usual array accessing methods to access individual elements and then the number operator to access member.

Arrays within structures:

            C permits the use of arrays as structure members.

Example:

Struct marks
{
int number;
float subject[3]
} student[3];

            Here the member subject contains 3 elements, subject[0], subject[1], subject[2].
For example student[1].subject[2] would refer to the marks obtained in the 3rd subject by the second student.

Nested structures:

            A structure can be defined as an element of another structure. The structure to be included as part of another structure can be defined inside the structure definition or outside as an individual structure type. That is called nesting.

Example:

struct payroll
{
  int empno;
  char name[20];
  int pay;
  struct date
  {
     int day, month, year;
  } birthdate, joindate;
  int citycode;
} emp[20];

            In this example, the structure describes the elements payroll of employees. One of the element is a structure type date, birthdate and joindate are two elements of the structure payroll which were of structure type date.

            In such environment the reference to the element of date structure can be made by giving two qualifications as follows.

            emp[0].birthdate.day references the inner structure element day of birthdate of emp[0].

Structures and functions:


            A structure can be passed to a function as a one variable or as an individual member. The scope of a structure declaration should be external storage class whenever a function in the main program using a structure data types. The field name should be same throughout the program either in a main or in a function.

Example:


1.A structure may be passed into a function as one variable as

struct sample
{
int x;
float y;
};
struct sample first;

#include
main()
{
--------------
--------------
--------------
display(first);
--------------
-------------
}
display(out)
struct sample out;
{
----------------
-----------------
out.x=20;
out.y=423.4;
----------------
---------------
}

2.A structure may be passed into a function as individual element as

struct sample
{
int x;
float y;
};
struct sample first;
#include
main()
{
-----------------
-----------------
display(first.x,first.y);
------------------
-----------------
}
display(out)
struct sample out;
{
----------------
---------------
out.x=38;
out.y=48.36;
----------------
----------------
}


 Program to read data in 3 structures and print
# include
# include
main( )
{
clrscr( );
struct book
{
char code;
int piece;
float price;
};
struct book b1,b2,b3;
printf(“enter code,piece,price”);
scanf(“%c%d%f”,&b1.code,&b1.piece,&b1.price);
printf(“enter code,piece,price”);
scanf(“%c%d%f”,&b2.code,&b2.piece,&b2.price);
printf(“enter code,piece,price”);
scanf(“%c%d%f”,&b3.code,&b3.piece,&b3.price);
printf(“the details are”);
printf(“\n %c%d%f”,b1.code,b1.piece,b1.price);
printf(“\n %c%d%f”,b2.code,b2.piece,b2.price);
printf(“\n %c%d%f”,b3.code,b3.piece,b3.price);
getch( );
}
 Program a structure which stores information about hotels which stores information about name, grade, room change, no of rooms.                                                        
  a) Print the hotels of given grade in order of roomchange.  
b) Print the hotels with roomchange less than a given change.
#include
#include
main( )
{
struct hotel
{
char name[20];
char city[10];
char grade;
int rc,nr;
};
struct hotel ht[20],t;
int i,n,j,c;
char gr;
clrscr( );
printf(“enter no. of hotels\n”);
scanf(“%d”,&n);
for(i=0;i
{
printf(“enter name of hotel \n”);
scanf(“%s”,&ht[i].name);
printf(“enter name of city \n”);
scanf(“%s”,&ht[i].city);
printf(“enter the grade \n”);
scanf(“%s”.ht[i].grade);
ht[i].grade=getche( );
printf(“enter room charge \n”);
scanf(“%d”,&ht[i].rc);
printf(“enter no of rooms \n”);
scanf(“%d”,&ht[i].nr);
}
for(i=0;i
for(j=0;j
{
t=ht[j];
ht[j]=ht[j+i];
ht[j+1]=t;
}
printf(“enter a grade to print the hotels \n”);
gr=getche();
clrscr();
printf(“hotel name city grade roomcharge no of room”);
for(i=0;i
if(gr==ht[i].grade)
printf(“%s %s %c %d %d”,ht[i].name,ht[i].city,ht[i].grade,ht[i].rc,ht[i].nr);
getch();
printf(“enter a room charge to print hotels less than given charge \n”);
scanf(“%d”,&c);
printf(“hotel name city grade roomcharge no of rooms”);
for(i=0;i
if(c<=ht[i].rc)
printf(“%s %s %c %d %d”,ht[i].name,ht[i].city,h[i].grade,ht[i].rc,ht[i].nr);
}
61. Program a structure which reads ‘n’ students information (name,3 subjects marks) and calculate total marks, result print them in a particular format.
# include
# include
main( )
{
struct student
{
char name[20];
int m1,m2,m3, tot;
char result[10];
}stud[10];
int i,n;
clrscr( );
printf(“enter no of students \n”);
scanf(“%d”,&n);
for(i=0;i
{
printf(”enter %d student deatails \n”,i);
printf(”enter name\n”);
scanf(“%s”, stud[i].name);
printf(“enter marks of 3 subjects \n”);
scanf(“%d%d%d”, &stud[i].m1,&stud[i].m2,&stud[i].m3);
stud[i].tot=stud[i].m1+stud[i].m2+stud[i].m3;
if((stud[i].m1>35)&&(stud[i].m2>35)&&(stud[i].m3>35))
strcpy(stud[i].result,”pass”);
else
strtcpy(stud[i].result,”fail”);
}
clrscr( );
printf(“name total result \n”);
for(i=0;i
{
printf(“%s %d %s \n”, stud[i].name,stud[i].tot,stud[i].result);
}
getch( );
}






Unions:


            Union is another data type with two or more members, similar to structure. But in this case, all the members share a common memory location. The members of a union can be referred by using the dot operator as in the case of a structure. The size of  a union  can contain only one type of member at any one time. The size of union corresponds to the length of the longest member.

The general form of union declaration is,

Syntax:

Union tag – name
{

data type member1;
data type member1;
--------------------
--------------------
data type member1;

}variable1,variable2,………;

Example:

union x
{
   int i;
   char c;
};
Here union is the keyword. The union with the tag – name x contains either an integer i
or char c at any one time. Since a character needs only one byte of storage as compared to two bytes required for an integer, the union is of two bytes length in this case. Union are used to minimize use of storage when it is known that only one object out of many will be active at any given time. Union may also have complex members such as arrays.
            We may have structures within unions and unions within structures. Unions may also be initialized like structures. However, since only one member can be active at a time, usually the assigned value will go to the first member of the union.
Program:
#include
void main()
{
            union value
            {
                        int i;
                        float f;
            }
            union value x;
            x.i=10;
            printf(“the value of i is %d\n”, x.i);
            x.f=-428.36;
            printf(“The value of f is %f\n”, x.f);
}

Chapter-10

Pointers

·        Introduction to Pointers
·        Declaration of Pointer Variables
·        The “Address of” Operator (&)
·        The “Indirection” Operator (*)
·        Pointer Arithmetic
·        Pointers and Functions
§  Call by Value
§  Call by Reference
·        Pointers and Arrays
·        Pointers and Strings
·        Array of Strings
·        Pointer to Pointer
·        Pointers and Structures
·        Self Referential Structures
·        Dynamic Storage Allocation
§  malloc()
§  calloc()
§  free()

Introduction to pointers:

            A pointer is a variable, which holds the memory address of another variable. Most commonly, this address is the location of another variable where it has been stored in memory. If one variable contains the address of another variable, then the first variable is said to point to the second.

For example, consider the statement
int a=5;
            This statement instructs the system to locate an integer variable and assign 5 in that location. Let us assume that the system has chosen the address 1000 for a . This situation is figuratively represented as

 








Let us assign the address of a the variable to  b and assume that address of b is 1004. Now the relation between a and b can be represented as

                       

Since the value of b is the address of variable ‘a’ we may access the value of a by using the value of b. Hence b gets the name pointer. The location that a pointer points to may contain character, an integer, a float or any other data type.
variable                                           value                  memory address
     a                                                     5                            1000
     b                                                    1000                       1004

 

 

Declaration of pointer variables:


            A pointer variable can be declared in the same way as the other variables, but an asterisk symbol should precede the variable name. This identifies the variable is a pointer.

           
The general form of the declaration is

                        Datatype    *variablename;

Example:

Int *ptr;
char *c;
The address operator (&):
            The address of any variable can be got by preceding the variable name by ampersand (&). For example, the declaration
            int i;
            float x;
            Declare and assign memory locations for i and x  &i, &x are the addresses of these locations.
Ptr=&i;// address of I will be stored on ptr
Ptr1=&x; //address of x is stored in ptr1.
            When an array is accepted through scanf, it does not require &, because the address of an array is represented by the array name itself.

The * operator:

            This operates on pointers and results in the contained in the location pointed by the pointer. The *(asterisk) is called indirection operator.
Example:
int *a,b,c;  //a is a pointer variable
b=5;
a=&b;
c=*a;
c=*a is equivalent to c=b.

Pointer arithmetic:

The C language supports four arithmetic operators that may be used with pointers such as

addition +    subtraction  -            incrementation ++     decrementation –

            A pointer when incremented or decremented is always relative to to its base type. That is, its value is increased or decreased by the length of the data type.

Example 1:

int value, *ptr;
value=120;
ptr=&value;
ptr++;

            The incrementation ptr++ increments the number of bytes of the storage class for the particular machine. If the system used two bytes to store an integer, then ptr++ will be incremented by 2 bytes.

Note:


Pointers are not permitted to perform the following arithmetic operations.

1.Multiply or devide
2.to operate bitwise shift
3.to add or subtract float or double type of pointers.

Pointers and functions:


            The parameters to the functions are passed in two ways. Call by value and call by reference. In the lesson on functions, the parameters were passed by value only. With pointer type variables, it is possible to pass parameters by reference.

Call by value and call by reference:


            When an argument passed by value, the data item is copied to the function. Thus any alteration made to the data item within the function is not carried over into the calling routine. This type of passing arguments to a function is called, call by value.

            When an argument is passed by reference (i.e. when a pointer is passed to the function) the address of the data item is passed to the function. The contents of that address can be accessed freely, either within a function or within a calling routine. More over any change that is made into the data item will be recognized in both the function and calling portion of the program.

            Thus use of the pointer as a function arguments permit the corresponding data item to be altered globally from within the function.

Pointers and arrays:


            In C, arrays and pointers are closely related. Whenever an array is created a block of memory is created and a pointer is made to point it. We may access the elements of this array by the subscripts or with the help of this pointer.

Consider the declaration
            int a[10];
s
            By this declaration ten memory locations each occupying 2 bytes of memory are allocated consecutively for the array variable a.

            We have learnt that integer values can be added to pointers. In C, the name of an array contains the array’s starting address, the array name itself is a pointer. Thus when a is a pointer to a[0].
(a+1) will points to a [1]
(a+2) will points to a [2]
.
.
.
.
(a+n) will points to a [n]

The value of the nth element may be accessed as a[n] of *(a+n).

The following two statements are equivalent

printf(“%d”,a[n]);
printf(“%d”,*(a+n));

now a[n] is same as *(a+n)
hence &a[n] is same as (a+n)
pointers and strings:
            Strings are nothing but arrays of characters. Since arrays and pointers are equivalent, it should be possible to declare and manipulate strings with pointers. For example, the declaration
char st[20];
declares a string st of 20 characters, including the null character ‘\0’
we may declare the same as char *st;

Here st is a pointer to a character and hence equivalently a array of characters. The only distinction between the two ways of declaring string is that, while in former, st can not have more than 20 characters, in the later there is no such restriction.
Value of string may be read as,
char *st;
scanf(“%s”,st);
or
gets(s);

Arrays of strings:

            An array of string is a two dimensional array of characters. Hence we may declare an array of 10 strings, each of which may be at most 20 character length as
Char names[20][20];
Or
Char *name[10];
The above two declaration create an array of strings. The only difference is that while in the former each string is provided with 20 spaces in memory and can be at most 20 characters long in the latter each pointer can point to string of any length.
            To read these strings we may write
for(j=0;j<10 j="" o:p="">
gets(name[j]);
we may initialize arrays as follows
char *name[3]={“jan”,”feb”,”march”};
or
char *name[]={“jan”,”feb”,”march”};
by not specifying the size of the array as in the above declaration, we may have any number of strings in the initialization and accordingly the size of the array is determined.

Pointer to Pointer:


            In the case of pointer to pointer, the first contains the address of the second pointer, which points to the variable that contains the value desired. A variable that is a pointer to a pointer must be declared by placing an additional * in front of the variables name.

For example

           
            Int **p;

            Where p is pointer which holds the address of another pointer.

Pointers and structures:


            A pointer can be declared in such a way that it points to a structure data type. A pointer to a structure is created as follows

struct student
{
int rno;
char name[20];
float avg;
};
struct student *s;

            The pointer structure variable will be accessed and processed in one of the following ways.

(*structurename).fieldname;

(or)
structurename->fieldname;
To access the elements of the structure pointed by s as
s->rno;
s->name;
s->avg;
(or)
(*s).rno
(*s).name
(*s).avg
self referential structures:
            when a structure contains a pointer to itself, it is known as a self referential structure.
struct list
{
int data;
struct list *next;
};
            Where list is structure that consists of two members one is a data item and other is a pointer variable holding the memory address of the other structure. The pointer variable next contains an address of either the location in memory of the successor list or the special value NULL. The null is used to denote the end of the list.

Dynamic Storage Allocation:

            In C language, the memory required by any variable can be allocated and already occupied memory by variables can be released when not required, through built in functions. Such a concept of allocating and releasing the memory is known as dynamic storage allocation.
            The following functions are used in C to use the dynamic memory allocations.
malloc()
calloc()
free()
sizeof()
These functions are declared in the following header files in the C standard library.

malloc( ):

            This function is used to allocate heap storage. Its name stands for memory allocation. The starting address is returned if the function is successful. A zero is returned if the function attempt to get a block of memory fails.

Example

int *ptr;

pt=(int *)malloc(10 * sizeof(int));
this malloc function allocates a block of 10 integers size locations(i.e) 20 bytes from the memory heap and returns a pointer to it. The pointer that is provided by the malloc is always of the type pointer to void. To assign this pointer to the pointer to integer ptr, type cast it with (int *) as shown
calloc():
            This function is used to allocate the contiguous memory. The name stands for calculated allocation. It is useful for arrays and array like structures where continuity of memory is required. The starting address of the area is returned if the function is successful otherwise a zero is returned.
ptr=(int *)calloc(n,sizeof(int));
Here n blocks of memory each containing 2 bytes of memory are allocated and the starting address is stored in ptr.

free():

            This function is used to free a portion of storage within the heap previously allocated by malloc() or calloc(). The argument of the function free() can only be a pointer.

free(ptr);

            This function releases the entire block of memory location, created dynamically and to which ptr is a pointer.
sizeof():
            sizeof() is an operator which computes the memory size of an item.

            The general form is
                        Variable=sizeof(item);
Variable is a variable to which the size is to be assigned and item is an object one wants to know the size of.


 Program to interchange two values using pointers.
# include
# include
void interchange(int *x,int *y);
main( )
{ int a,b;
clrscr( );
printf(“enter values of a and b”);
scanf(“%d%d”,&a,&b);
interchange(&a,&b);
}
void interchange(x,y)
int *x,*y;
{
int t;
t=*x;
*x=*y;
*y=t;
printf(“%d=x, %d=y”,*x,*y);
getch( );
}



Comments