+ All Categories
Home > Documents > Introduction to C Programming Language

Introduction to C Programming Language

Date post: 01-Nov-2014
Category:
Upload: pushpinder-singh-khalsa
View: 64 times
Download: 1 times
Share this document with a friend
104
Introduction To C Programming Language The C language was invented at Bell Labs by Dennis Ritchie in 1972 to allow the writing of the UNIX operating system, then developed by Ken Thompson and Dennis Ritchie. The UNIX operating system, born in the late 1960s - early 1970s, was written directly in assembly language for the machines which it was intended. born in the late 1960s - early 1970s, was written directly in assembly language for the machines which it was intended. If the assembly language for writing such a system, it was nevertheless not easy to use. Such language is in fact a particular type of processor, which makes the whole system should be rewritten to make it work on a new architecture. This is its main creator, Ken Thompson, wanted to use a language more quickly evolved to rewrite UNIX. Among the languages available at the time, BCPL (Basic Combined Programming Language for, which is a simplification of CPL), created by Martin Richards in 1966, was interesting. Without going into detailed descriptions, BCPL is a simple language, procedural, and not typed. Its simplicity makes it easy to create BCPL compilers on machines of the time, when resources were very limited (the first computer used by Keith Thompson was to launch a Unix PDP- 7, which had a memory of 4000 words 18 bits, or less than 9 KB). Ken Thompson has evolved to design the B language, which he implemented the first UNIX machines. However, some limitations of language B were UNIX could be rewritten in this language. From 1971, Dennis Ritchie B did evolve to address these issues. Like the programmers increment versions of their programs, Ritchie "Nudge" the letter B to call the new language C. This evolution is "stabilized" to 1973, from which UNIX and UNIX system utilities have been rewritten successfully in C. Subsequently in 1978, Brian W. Kernighan documentation very active language, and finally publish the book with reference Ritchie The C Programming Language. Often called K & R C language as specified in the first edition of this book. In the years that followed, the C language was carried on many other machines. These ports were often made at the beginning, from the pcc compiler Steve Johnson, but then the original compilers were developed independently. During these years, every C compiler was written in accordance with the specifications of K & R, but some added extensions, such as data types or additional features, or different interpretations of certain parts of the book (not necessarily very precise). Because of this, it was less easy to write C programs that can run unchanged on many architectures. Turbo C++ Integrated Development Environment IDE is nothing but Integrated Development Environment in which one can develop, run, test and debug the application. The Turbo C++ IDE appears as shown in figure.
Transcript
Page 1: Introduction to C Programming Language

Introduction To C Programming Language

                      The C language was invented at Bell Labs by Dennis Ritchie in 1972 to allow the writing of the UNIX operating system, then developed by Ken Thompson and Dennis Ritchie.

                      The UNIX operating system, born in the late 1960s - early 1970s, was written directly in assembly language for the machines which it was intended. born in the late 1960s - early 1970s, was written directly in assembly language for the machines which it was intended. If the assembly language for writing such a system, it was nevertheless not easy to use. Such language is in fact a particular type of processor, which makes the whole system should be rewritten to make it work on a new architecture. This is its main creator, Ken Thompson, wanted to use a language more quickly evolved to rewrite UNIX.

                      Among the languages available at the time, BCPL (Basic Combined Programming Language for, which is a simplification of CPL), created by Martin Richards in 1966, was interesting. Without going into detailed descriptions, BCPL is a simple language, procedural, and not typed. Its simplicity makes it easy to create BCPL compilers on machines of the time, when resources were very limited (the first computer used by Keith Thompson was to launch a Unix PDP-7, which had a memory of 4000 words 18 bits, or less than 9 KB). Ken Thompson has evolved to design the B language, which he implemented the first UNIX machines. However, some limitations of language B were UNIX could be rewritten in this language.

                     From 1971, Dennis Ritchie B did evolve to address these issues. Like the programmers increment versions of their programs, Ritchie "Nudge" the letter B to call the new language C. This evolution is "stabilized" to 1973, from which UNIX and UNIX system utilities have been rewritten successfully in C.

                      Subsequently in 1978, Brian W. Kernighan documentation very active language, and finally publish the book with reference Ritchie The C Programming Language. Often called K & R C language as specified in the first edition of this book.

                      In the years that followed, the C language was carried on many other machines. These ports were often made at the beginning, from the pcc compiler Steve Johnson, but then the original compilers were developed independently. During these years, every C compiler was written in accordance with the specifications of K & R, but some added extensions, such as data types or additional features, or different interpretations of certain parts of the book (not necessarily very precise). Because of this, it was less easy to write C programs that can run unchanged on many architectures.

Turbo C++ Integrated Development Environment

              IDE is nothing but Integrated Development Environment in which one can develop, run, test and debug the application. The Turbo C++

IDE appears as shown in figure.

              The C Developing Environment is a screen display with windows and pull-down menus. The program listing, error messages and other information are displayed in separate windows. The menus may be used to invoke all the operations necessary to develop the program, including editing, compiling, linking, and debugging and program execution. If the menu bar is inactive, it may be invoked by pressing the [F10] function key. To select different menu, move the highlight left or right with cursor (arrow) keys. You can also revoke the selection by pressing the key combination for the specific menu.

Invoking the Turbo C IDE

Page 2: Introduction to C Programming Language

              The default directory of Turbo C compiler is c:\tc\bin. So to invoke the IDE from the windows you need to double click the TC icon in

the directory c:\tc\bin.

               The alternate approach is that we can make a shortcut of tc.exe on the desktop.

Opening New Window in Turbo C

To type a program, you need to open an Edit Window. For this, open file menu and click “new”. A window will appear on the screen where the program may be typed.

Writing a Program in Turbo C

When the Edit window is active, the program may be typed. Use the certain key combinations to perform specific edit functions.

Saving a Program in Turbo C

To save the program, select save command from the file menu. This function can also be performed by pressing the [F2] button. A dialog box will appear asking for the path and name of the file.Provide an appropriate and unique file name. You can save the program after compiling too but saving it before compilation is more appropriate. 

Making an Executable File in Turbo C

The source file is required to be turned into an executable file. This is called “Making” of the .exe file. The steps required to create an executable file are:

1. Create a source file, with a .c extension.2. Compile the source code into a file with the .obj extension.3. Link your .obj file with any needed libraries to produce an executable programAll the above steps can be done by using Run option from the menu bar or using key combination Ctrl+F9 (By this linking & compiling is done in one step).

Compiling and linking in the Turbo C IDE

                    In the Turbo C IDE, compiling and linking can be performed together in one step. There are two ways to do this: you can select Make EXE from the compile menu, or you can press the [F9] key

Correcting Errors in Turbo C

If the compiler recognizes some error, it will let you know through the Compiler window. You’ll see that the number of errors is not listed as 0, and the word “Error” appears instead of the word “Success” at the bottom of the window. The errors are to be removed by returning to the edit window. Usually these errors are a result of a typing mistake. The compiler will not only tell you what you did wrong, they’ll point you to the exact place in your code where you made the mistake.

Executing a Programs in Turbo C

If the program is compiled and linked without errors, the program is executed by selecting Run from the Run Menu or by pressing the [Ctrl+F9] key combination.

Exiting Turbo C IDE

                     An Edit window may be closed in a number of different ways. You can click on the small square in the upper left corner, you can select close from the window menu, or you can press the Alt+F3 combination. To exit from the IDE, select Exit from the File Menu or press Alt+X Combination.

Page 3: Introduction to C Programming Language

A Simple C Program

                  Every C program must have one special function main (). This is the point where execution begins when the program is running. We will see later that this does not have to be the first statement in the program, but it must exist as the entry point. The group of   statements defining the main () enclosed in a pair of braces ({}) are executed sequentially. Each expression statement must end with a semicolon.  The closing brace of the main function signals the end of the program. The main function can be located anywhere in the program but the general practice is to place it as the first function.

Here is an elementary C program.

main ()

     {

     }

                  There is no way to simplify this program, or to leave anything out. Unluckily, the program does not do anything. Following the "main" program name is a couple of parentheses, which are an indication to the compiler that this is a function. The 2 curly brackets { }, properly called braces, are used to specify the limits of the program itself. The actual program statements go between the 2 braces and in this case, there are no statements because the program does absolutely nothing. You will be able to compile and run this program, but since it has no executable statements, it does nothing. Keep in mind however, that it is a legal C program.

                main ( ) function should return zero or one. Turbo C accepts both int and void main ( ) and Turbo C coders use both int and void main ( ) in their programs. But in my belief, void main ( ) is not a standard usage. The reason is, whenever a program gets executed it returns an integer to the OS. If it returns 'zero', the program is executed successfully. Otherwise it means the program has been ended with error. So main ( ) shouldn't be declared as void.d as void.

main( ) should be declared as

int main( )

   {

    ……………..

    ……………..

   return  0 ;     

  }

 .For a much more interesting program, load the program

int main ()

      {

       printf (“Welcome to C language”);

       return 0;

      }

and display it on your monitor. It is  same as the previous program except that it has one executable statement between the braces.                 

               The executable statement is another function. Again, we won't care about what a function is, but only how to use this one. In order to output text to the monitor, it's placed within the function parentheses and bounded by quotes. The end result is that whatever is included between the quotes will be showed on the monitor when the program is run.

Page 4: Introduction to C Programming Language

                Notice the semi-colon; at the end of the line. C uses a semi-colon as a statement terminator, so semi-colon is required as a signal to the compiler that this line is complete. This program is also executable, so you'll be able to compile and run it to see if it does what you think it should. With some compilers, you may get an error message while compiling, indicating that the function printf () should have a prototype.

#include<stdio.h>

#include<conio.h>

int main ()

        {

         printf (“Welcome to C language”);

         return 0;        }

              Here you'll be able to see #include at the beginning of the program. It is a pre-processor directive. It's not a part of our program; it's an instruction to the compiler to make it do something. It says the C compiler to include the contents of a file, in this case the system file stdio.h. This is the name of the standard library definition file for all Standard Input Output. Your program will almost certainly want to send stuff to the screen and read things from the keyboard. stdio.h is the name of the file in which the functions that we want to use are defined. A function is simply a group of  related statements that we can use later. Here the function we used is  printf . To use printf correctly C needs to know what it looks like, i.e. what things it can work on and what value it returns. The actual code which performs the printf will be tied in later by the linker. Note that without the definition of what printf looks like the compiler makes a guess when it sees the use of it. This can lead to the call failing when the program runs, a common cause of programs crashing.

                The <> characters around the name tell C to look in the system area for the file stdio.h. If  I had given the name "abc.h" instead it would tell the compiler to look in the current directory. This means that I can arrange libraries of my own routines and use them in my programs.

                 Imagine you run above program and then change it and run it again you may find that the previous output is still stucked there itself, at this time clrscr(); would clear the previous screen.One more thing to remember while using clrscr()  is that it should be called only after the variable declaration, likeint p,q,r;clrscr()

Here is an example of minimal C program that displays the string Welcome to C language (this famous example included in all languages moreover been done originally in C in 1978 from the creators of the language, Brian Kernighan and Dennis Ritchie) Example

#include<stdio.h>#include<conio.h>

int main ()

       {

        clrscr();

        printf (“Welcome to C language”);

        return 0;

       }

              When you execute above program you won’t see ‘Welcome  to C language’ on the  console  because  the screen will just flash and go away .If you want to see the line you can use getch() function just  below the printf() statement. Actually it waits until a key is pressed.

Example:

Page 5: Introduction to C Programming Language

Identifiers

            Identifiers are the names that are given to various program elements such as variables, symbolic constants and functions.Variable or function identifier that is called a symbolic constant name.

Identifier can be freely named, the following restrictions.

Alphanumeric characters ( a ~ z , A~Z , 0~9 ) and half underscore ( _ ) can only be used.

The first character of the first contain letters ( a ~ z , A~Z ) or half underscore ( _ ) can only be used.

Case is distinguishable. That is, word and WORD is recognized as a separate identifier.

Reserved words are not allowed. However, part of an identifier reserved words can be included.

Here are the rules you need to know:

1.       Identifier name must be a sequence of letter and digits, and must begin with a letter.

2.       The underscore character (‘_’) is considered as letter.

3.       Names shouldn't be a keyword (such as int , float, if ,break, for etc)

4.       Both upper-case letter and lower-case letter characters are allowed. However, they're not interchangeable.

5.       No identifier may be keyword.

6.       No special characters, such as semicolon,period,blank space, slash or comma are permitted

Examples of legal and illegal identifiers follow, first some legal identifiers:

float _number;

float a;

int this_is_a_very_detailed_name_for_an_identifier;

Page 7: Introduction to C Programming Language

Share on facebook Share on twitter Share on email Share on print More Sharing Services 47

Data Types

                  C offers a standard, minimal set of basic data types. Sometimes these are called "primitive" types. A lot of complex data structures can be developed from these basic data types. The C language defines 4 fundamental data types: characterinteger floating-point  and

double floating-point This data types are declared using the keywords char,int,float and double respectively. Typical memory requirements of the basic data types are given below

                 The size and range of these data types may vary among processor types and compilers. Data type qualifiers modify the behavior of variable type to which they are applied. Data type qualifiers can be classified into two types.two types.1. size qualifiers2. sign qualifiers

Size qualifiers:

               Size qualifiers alter the size of the basic data types. There are two size qualifiers that can be applied to integer: short and long.The minimum size of short int is 16 bit. The size of int must be greater than or equal to that of a short int. The size of long int must be greater than or equal to a short int. The minimum size of a long int is 32 bits.

Sign qualifiers:

             The keywords signed and unsigned are the two sign qualifiers that specify whether a variable can hold both –ve and +ve numbers, or only +ve numbers. These qualifiers can be applied to the data types int and char only.Example: unsigned int I;

The following table shows all valid data type combinations supported by C, along with their minimal ranges and typical memory size.

Share on facebook Share on twitter Share on email Share on print More Sharing Services 22

Page 8: Introduction to C Programming Language

int

                     An integer is a whole number (a number without a fractional part). It can be  positive or negative numbers like 1, -2, 3, etc., or zero.

The sizes of the integer variables depend on the hardware and operating system of the computer. On a typical 16-bit system, the sizes of the integer types are as follows.

TYPE Bytes Possible Values le Values

int 2 or 4  -32,767 to 32,767

unsigned int                    

2 or 4  0 to 65,535

signed int                    

2 or 4  -32,767 to 32,767

short int                     2 -32,767 to 32,767

unsigned short int      2 0 to 65,535

signed short int          2 -32,767 to 32,767

long int                       4 -2,147,483,647 to 2,147,483,647

signed long int                  

4 -2,147,483,647 to 2,147,483,647

unsigned long int           

4 0 to 4,294,967,295

Example:

Share on facebook Share on twitter Share on email Share on print More Sharing Services 54

Page 9: Introduction to C Programming Language

char

                    char is a special integer type designed for storing single characters. The integer value of a char corresponds to an ASCII character. E.g., a value of 65 corresponds to the letter A, 66 corresponds to B, 67 to C, and so on.

                    As in the table below, unsigned char permits values from 0 to 255, and signed char permits values from -127 (or -128) to 127. The char type is signed by default on some computers, but unsigned on others the sizes of the char types are as follows.

Type                         Bytes                Minimal range

char                               1                    -127 to 127

unsigned char              1                     0 to 255

signed char                   1                   -127 to 127

Example:

Float

                   Floating point numbers are numbers with a decimal point. The float type can take large floating point numbers with a small degree of precision (Precision is simply the number of decimal places to which a number can be calculated with accuracy. If a number can be calculated to three decimal places, it is said to have three significant digits.)

Memory size   : 4 bytes

Minimal range : IE-38 to IE+38 with six digit of precision

Example:

Page 10: Introduction to C Programming Language

Double

                     Double-precision floating point numbers are also numbers with a decimal point. We know that the float type can take large floating point numbers with a small degree of precision but the double-precision double type can hold even larger numbers with a higher degree of precision.

The sizes of the double types are as follows.

Type                  Bytes     Minimal range

doubleprecision  8          IE-38 to IE+38 with 10 digit of precision

long double          8          IE-38 to IE+38 with 10 digit of precision

Example:

Page 11: Introduction to C Programming Language

Constants

               The term constant means that it does not change during the execution of program. There are four basic types of constants in C. They are:

1.Integer constants 2.Floating-point constants 3.Character constants 4.String constants

                 Integer and floating-point constants represent numbers. They are often referred to as numeric-type constants. The following rule applies to all numeric type constants:

Comma and blank spaces cannot be included within the constants. Constants can be preceded by a – or + sign, if desired. If either sign does not precede the constant it is assumed to be positive.

The value of a constant cannot exceed specified minimum and maximum bounds. For each type of constant, these bound vary from one C compiler to another.

Integer constants                        Integer constants are whole numbers without any fractional part. Thus integer constants consist of a sequence of digits.

Integer constants can be written in three different number systems: Decimal, Octal and Hexadecimal.                        A decimal integer constant consists of any combination of digits taken from the set 0 through 9. If the decimal constant

contains two or more digits, the first digit must be something other than 0. The following are valid decimal integer constants. 0                  1             1234          -786

Example:

Page 12: Introduction to C Programming Language

The following decimal integer constants are written incorrectly for the reasons stated. 12,001               Illegal character (,).

103.0                 Illegal decimal point (.).10 20 30           Illegal character (blank space).045                    First digit cannot be zero.

Example:

                 An octal integer constant can consist any combination of digits taken from the set 0 through 7. However, the first digit must be 0, in order to identify the constant as an octal number. The following are valid octal integer constants.

0                  01            0125          0555

Example :

Page 13: Introduction to C Programming Language

The following decimal integer constants are written incorrectly for the reasons stated. 2010               Does not begin with 0.

2008                      Illegal digit (8).05.10                     Illegal character (.).

A hexadecimal integer constant must begin with either 0x or 0X. It can then be followed by any combination of digits taken from the set 0 through 9 and A through F (either upper-case or lower-case). The following are valid hexadecimal integer constants.

0X0                  0x1            0XAB125          -0x555

Example:

The following hexadecimal integer constants are written incorrectly for the reasons stated. 0x20.10                Illegal character (.).

02008                    Does not begins with 0x or 0X.0xabcdefg           Illegal character (g).

Floating-point constants                  A floating-point constant is a base-10 number that contains either a decimal point or an exponent or both. A floating-point

constant can be written in two forms: Factorial form or Exponential form. A floating-point constant in a fractional form must have at least one digit each to the left and right of the decimal point. A floating-point in exponent form consists of a mantissa and an exponent. The mantissa itself is represented as a decimal integer constant or a decimal floating-point constant in fractional form. The letter E or e and the exponent follow the mantissa. The exponent must be a decimal integer. The actual number of digits in the mantissa and the exponent depends on the computer being used.

The following are valid floating-point constants.</1.0             0.1           2E-4    -0.1555e-4 The following floating-point constants are written incorrectly for the reasons stated.written incorrectly for the reasons stated.

Page 14: Introduction to C Programming Language

                       1                       No decimal point or exponent.                  2,00.8                  Illegal character (,).                      2                        E+10.20 Exponent must be an integer.                      3                        E10 Illegal character (space).  

Example:

Character constants

             A character constant is a single character, enclosed in single quotation marks.

e.g., ‘A’  ‘B’ ‘1’

           Characters are stored internally in computer as coded set of binary digits, which have positive decimal integer equivalents. The value of a character constant is the numeric value of the character in the machine’s character set. This means that the value of a character constant can vary from one machine to the next, depending on the character set being used on the particular machine. For example, on ASCII machine the value of ‘A’ is 65 and on EBCDIC machine it is 193.

Example:

Share on facebook Share on twitter Share on email Share on print More Sharing Services 9

Page 15: Introduction to C Programming Language

String constants

                 A string constant consists of zero or more character enclosed in quotation marks. Several string constants are given below.

       “Welcome to C Programming”                      “ ”

        “a+b\n”                                                          “Error\a\a\a”

                There is a difference between the constant ‘A’ and “A” in C, the first ‘A’ is a character constant while the second “A” is string constant. The notation ‘A’ is a constant occupying a single byte containing the ASCII code of the character A. The notation  “A”  on the other hand ,is a constant that occupies two bytes one for ASCII code of A and another for the null character with the value 0,that terminates all the string.

Example:

Share on facebook Share on twitter Share on email Share on print More Sharing Services 17

Variables

               Variables are means for location in memory used by a program to store data. The size of that block depends upon the range over which the variable is allowed to vary.

For example, on personal computer the size of an integer variable is two bytes, and that of a long integer is four bytes.

A variable region is temporarily remember a number or string value, such as covered by the program. To identify the variables, you have a name unique to every single variable. This is called a variable name. Before using a variable, use variables to what is called a variable declaration that you have to reveal the names and data types that can be stored in the variable variable.

The format for declaring a variable in C.[Storage-class] type data variable name [= initial value];

Storage class and the initial value can be omitted.

The same data type and storage class variable can be declared, separated by commas.[Storage-class] type data variable name [= initial value] variable [= initial value] variable [= initial value];

              In C the size of a variable type such as an integer need not be the same on all types of machines. When we declare a variable we inform the compiler of two things, the name of the variable and the type of the variable. For example, we declare a variable of type character with the name i by writing:

Page 16: Introduction to C Programming Language

char i;

             On seeing the "char" part of this statement the compiler sets aside one bytes of memory to hold the value of the character. It also sets up a symbol table. In that table it adds the symbol i and the relative address in memory where those one byte was set aside. Thus, later if we write: i = 'x'; we expect that,at run time when this statement is executed, the value 'x' will be placed in that memory location reserved for the storage of the value of i.

Following are the rules for naming the variables:

1. All variables must be declared before they can appear in executable statement.2.  A declaration consists of a data type followed by one or more variable names separated by commas.

 Example: int a,b,c;

3. Variables can be distributed among declarations in any fashion. The above declaration can be written as

int a;

int b,c;

4. Integer type variables can be declared to be short integer for smaller integer quantities or long integer for larger integer quantities.

Example:

short int a,b,c;

long int a,b,c;

5. An integer variable can also be declared to be un signed by writing unsigned int.

Example: unsigned int;

Example:

Expressions

              An expression is a sequence of operators and operands that specifies computation of a value. An expression may consist of single entity or some combination of such entities interconnected by one or more operators. All expression represents a logical connection that's either true or false. Thus logical type expression actually represents numerical quantities.

Page 17: Introduction to C Programming Language

              In C every expression evaluates to a value i.e., every expression results in some value of a certain type that can be assigned to a variable. Some examples of expressions are shown in the table given below.

A+b

3.14*r*r

a*a+2*a*b+b*b

Example:

Statements

                The statements of a C program control the flow of program execution.In C language several kinds of statements are available. They are

if statement switch statementgoto statementfor statement while statementdo-while statementbreak statement continue statement expression statementcompound statement return statement null statement

Operators

                  An operator in general, is a symbol that operates on a certain data type. C language is very rich in operators. The commonly used operators include

  1.     Arithmetic operators     2.     Relational operators     3.     Logical operators     4.     Assignment operators     5.     Conditional operators  

Page 18: Introduction to C Programming Language

  6.     Comma operators     7.     Unary operators     8.     Bitwise Operators

Share on facebook Share on twitter Share on email Share on print More Sharing Services 19

scanf

                The usually used input statement is scanf () function.

Syntax of scanf function is                   scanf (“format string”, argument list);

                The format string must be a text enclosed in double quotes. It contains the information for interpreting the entire data for connecting it into internal representation in memory.Example: integer (%d) , float (%f) , character (%c) or string (%s).

                The argument list contains a list of variables each preceded by the address list and separated by comma. The number of argument is not fixed; however corresponding to each argument there should be a format specifier. Inside the format string the number of argument should tally with the number of format specifier.

               Example: if i is an integer and j is a floating point number, to input these two numbers we may use scanf (“%d%f”, &i, &j);

Program:

More Sharing Services

getchar

               getchar function will accept a character from the console or from a file, displays immediately while typing and we need to press Enter key for proceeding.

Syntax of getchar() is                                        int getchar(void);

Page 19: Introduction to C Programming Language

                 It returns the unsigned char that they read.If end-of-file or an error is encountered getchar() functions return EOF.

For example:char a;a= getchar();                   The function "getchar()" reads a single character from the standard input device, the keyboard being assumed because that is the standard input device, and assigns it to the variable "a".

The following program illustrates the use of getchar function.

gets

                 It is used to scan a  line of text from a standard input device. The gets() function will be terminated by a newline character. The newline character won't be included as part of the string. The string may include white space characters.

Syntax :      char *gets(char *s);

                gets() function is declared in the header file stdio.h. It takes a single argument. The argument must be a data item representing a string. On successful completion, gets() shall return a pointer to string s.

The usage of gets() is illustrated in the following program.

Page 20: Introduction to C Programming Language

printf

               The usually used output statement is printf (). It is one of the library functions.

Syntax : printf (“format string”, argument list);

              Format string may be a collection of escape sequence or/and conversion specification or/and string constant. The format string directs the printf function to display the entire text enclosed within the double quotes without any change.

Escape sequence:

                 Escape sequence is a pair of character. The first letter is a slash followed by a character. Escape sequence help us to represent within the format string invisible and non-printed character although there are physically two characters in any escape sequence. It actually represents only one. The various escape sequences are

  Escape sequence     Meaning     \n     New line     \t     Tab     \b     Back space     \a     Bell     \o     Null character     \?     To print question mark     \\     To print slash     \'     To print single quote     \"     To print double quote  

Conversion specification:

                Conversion specification is also a pair of character. it is preceded by  % and followed by a quote which may be a character. The Conversion specification inscribes the printf() function that it could print some value at that location in the text. The Conversion characters supported by C are

  Conversion character     Meaning     %d     Data item is displayed as a signed decimal integer.     %i     Data item is displayed as a single decimal integer.  

Page 21: Introduction to C Programming Language

  %f     Data item is displayed as a floating-point value without an exponent.     %c     Data item is displayed as a single character.     %e     Data item is displayed as a floating-point value with an exponent.  

  %g     Data item is displayed as a floating-point value using either e-type or f-type conversion depending on value.

 

  %o     Data item is displayed as an octal integer, without a leading zero.     %s     Data item is displayed as string.     %u     Data item is displayed as an unsigned decimal integer.     %x     Data item is displayed as a hexadecimal integer, without a leading 0x.  

The following program illustrates the use of puts function.

putchar

putchar function displays a single character on the screen.

prototype:     int  putchar(int c);

The following program illustrates the use of putchar function.

Page 22: Introduction to C Programming Language

puts

                           It is used to display a string on a standard output device. The puts() function automatically inserts a newline character at the end of each string it displays, so each subsequent string displayed with puts() is on its own line. puts() returns non-negative on success, or EOF on failure.

The following program illustrates the use of puts function.

if statements

Page 23: Introduction to C Programming Language

                  If statement is a conditional branching statement. In conditional branching statement a condition is evaluated, if it is evaluate true a group of statement is executed. The simple format of an if statement is as follows:

if (expression)         statement;

                 If the expression is evaluated and found to be true, the single statement following the "if" is executed. If false, the following statement is skipped. Here a compound statement composed of several statements bounded by braces can replace the single statement.

Here's an example program using simple if statement:

if else statement:

                    This feature permits the programmer to write a single comparison, and then execute one of the two statements depending upon whether the test expression is true or false. The general form of the if-else statement is

if(expression)          statement1else          statement2

                    Here also expression in parentheses must evaluate to (a boolean) true or false. Typically you're testing something to see if it's true, and then running a code block(one or more statements) if it is true, and another block of code if it isn't. The statement1 or statement2 can be either simple or compound statement.

The following program demonstrates a legal if else statement:

Page 24: Introduction to C Programming Language

                     You can set up an if-else statement to test for multiple conditions. The following example uses two conditions so that if the first test fails, we want to perform a second test before deciding what to do:

if (x%2==0)        {        printf(“x is an even number”);        } else       {       if (x>10)                 {                 printf(“x is an odd number and greater than 10”);                 }       else                 {                 printf(“x is an odd number and less than 10”);                  }       }

                   This brings up the other if-else construct, the  if, else if, else. This construct is useful where two or more alternatives are available for selection.

The syntax is

if(condition)          statement 1;else if (condition)          statement 2;          .....................          .....................else if(condition)         statement n-1;else          statemens n ;

                The various conditions are evaluated one by one starting from top to bottom, on reaching a condition evaluating to true the statement group associated with it are executed and skip other statements. If none of expression is evaluate to true, then the statement or group of statement associated with the final else is executed.

Page 25: Introduction to C Programming Language

The following program demonstrates a legal if-elseif-else statement:

  c switch statement

              Switch statements simulate the use of multiple if statement.The switch statement is probably the single most syntactically awkward and error-prone feature of the C language. Syntax of c switch statement is

switch(expression)          {          case constant1:                       statements 1;           break;           case constant2:                       statements 2;           break;           …………………..          default:                       statements n;           break;          }

                  When the switch statement is executed, the expression in the switch statement is evaluated and the control is transferred directly to the group of statements whose case label value matches the value of the expression. Each group of statement ends with a break statement. The execution of break statement causes immediate exit from the switch statement. If break statement is not present, then the execution will falls trough all the statement in the selected case.  If none of the case-label value matches the value of expression, then none of the group within the switch statement will be selected and the control is transferred directly to the statement that follows the switch statement c.

                  The expression that forms the argument of switch is evaluated to either char or integer. Similarly the constant expression follows the keyword case should be a value int or char. That is, names of variable can also be used. Switch can test for only equality.

                   Take a look at the following if-else code, and notice how confusing it can be to have nested if tests, even just a few levels deep:

int number = 10;if(number == 1)          {         printf("Given number is 1\n");          }else if((number == 2)

Page 26: Introduction to C Programming Language

        {        printf("Given number is 2\n");         }else if((number ==3)        {        printf("Given number is 3\n");         }else if((number ==4)        {        printf("Given number is 4\n");         }else if((number ==5)       {        printf("Given number is 5\n");         }else         {         if(number<0)                   printf("Given number is negative\n");        else                   printf("Given number is greater than 5\n");         }

Now let's see the same functionality represented in a switch construct:

Page 27: Introduction to C Programming Language

                 It’s illegal to have more than one case label using the same value. For example, the following block of code won't compile because it uses two cases with the same.

int temp = 100;switch(temp)          {         case 10 : printf("10");         break;         case 10 : printf("10"); // won't compile!         break;         case 100 :printf("1000");         break;         default : printf("default");         break;         }

Break and Fall-Through in switch Blocks:

                 When case constants are evaluated from the top to down, and the first case constant that matches the switch's expression is the execution entry point. In other words, once a case constant is matched, C will execute the associated code block, and all subsequent code blocks .

Example:

goto statement

                   The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program unconditionally. In its general form, the goto statement is written as

goto label;

Page 28: Introduction to C Programming Language

                   where the label is an identifier that is used to label the target statement to which the control is transferred. Control may be transferred to anywhere within the current function. The target statement must be labeled, and a colon must follow the label. Thus the target statement will appear as

label:statement;

Each labeled statement within the function must have a unique label, i.e., no two statement can have the same label.

The following program illustrates the use of goto statement.

goto statement

                   The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program unconditionally. In its general form, the goto statement is written as

goto label;

                   where the label is an identifier that is used to label the target statement to which the control is transferred. Control may be transferred to anywhere within the current function. The target statement must be labeled, and a colon must follow the label. Thus the target statement will appear as

label:statement;

Each labeled statement within the function must have a unique label, i.e., no two statement can have the same label.

The following program illustrates the use of goto statement.

Page 29: Introduction to C Programming Language

for loop

                 For loop in C is the most general looping construct. The loop header contains three parts: an initialization, a continuation condition, and step.

Syntax:               for (initialization, condition, step)                        {                        Statement 1;                        Statement 2;                         …………...                        Statement n;                       }

               For statement contain three parts separated by two semicolons. The first part is known as initialization. The variable called loop control variable or index variable is initialized in this part.

              The second part is known as the condition. The condition should be a value one. The condition check can be a compound expression made up of relational expression connected by logical AND, OR.

                 The third part is known as step. It should be an arithmetic expression. The initialization need not be contained to a single variable. If more than one variable is used for initialization they are separated by commas. The step can also applied to more than one variable separated by commas.

               When for statement is encountered at first index variable is get initialized. This process is done only once during the execution of for statement. When condition is evaluated, if it is true the body of the loop will be executed. If more than one statement has to be executed it should end with a pair of braces. The condition of for loop is executed each time at the beginning of the loop. After executing the body of the loop the step is executed, again the condition is executed. If the condition become false it exit from the loop and control transferred to the statement followed by the loop.

The following example executes 10 times by counting 0..9. for (i = 0; i < 10; i++)         ;

The following example illustrates the use of for loop.

Page 30: Introduction to C Programming Language

while loop

              The while statement is also a looping statement. The while loop evaluates the test expression before every loop, so it can execute zero times if the condition is initially false. It has the following syntax.

while (expression)        {        Statement 1;        Statement 2;         …………...        Statement n;       }

               Here the initialization of a loop control variable is generally done before the loop separately. The testing of the condition is done in while by evaluating the expression within the parenthesis. If the evaluation result is true value, the block of statement within calibrates is executed. If the evaluation result is false value the block of statements within the body of loop is skipped and the loop execution get terminated with the control passing to the statement immediately following the while construct. The increment or decrement of the loop control variable is generally done within the body of the loop.

The following example illustrates the use of while loop.

Page 31: Introduction to C Programming Language

Share on facebook Share on twitter Share on email Share on print More Sharing Services 14

do-while loop

              This construct is also used for looping. In this case the loop condition is tested at the end of the body of the loop. Hence the loop is executed al least one. The do-while is an unpopular area of the language, most programmers’ tries to use the straight while if it is possible.

Syntax of do while loop isdo     {     Statement 1;     Statement 2;      …………...     Statement n;    }while(expression);     

                 Here the block of statement following the do is executed without any condition check. After this expression is evaluated and if it is true the block of statement in the body of the loop is executed again. Thus the block of statement is repeatedly executed till the expression is evaluated to false.

                  do-while construct is not used as often as the while loops or for loops in normal case of iteration but there are situation where a loop is to be executed at least one, in such cases this construction is very useful.

The following example illustrates the use of do-while loop.

Page 32: Introduction to C Programming Language

break statement

              The break statement is a jump instruction and can be used inside a switch construct, for loop, while loop and do-while loop. The execution of break statement causes immediate exit from the concern construct and the control is transferred to the statement following the loop. In the loop construct the execution of break statement terminates loop and further execution of the program is reserved with the statement following the body of the loop.

The following program illustrates the use of break statement.

Page 33: Introduction to C Programming Language

continue statement

                  continue statement is a jump statement. The continue statement can be used only inside for loop, while loop and do-while loop. Execution of these statement does not cause an exit from the loop but it suspend the execution of the loop for that iteration and transfer control back to the loop for the next iteration.

The following program illustrates the use of continue statement.

Page 34: Introduction to C Programming Language

Nested loop

                In many cases we may use loop statement inside another looping statement. This type of looping is called nested loop. In nested loop the inner loop is executed first and then outer. The nested loop must be used to input or output multi-dimensional array elements.

The following program illustrates the use of Nested loop.

Arrays

                Array is a data structure, which provides the facility to store a collection of data of same type under single variable name. Just like the ordinary variable, the array should also be declared properly. The declaration of array includes the type of array that is the type of value we are going to store in it, the array name and maximum number of elements.

               The type may be any valid type supported by C. Array names, like other variable names, can contain only letter, digit and underscore characters. Array names cannot begin with a digit character. I.e., The rule for giving the array name is same as the ordinary variable. The size should be an individual constant. To refer to a particular location or element in the array, we specify the name of the array and the index of the particular element in the array. The index specifies the location of the element in the array. The array index starts from zero. The maximum index value will be equal to the size of the array minus one. The array index can be an integer variable for an integer constant.

One dimensional array in c programming language : ID array

                     The declaration form of one-dimensional array is Data_type array_name [size];

                    The following declares an array called ‘numbers’ to hold 5 integers and sets the first and last elements. C arrays are always indexed from 0. So the first integer in ‘numbers’ array is numbers[0] and the last is numbers[4].

int numbers [5];numbers [0] = 1;       // set first elementnumbers [4] = 5;       // set last element

                This array contains 5 elements. Any one of these elements may be referred to by giving the name of the array followed by the position number of the particular element in square brackets ([]). The first element in every array is the zeroth element.Thus, the first element of array ‘numbers’is referred to as numbers[ 0 ], the second element of array ‘numbers’is referred to as numbers[ 1 ], the fifth element of array ‘numbers’is referred to as numbers[ 4 ], and, in general, the n-th element of array ‘numbers’is referred to as numbers[ n - 1 ].

Example:

Page 35: Introduction to C Programming Language

                  It's a very common error to try to refer to non-existent numbers[ 5], element. C does not do much hand holding. It is invariably up to the programmer to make sure that programs are free from errors. This is especially true with arrays. C does not complain if you try to write to elements of an array which do not exist!

For example: If you wrote: numbers[ 5 ], = 6;                   C would happily try to write 6 at the location which would have corresponded to the sixth element, had it been declared that way. Unfortunately this would probably be memory taken up by some other variable or perhaps even by the operating system. The result would be either:

The value in the incorrect memory location would be corrupted with unpredictable consequences. The value would corrupt the memory and crash the program completely!

                      The second of these tends to be the result on operating systems with proper memory protection. Writing over the bounds of an array is a common source of error. Remember that the array limits run from zero to the size of the array minus one.

Out of bounds access

I would be doing well, that really shows the range of valid indices, please check often. 10 When the number of elements, all the indices of 10 or more is illegal. Also, whether any size of negative indices is also illegal.

These errors are detected at compile time is not. It is an error at run time. However, there is no guarantee that the error reliably. Sometimes works correctly (seems to be moving.) This is the "luck ran" instead of "bad luck worked" so, please, as no doubt.

                   The best way to see these principles is by use of an example, so load the program  and display it on your monitor.

#include <stdio.h>#include <conio.h> int main( )       {       char name[7]; /* define a string of characters */

Page 36: Introduction to C Programming Language

       name[0] = 'A';       name[1] = 's';       name[2] = 'h';       name[3] = 'r';       name[4] = 'a';       name[5] = 'f';       name[6] = '\0'; /* Null character - end of text */       name[7] = ‘X’;        clrscr();       printf("My name is %s\n",name);       printf("First letter is %c\n",name[0]);       printf("Fifth letter is %c\n",name[4]);       printf("Sixth letter is %c\n",name[5]);       printf("Seventh letter is %c\n",name[6]);       printf("Eight letter is %c\n",name[7]);        getch();       return 0;      }

                 The elements of an array can also be initialized in the array declaration by following the declaration with an equal sign and a comma-separated list (enclosed in braces) of initializers.

                The following program initializes an integer array with five values and prints the array.

#include <stdio.h>#include <conio.h> int main()     {     int numbers[]={1,2,3,4,5};     int i;     clrscr();     printf("Array elements are\n");     for(i=0;i<=4;i++)              printf("%d\n",numbers[i]);     getch();     return 0;    }

                    If there are fewer initializers than elements in the array, the remaining elements are initialized to zero. For example, the elements of the array n could have been initialized to zero with the declaration int n[ 10 ] = { 0 };which explicitly initializes the first element to zero and initializes the remaining nine elements to zero because there are fewer initializers than there are elements in the array. It is important to remember that arrays are not automatically initialized to zero. The programmer must at least initialize the first element to zero for the remaining elements to be automatically zeroed. This method of initializing the array elements to 0 is performed at compile time for static arrays and at run time for automatic arrays.

There are more complex uses of arrays, which I will address later along with pointers.

2 dimensional array

                      Two-dimensional array are those type of array, which has finite number of rows and finite number of columns. The declaration form of 2-dimensional array is

Data_type    Array_name [row size][column size];

                     The type may be any valid type supported by C. The rule for giving the array name is same as the ordinary variable. The row size and column size should be an individual constant.

                      The following declares a two-dimensional 3 by 3 array of integers and sets the first and last elements to be 10.int matrix [3][3];matrix[0][0] = 10;matrix[2][2] = 10;

Page 37: Introduction to C Programming Language

                    The following Figure illustrates a two dimensional array, matrix. The array contains three rows and tree columns, so it is said to be a 3-by-3 array. In general, an array with m rows and n columns is called an m-by-n array.

  [0] [1] [2]

[0] 10    

[1]      

[2]     10

                      Every element in array matrix is identified by an element name of the form matrix[ i ][ j ]; matrix is the name of the array, and i and j are the subscripts that uniquely identify each element in matrix . Notice that the names of the elements in the first row all have a first subscript of 0; the names of the elements in the third column all have a second subscript of 2.

                  In the case of Two-dimensional array, during declaration the maximum number of rows and maximum number of column should be specified for processing all array elements.       

                    The implementation of the array stores all the elements in a single contiguous block of memory. The other possible implementation would be a combination of several distinct one-dimensional arrays. That’s not how C does it. In memory, the array is arranged with the elements of the rightmost index next to each other. In other words, matrix[1][1] comes right before matrix[1][2] in memory.

The following array:

  [0] [1] [2]

[0] 1 2 3

[1] 4 5 6

[2] 7 8 9

would be stored:

1 2 3 4 5 6 7 8 9

Example:

Page 38: Introduction to C Programming Language

Three dimensional array in c programming

The declaration form of Three-dimensional array is

Data_type     Array_name [size1][size2][size3];

Example:

Page 39: Introduction to C Programming Language

String

                        A string in C is actually a character array. As an individual character variable can store only one character, we need an array of characters to store strings. Thus, in C string is stored in an array of characters. Each character in a string occupies one location in an array. The null character ‘\0’ is put after the last character. This is done so that program can tell when the end of the string has been reached. For example, the string ”I Like C Programming” is stored as follows.

I   L i k e   C   P r o g r a m m i n g \o

Since the string has 20 characters (including space), it requires an arrayof at least, size 21 to store it.

                       Thus, in C, a string is a one-dimensional array of characters terminated a null character. The terminating null character is important. In fact, a string not terminated by ‘\0’ is not really a string, but merely a collection of characters.

Page 40: Introduction to C Programming Language

                      A string may contain any character, including special control characters, such as \n, \t, \\ etc...

                      There is an important distinction between a string and a single character in C. The convention is that single characters are enclosed by single quotes e.g. '*' and have the type char. Strings, on the hand, are enclosed by double quotes e.g. "name" and have the type "pointer to char" (char *) or array of char.

                      Strings can be declared in two main ways; one of these is as an array of characters, the other is as a pointer to some pre-assigned array. Perhaps the simplest way of seeing how C stores arrays is to give an extreme example which would probably never be used in practice.

#include<stdio.h>int main ()       {        char string[];       string[0] = 'C';       string[1] = 'P';       string[2] = 'r';       string[3] = 'o';       string[4] = 'g';       string[5] = 'r';       string[6] = 'a';       string[7] = 'm';       string[8] = 'm';       string[9] = 'i';       string[10]= 'n';       string[11] = 'g';       printf ("%s", string);       return 0;      }

                          This method of handling strings is perfectly acceptable, if there is time to waste, but it is so laborious that C provides a special initialization service for strings, which bypasses the need to assign every single character with a new assignment!.

The other way is use a pointer to some pre-assigned array.

#include<stdio.h>int main ()      {      char str1[]=”I Like”;      char *str2=”C Programming”;       puts(str1);      puts(str2);      return 0; }

String

                        A string in C is actually a character array. As an individual character variable can store only one character, we need an array of characters to store strings. Thus, in C string is stored in an array of characters. Each character in a string occupies one location in an array. The null character ‘\0’ is put after the last character. This is done so that program can tell when the end of the string has been reached. For example, the string ”I Like C Programming” is stored as follows.

I   L i k e   C   P r o g r a m m i n g \o

Since the string has 20 characters (including space), it requires an arrayof at least, size 21 to store it.

                       Thus, in C, a string is a one-dimensional array of characters terminated a null character. The terminating null character is important. In fact, a string not terminated by ‘\0’ is not really a string, but merely a collection of characters.

                      A string may contain any character, including special control characters, such as \n, \t, \\ etc...

Page 41: Introduction to C Programming Language

                      There is an important distinction between a string and a single character in C. The convention is that single characters are enclosed by single quotes e.g. '*' and have the type char. Strings, on the hand, are enclosed by double quotes e.g. "name" and have the type "pointer to char" (char *) or array of char.

                      Strings can be declared in two main ways; one of these is as an array of characters, the other is as a pointer to some pre-assigned array. Perhaps the simplest way of seeing how C stores arrays is to give an extreme example which would probably never be used in practice.

#include<stdio.h>int main ()       {        char string[];       string[0] = 'C';       string[1] = 'P';       string[2] = 'r';       string[3] = 'o';       string[4] = 'g';       string[5] = 'r';       string[6] = 'a';       string[7] = 'm';       string[8] = 'm';       string[9] = 'i';       string[10]= 'n';       string[11] = 'g';       printf ("%s", string);       return 0;      }

                          This method of handling strings is perfectly acceptable, if there is time to waste, but it is so laborious that C provides a special initialization service for strings, which bypasses the need to assign every single character with a new assignment!.

The other way is use a pointer to some pre-assigned array.

#include<stdio.h>int main () { char str1[]=”I Like”; char *str2=”C Programming”; puts(str1); puts(str2); return 0; }

Share on facebook Share on twitter Share on email Share on print More Sharing Services 7

strlen()

Syntax: #include < string.h>size_t strlen( char *str );

strlen(char *str) returns the length of the null terminated string pointed to by str. The null terminator is not counted.

This function will return number of characters in the string provided as parameter to this function. For example if we are providing "The world" as the string it will return 9. That means it will take the blank spaces in between the words in the string into count. But the null terminator is not counted. It will aslo take special characters like @,#,$,% etc into count.

consider this example str[30]="www.cprogrammingexpert.com";

Page 42: Introduction to C Programming Language

It is stored like

str[0] <- 'w'str[1] <- 'w'str[2] <- 'w'str[3] <- '.'str[4] <- 'c'str[5] <- 'p'str[6] <- 'r'str[7] <- 'o'str[8] <- 'g'str[9] <- 'r'str[10] <-'a' str[11] <-'m' str[12] <-'m' str[13] <-'i' str[14] <-'n' str[15] <-'g' str[16] <- 'e' str[17] <- 'x'str[18] <- 'p'str[19] <- 'e'str[20] <- 'r'str[21] <- 't'str[22] <- '.'str[23] <- 'c'str[24] <- 'o'str[25] <- 'm'str[26] <- '\0'str[27] <- 'garbage value'str[28] <- 'garbage value'str[29] <- 'garbage value'

Here strlen(str) equals 26. null terminator is not counted.

Example:

string function : strlwr()

Syntax: char * strlwr(char *str)

Page 43: Introduction to C Programming Language

strlwr(str) coverts str to all lowercase.

This function will convert all the uppercase characters in the string, which is provided as parameter, into lowercase. It does not take care whether it is the starting letter or not. It will convert every uppercase to lowercase.

For example

#include<stdio.h>#include<conio.h>int main(){ char str[30]="www.CProgrammingExpert.com"; clrscr(); printf("\n\nstr : %s\n\n",str); printf("strlwr(str) : %s\n",strlwr(str)); getch(); return 0;}

here we declares the string str like this str[30]="www.CProgrammingExpert.com"; The string str is a character array of size 30.The character is stored like this

str[0] <- 'w'str[1] <- 'w'str[2] <- 'w'str[3] <- '.'str[4] <- 'C'str[5] <- 'P'str[6] <- 'r'str[7] <- 'o'str[8] <- 'g'str[9] <- 'r'str[10] <-'a' str[11] <-'m' str[12] <-'m' str[13] <-'i' str[14] <-'n' str[15] <-'g' str[16] <- 'E' str[17] <- 'x'str[18] <- 'p'str[19] <- 'e'str[20] <- 'r'str[21] <- 't'str[22] <- '.'str[23] <- 'c'str[24] <- 'o'str[25] <- 'm'str[26] <- '\0'str[27] <- 'garbage value'str[28] <- 'garbage value'str[29] <- 'garbage value'

when we use the function strlwr(str) it will convert all characters stored in the character array str to lowercase.Then stored like this

str[0] <- 'w'str[1] <- 'w'str[2] <- 'w'str[3] <- '.'str[4] <- 'c'str[5] <- 'p'str[6] <- 'r'str[7] <- 'o'str[8] <- 'g'str[9] <- 'r'

Page 44: Introduction to C Programming Language

str[10] <-'a' str[11] <-'m' str[12] <-'m' str[13] <-'i' str[14] <-'n' str[15] <-'g' str[16] <- 'e' str[17] <- 'x'str[18] <- 'p'str[19] <- 'e'str[20] <- 'r'str[21] <- 't'str[22] <- '.'str[23] <- 'c'str[24] <- 'o'str[25] <- 'm'str[26] <- '\0'str[27] <- 'garbage value'str[28] <- 'garbage value'str[29] <- 'garbage value'

so after using the function strlwr(str) the value of string str is"www.cprogrammingexpert.com"

Example:

string function : strupr()

Syntax: char * strupr(char *str);

strupr(str) coverts str to all uppercase. It returns a pointer to the original input string str.

This function will convert all the lowercase characters in the string, which is provided as parameter, into uppercase. It will convert every lowercase to uppercase.

For example

#include<stdio.h>#include<conio.h>int main(){ char str[30]="www.CProgrammingExpert.com"; clrscr();

Page 45: Introduction to C Programming Language

printf("str : %s\n",str); printf("strupr(str) : %s\n",strupr(str)); getch(); return 0;}

here we declares the string str like this str[30]="www.CProgrammingExpert.com"; The string string str is a character array of size 30.The character is stored like this

str[0] <- 'w'str[1] <- 'w'str[2] <- 'w'str[3] <- '.'str[4] <- 'C'str[5] <- 'P'str[6] <- 'r'str[7] <- 'o'str[8] <- 'g'str[9] <- 'r'str[10] <-'a' str[11] <-'m' str[12] <-'m' str[13] <-'i' str[14] <-'n' str[15] <-'g' str[16] <- 'E' str[17] <- 'x'str[18] <- 'p'str[19] <- 'e'str[20] <- 'r'str[21] <- 't'str[22] <- '.'str[23] <- 'c'str[24] <- 'o'str[25] <- 'm'str[26] <- '\0'str[27] <- 'garbage value'str[28] <- 'garbage value'str[29] <- 'garbage value'

whe we use the function strupr(str) it will convert all characters stored in the character array str to uppercase.Then stored like this

str[0] <- 'W'str[1] <- 'W'str[2] <- 'W'str[3] <- '.'str[4] <- 'C'str[5] <- 'P'str[6] <- 'R'str[7] <- 'O'str[8] <- 'G'str[9] <- 'R'str[10] <-'A' str[11] <-'M' str[12] <-'M' str[13] <-'I' str[14] <-'N' str[15] <-'G' str[16] <- 'E' str[17] <- 'X'str[18] <- 'P'str[19] <- 'E'str[20] <- 'R'str[21] <- 'T'str[22] <- '.'str[23] <- 'C'str[24] <- 'O'str[25] <- 'M'str[26] <- '\0'str[27] <- 'garbage value'

Page 46: Introduction to C Programming Language

str[28] <- 'garbage value'str[29] <- 'garbage value'

so after using the function strupr(str) the value of string str is"WWW.CPROGRAMMINGEXPERT.COM"

Example:

strcat()

Syntax: #include<string.h>char *strcat( char *str1, const char *str2 );

                    strcat(str1,str2) concatenates a copy of the string pointed to by str2 to the the string pointed to by str1 and terminates str1 with a null. The first character of str2 overwrites the null terminator originally ending sr1. The str2 is untouched by the operation.In this function we will pass two arguments str1,str2 as parameters.

For example, Consider this program

#include<stdio.h>#include<conio.h>int main(){ char str1[30]="www.cprogramming"; char str2[15]="expert.com"; clrscr(); printf("%d\t%d\nn",strlen(str1),strlen(str2)); printf("\n\nstrcat(str1,str2) : %s\n\n",strcat(str1,str2)); printf("\n\nstr1 : %s\t\tstr2 : %s\n\n",str1,str2); getch(); return 0;}

Herestr1[30]= www.cprogramming and str2[15]=expert.com if we are using function as strcat(str1,str2) and print the output. It will be www.cprogrammingexpert.com.i.e the last character in the first parameter get erased and second parameter concatenated in memory str1 is stored like this "www.cprogramming\0" and str2 like this "expert.com\0" after concatenation str1 is "www.cprogrammingexpert.com\0" and str2 is"expert.com\0".So make sure that the size of str1 is large enough to accomodate all the characters in str1 and str2.

Page 47: Introduction to C Programming Language

str1[0] <- 'w'str1[1] <- 'w'str1[2] <- 'w'str1[3] <- '.'str1[4] <- 'c'str1[5] <- 'p'str1[6] <- 'r'str1[7] <- 'o'str1[8] <- 'g'str1[9] <- 'r'str1[10] <-'a' str1[11] <-'m' str1[12] <-'m' str1[13] <-'i' str1[14] <-'n' str1[15] <-'g' str1[16] <- '\0' str1[17] <- 'garbage value'str1[18] <- 'garbage value'str1[19] <- 'garbage value'str1[20] <- 'garbage value'str1[21] <- 'garbage value'str1[22] <- 'garbage value'str1[23] <- 'garbage value'str1[24] <- 'garbage value'str1[25] <- 'garbage value'str1[26] <- 'garbage value'str1[27] <- 'garbage value'str1[28] <- 'garbage value'str1[29] <- 'garbage value'

str2 is

str2[0] <- 'e'str2[1] <- 'x'str2[2] <- 'p'str2[3] <- 'e'str2[4] <- 'r'str2[5] <- 't'str2[6] <- '.'str2[7] <- 'c'str2[8] <- 'o'str2[9] <- 'm'str2[10] <- '\0' str2[11] <- 'garbage value'str2[12] <- 'garbage value'str2[13] <- 'garbage value'str2[14] <- 'garbage value'

After concatenation

str1[0] <- 'w'str1[1] <- 'w'str1[2] <- 'w'str1[3] <- '.'str1[4] <- 'c'str1[5] <- 'p'str1[6] <- 'r'str1[7] <- 'o'str1[8] <- 'g'str1[9] <- 'r'str1[10] <-'a' str1[11] <-'m' str1[12] <-'m' str1[13] <-'i' str1[14] <-'n' str1[15] <-'g' str1[16] <- 'e' str1[17] <- 'x'str1[18] <- 'p'str1[19] <- 'e'

Page 48: Introduction to C Programming Language

str1[20] <- 'r'str1[21] <- 't'str1[22] <- '.'str1[23] <- 'c'str1[24] <- 'o'str1[25] <- 'm'str1[26] <- '\0'str1[27] <- 'garbage value'str1[28] <- 'garbage value'str1[29] <- 'garbage value'

In this example I have declared size of str1 equal to 30 and str2 equal to 15.

Now you may think why I have declared str1 as 30 and str2 as 15. It's just because I want you to undestand the concepts .OK

So if you know exact size of the string declare that size to save memory. Here str1[27] is enough, str2[11] is enough.

One more thing , what will happen if you are declaring the string like char *str1,*str2 , here no garbage values will come. Before concatenation size of str1 is 16 & str2 is 10 and a fter concatenation size of str1 is 26 & str2 is 10. so we Saved memory.

Example:

 

strncat()

Syntax: #include<string.h>char *strncat( char *str1, const char *str2,size_t count  );

                    strncat(str1,str2,n) concatenates not more than n characters  of the string pointed to by str2 to the the string pointed to by str1 and terminates str1 with a null. The first character of str2 overwrites the null terminator originally ending sr1. The str2 is untouched by the operation.

Example:

Page 49: Introduction to C Programming Language

Share on facebook Share on twitter Share on email Share on print More Sharing Services 8

strcpy()

Syntax: #include<string.h>char *strcpy( char *to, const char *from );

                    strcpy(str1,str2) copies the string pointed to by str2 to the string pointed to by str1 and terminates str1 with a null. The str2 must be a pointer to a null terminated string.

Example:

Share on facebook Share on twitter Share on email Share on print More Sharing Services 6

strncpy()

Syntax:

Page 50: Introduction to C Programming Language

#include<string.h>char *strncpy( char *to, const char *from,size_t count );

                    strncpy(str1,str2,n) copies up to n characters from the string pointed to by str2 to the string pointed to by str1 and terminates str1 with a null. The str2 must be a pointer to a null terminated string.

Example:

Hi, There is a small mistake in this program. Do you know ? Here is the currect value of str1- "experProgramming".Sorry!!

strcmp()

Syntax: #include<string.h>int strcmp( char *str1, char *str2 );

                   strcmp(str1,str2) compares str1 and str2 lexicographically .Returns a negative value if str1<str2; 0 if str1 and str2 are identical; and positive value if str1>str2.

Example -1:

 

Example-2:

Page 52: Introduction to C Programming Language

#include<string.h>int strcmpi( char *str1, char *str2 );

                   strcmpi(str1,str2) compares str1 and str2 lexicographically without regards to case .Returns a negative value if str1<str2; 0 if str1 and str2 are identical; and positive value if str1>str2.

Example:

strncmp()

Syntax: #include<string.h>int strncmp( char *str1, char *str2,int n );

                   strncmp(str1,str2,n) compares atmost n charactes of str2 to str1 lexicographically .Returns a negative value if str1<str2; 0 if str1 and str2 are identical; and positive value if str1>str2.

Example:

Page 53: Introduction to C Programming Language

Share on facebook Share on twitter Share on email Share on print More Sharing Services 6

stricmp()

Syntax: #include<string.h>int stricmp( char *str1, char *str2 );

                   stricmp(str1,str2) compares str1 and str2 lexicographically without regards to case .Returns a negative value if str1<str2; 0 if str1 and str2 are identical; and positive value if str1>str2.

Example:

Page 54: Introduction to C Programming Language

strncmpi()

Syntax: #include<string.h>int strncmpi( char *str1, char *str2 ,int n);

                   strncmpi(str1,str2,n) compares at most n characters of str2 to str1,lexicographically,by ignoring case. Returns a negative value if str1<str2; 0 if str1 and str2 are identical; and positive value if str1>str2.

Example:

Page 55: Introduction to C Programming Language

strchr()

Syntax: #include<string.h>char *strchr( const char *str, int ch );

                    strchr(str,ch)  finds ch in str. Returns a pointer to the first occurrence of the character ch in str, if ch does not occur in str ,strchr returns NULL.           

Example:

Page 56: Introduction to C Programming Language

strnicmp()

Syntax: #include<string.h>int strnicmp( char *str1, char *str2 ,int n);

                   strnicmp(str1,str2,n) compares at most n characters of str2 to str1,lexicographically,by ignoring case. Returns a negative value if str1<str2; 0 if str1 and str2 are identical; and positive value if str1>str2.

Example:

Page 57: Introduction to C Programming Language

Share on facebook Share on twitter Share on email Share on print More Sharing Services 3

strstr()

Syntax: #include<string.h>char *strstr( const char *str1, const char *str2 );

                  strstr(str1,str2)  finds the first occurrence of substring str2 in str1.Returns a pointer to the elements in str1 that contain str2, or NULL if str2 does not occur in str1.

Example:

Page 58: Introduction to C Programming Language

More Sharing Services

strset()

It is one of many string functions available. For using string functions we need to include string library.In this function we pass 2 parameters namely a string and a character. When this function is called it will replace all the characters in the string by the specified character. While counting it will take blank spaces also.

Syntax of strset function is #include<string.h>char *strset( const char *str,char ch );

                  strset(str,ch) set all character in str to ch. quits when the first null character is found. Returns a pointer to str.

Example:

Page 59: Introduction to C Programming Language

strnset()

Syntax: #include<string.h>char *strnset( const char *str,char ch ,int n);

                 strnset(str,ch,n) set the first n character of str to ch. quits when the first null character is found. Returns a pointer to str.

Example:

Share on facebook Share on twitter Share on email Share on print More Sharing Services 3

Page 60: Introduction to C Programming Language

strrev()

Syntax: #include<string.h>char *str( char *str);

                  strrev(str) reverses all characters in str(except for the terminating null ). Returns a pointer to the reversed string.

Example:

Functions

                  A number of statements grouped into a single logical unit are called a function. The use of function makes programming easier since repeated statements can be grouped into functions. Splitting the program into separate function make the program more readable and maintainable.

                  It is necessary to have a single function ‘main’ in every C program, along with other functions used/defined by the programmer.

                 A function definition has two principal components: the function header and body of the function. The function header is the data type of return value followed by function name and (optionally) a set of arguments separated by commas and enclosed in parenthesis. Associated type to which function accepts precedes each argument. In general terms function header statement can be written as

return_type  function_name (type1 arg1,type2 arg2,..,typen argn)

                where return_type represents the data type of the item that is returned by the function, function_name represents the name of the function, and type1,type2,…,typen represents the data type of the arguments arg1,arg2,..,argn.

Example: Following function returns the sum of two integers.int add(int p,int q)       {      return p+q;          //Body of the function      }

                 Here p and q are arguments. The arguments are called formal arguments or formal parameters, because they represent the name of the data item that is transferred into the function from the calling portion of the program. The corresponding arguments in the function call are called actual arguments or actual parameters, since they define the data items that are actually transferred.

Page 61: Introduction to C Programming Language

                    A function can be invoked whenever it is needed. It can be accessed by specifying its name followed by a list of arguments enclosed in parenthesis and separated by commas. e.g., add(5,10);

The following condition must be satisfied for function call.

The number of arguments in the function calls and function declaration must be same. The prototype of each of the argument in the function call should be same as the corresponding parameter in the function declaration

statement.

For example, the following program makes use of function that determine the sum of two integer quantities.

                 The line of the function contains the function name, ‘add’ followed by formal arguments p and q, enclosed in parenthesis. The formal arguments p and q represents the data item that are transferred to the function from the calling portion of the program (i.e., add (a, b)). In addition, the formal arguments p and q are preceded by the data type int. i.e., it only accepts integers. When we execute this program the content of the variables a and b are copied to the formal arguments p and q respectively and the function returns the sum of p and q and is assigned to the variable c in the left side of the calling function.

                   A function may or may not return a value. A ‘return’ statement returns some value to the calling function and it may be assigned to the variable in the left side of the calling function. The return value can be a constant, variable, a user defined data structure, a general expression, a pointer to function, or a function call. The return statement also causes the program logic to return to the point from which the function was accessed. In general term the return statement is written as

return expression;

                  If a function does not return a value, the return type in the function definition and declaration is specified as void. The declaration for a prototype for a function that receive any arguments from the calling function and does not return any value will have the format                                                void function_name (void);

The above program can be rewrite as

#include <stdio.h>#include <conio.h> int add(int p,int q);                       // function prototypevoid display(int p, int q, int r); // function prototype

Page 62: Introduction to C Programming Language

int main()        {        int a,b,c;        clrscr();        printf("Enter two numbers\n");        scanf("%d%d",&a,&b);        c=add(a,b);         display(a,b,c);         getch();        return 0;       }

int add(int p,int q)          //This function returns sum of a and b.        {        return(p+q);        }void display(int p, int q, int r). //This function returns nothing        {        printf("Sum of %d and %d is %d",p,q,r);        }

Pass by value

                Arguments can be passed to a function by two methods, They are

1. pass by value 2. pass by reference

                 Function in C passes all arguments by value. When a single value is passed to a function via an actual argument, the value of the actual argument is copied into the function. Therefore, the value of the corresponding formal argument can be altered within the function, but the value of the actual argument within the calling routine will not change. This procedure for passing the value of an argument to a function is known as passing by value.

Example:

Pass by Reference

Page 63: Introduction to C Programming Language

                When passing by reference technique is used, the address of the data item is passed to the called function. Using & operator we can determine the address of the data item. Note that function once receives a data item by reference, it acts on data item and the changes made to the data item also reflects on the calling function. Here you don't need to return anything to calling function.

Example:

Recursion

             Recursive functions are those functions, which call itself within that function. A recursive function must have the following type of statements.

A statement to test and determine whether the function is calling itself again. A statement that calls the function itself and must be argument.

A conditional statement (if-else)

A return statement.

Example: Factorial of a number

Page 64: Introduction to C Programming Language

             This is the most famous program on recursion. Many versions of this program are available. All programs differ only in checking conditions. I prefer to write like the following one.

static storage class

               A variable is declared to be static by prefixing its normal declaration with the keyword static, as in                static int a;since the property of a variable may be stated in any order we could also use                 int static a;

Static variables can be declared within a function. These variables retain their values from the previous call. i.e., the value that they had before returning from the function. This is illustrated in the following example.

Page 65: Introduction to C Programming Language

register storage class

Physical storage space can be a variable that is the main storage. With access to the registers in the CPU is faster than main memory, a register variable to register the specified variable is the physical storage space of variables. However, they require that as much as possible to ensure the register, the register guarantee is not necessarily secure.               Register variables are stored in the register of the microprocessor. The number of variable which can be declared register are limited. This means that the variable has a maximum size equal to the register size. If more variables are declared as register variable, they are treated as auto variables. A program that uses register variables executes faster as compared to similar program without register variable.To declare a variable register storage class register specified.register int n;

Example for register variables :

Page 66: Introduction to C Programming Language

Automatic storage class or variables

                 Automatic variables are allocated space in the variable on the stack. To declare a variable automatic storage class auto specified.

eg:    auto int n;

When you declare a variable, if the omitted variable storage class is automatic.eg:    int n;

When you declare an automatic variable initialization to be made explicit initial value is undefined.

The scope of an automatic variable is only for the block, or any block within the block, in which it appears. All variables declared within a function are auto by default. A variable can be defined as automatic by placing the keyword auto at the beginning of the variable declaration.

Example:   auto int a;            

Take a look at the following example:

Page 67: Introduction to C Programming Language

External Storage class or Global variable

                 External variables are global to the file in which they are defined. External variables are used only when all functions needed a particular variable. It retains the assigned value within the scope. In the following program variable  i is an external variable.

Page 68: Introduction to C Programming Language

Structure

                      A structure is a user defined data type. We know that arrays can be used to represent a group of data items that belong to the same type, such as int or float. However we cannot use an array if we want to represent a collection of data items of different types using a single name. A structure is a convenient tool for handling a group of logically related data items.

The syntax of structure declaration is struct structure_name         {         type element 1;         type element 2;         ……………..         type element n;         };

                       In structure declaration the keyword struct appears first, this followed by structure name. The member of structure should be enclosed between a pair of braces and it defines one by one each ending with a semicolon. It can also be array of structure. There is an enclosing brace at the end of declaration and it end with a semicolon.

We can declare structure variables as follows                          struct structure_name var1,var2,…..,var n;

For Example:                           To store the names, roll number and total mark of a student you can declare 3 variables. To store this data for more than one student 3 separate arrays may be declared. Another choice is to make a structure. No memory is allocated when a structure is declared. It just defines the “form” of the structure. When a variable is made then memory is allocated. This is equivalent to saying that there's no memory for “int” , but when we declare an integer that is. int var; only then memory is allocated. The structure for the above-mentioned case will look like

Page 69: Introduction to C Programming Language

struct student           {           int rollno;           char name[25];           float totalmark;           };

We can now declare structure variables stud1, stud2 as follows                            struct student stud1,stud2;Thus, the stud1 and stud2 are structure variables of type student. The above structure can hold information of 2 students.

                            It is possible to combine the declaration of structure combination with that of the structure variables, as shown below.struct structure_name          {          type element 1;          type element 2;           ……………..          type element n;          }var1,var2,…,varn;

                               The following single declaration is equivalent to the two declaration presented in the previous example.struct student           {           int rollno;           char name[25];           float totalmark;           } stud1, stud2;

                                The different variable types stored in a structure are called its members. The structure member can be accessed by using a dot (.) operator, so the dot operator is known as structure member operator.

Example:                                In the above example stud1 is a structure variable of type student. To access the member name, we would write                                  stud1.nameSimilarly, stud1’s rollno and stud1’s totalmark can be accessed by writing                                 stud1.rollno                  And                                stud1.totalmark

Initializing Structure Members

Structure members can be initialized at declaration. This much the same manner as the element of an array; the initial value must appear in the order in which they will be assigned to their corresponding structure members,enclosed in braces and seperated by commas .The general form is

struct stucture_name  var={val1,val2,val3…..};

Example:#include  <stdio.h>#include<conio.h> int main()      {      struct student                {                char *name;                int rollno;                float totalmark;               };      struct student stud1={"Ashraf",1,98};      struct student stud3= {"Rahul",3,97};      struct student stud2={"Vineeth",2,99};      clrscr();      printf("STUDENTS DETAILS:\nRoll number:%d\n\nName:%s\n\nTotel mark:%.2f\n",stud1.rollno,stud1.name,stud1.totalmark);      printf("\nRoll number:%d\n\nName:%s\n\nTotel mark:%.2f\n",stud2.rollno,stud2.name,stud2.totalmark);      printf("\nRoll number:%d\n\nName:%s\n\nTotel mark:%.2f\n",stud3.rollno,stud3.name,stud3.totalmark);     getch();

Page 70: Introduction to C Programming Language

     return 0;     }

Array of structures:

                     It is possible to store a structure has an array element. i.e., an array in which each element is a structure. Just as arrays of any basic type of variable are allowed, so are arrays of a given type of structure. Although a structure contains many different types, the compiler never gets to know this information because it is hidden away inside a sealed structure capsule, so it can believe that all the elements in the array have the same type, even though that type is itself made up of lots of different types.

The declaration statement is given below.struct struct_name       {       type element 1;       type element 2;       ……………..       type element n;       }array name[size];

Example:struct student       {       int rollno;       char name[25];       float totalmark;       } stud[100];

                          In this declaration stud is a 100-element array of structures. Hence, each element of stud is a separate structure of type student. An array of structure can be assigned initial values just as any other array. So the above structure can hold information of 100 students.

program:

#include  <stdio.h>#include  <conio.h>int main()      {      struct student               {               int rollno;               char name[25];               int totalmark;               }stud[100];      int n,i;      clrscr();      printf("Enter total number of students\n\n");      scanf("%d",&n);      for(i=0;i<n;i++)                {                printf("Enter details of %d-th student\n",i+1);                printf("Name:\n");                scanf("%s",&stud[i].name);                printf("Roll number:\n");                scanf("%d",&stud[i].rollno);                printf("Total mark:\n");                scanf("%d",&stud[i].totalmark);                }     printf("STUDENTS DETAILS:\n");     for(i=0;i<n;i++)               {               printf("\nRoll number:%d\n",stud[i].rollno);               printf("Name:%s\n",stud[i].name);               printf("Totel mark:%d\n",stud[i].totalmark);              }    getch();    return 0;    }

Page 71: Introduction to C Programming Language

Structure as structure member:

                              A structure can have one or more of its member as another structure, but a structure cannot be member to itself when a structure is used as structure member. In such situation, the declaration of the embedded structure must appear before the declaration of the outer structure. For example

#include  <stdio.h>#include  <conio.h>int main()       {       struct dob                {                int day;                int month;                int year;                };       struct student                {                struct dob d;                int rollno;                char name[25];                int totalmark;                }stud[25];       int n,i;       clrscr();       printf("Enter total number of students\n\n");       scanf("%d",&n);       for(i=0;i<n;i++)                {                printf("\nEnter details of %d-th student\n\n",i+1);               printf("\nName:\n");               scanf("%s",&stud[i].name);               printf("\nRoll number:\n");               scanf("%d",&stud[i].rollno);               printf("\nTotal mark:\n");               scanf("%d",&stud[i].totalmark);               printf("\nDate of birth (Format:01 06 2010):\n");               scanf("%d%d%d",&stud[i].d.day,&stud[i].d.month,&stud[i].d.year);               }        printf("STUDENTS DETAILS:\n");       for(i=0;i<n;i++)               {               printf("\n\nRoll number:%d\n\n",stud[i].rollno);               printf("Name:%s\n\n",stud[i].name);               printf("Totel mark:%d\n\n",stud[i].totalmark);               printf("Date of birth:%d / %d / %d \n\n",stud[i].d.day,stud[i].d.month,stud[i].d.year);               }     getch();     return 0; }

Union

                    Union is a data type with two or more member similar to structure but in this case all the members share a common memory location. The size of the union corresponds to the length of the largest member. Since the member share a common location they have the same starting address.

                    The real purpose of unions is to prevent memory fragmentation by arranging for a standard size for data in the memory. By having a standard data size we can guarantee that any hole left when dynamically allocated memory is freed will always be reusable by another instance of the same type of union. This is a natural strategy in system programming where many instances of different kinds of variables with a related purpose and stored dynamically.

                          A union is declared in the same way as a structure.The syntax of union declaration is union union_name         {          type element 1;          type element 2;

Page 72: Introduction to C Programming Language

          ……………..          type element n;         };     This declares a type template. Variables are then declared as:                            union union_name x,y,z;

                             For example, the following code declares a union data type called Student and a union variable called stud:union student             {              int rollno;              float totalmark;             };union student stud;

                              It is possible to combine the declaration of union combination with that of the union variables, as shown below.union union_name           {           type element 1;           type element 2;           ……………..           type element n;           }var1,var2,…,varn;       

                               The following single declaration is equivalent to the two declaration presented in the previous example.union student          {            int rollno;            float totalmark;          }x,y,z;

Exercise: Compare structure and Union

Structure:

Page 73: Introduction to C Programming Language

Union:

Page 74: Introduction to C Programming Language

Pointers

                           Pointer is a variable that represents the location of a data item, such as variable or an array element. Within the computer’s memory, every stored data item occupies one or more contiguous memory cells. The number of memory cells required to store a data item depends on the type of the data item. For example, a single character will typically be stored in one byte of memory; an integer usually requires two contiguous bytes, a floating-point number usually requires four contiguous bytes, and a double precision usually requires eight contiguous bytes.

                          Suppose v is a variable that represents some particular data item. The compiler will automatically assign memory cells to this data item. The data item can then be accessed if we know the address of the first memory cell. The address of v’s memory location can be determined by the expression &v, where & is the unary operator, called the address operator, that evaluates the address of its operand.

                          Now let us assign the address of v to another variable pv. Thus pv = &v; This new variable is called pointer to v. since it “points to” the location where v is stored in address, not its value. Thus pv is referred to as a pointer variable. The relationship between pv and v is illustrated in the following figure.

Address of V-----------> Value of V

                          The data item represented by v. (i.e. the data item stored in v’s memory cells) can be accessed by the expression *pv where * is a unary operator called the indication operator, that operates only on a pointer variable. Therefore, *pv and v both represent the same data item.

                          The address operator (&) and indirection operator(*) are unary operators and they are the members of the same precedence group as the other unary operators. The address operator (&) must act upon operands that associated with unique address, such as ordinary variable or single array element. Thus the address operators cannot act upon arithmetic expressions. The indirection operator can only act upon operands that are pointers (e.g., pointer variables).

Page 75: Introduction to C Programming Language

Pointer declaration:

                            Pointer variables, like all other variables, must be declared before, they may be used in C program. When a pointer variable is declared, the variable name must be preceded by an asterisk(*). This identifies the fact that the variable is a pointer. The data type that appears in the declaration refers to the object of the pointer. i.e. the data item that is stored in the address represented by the pointer, rather than the pointer itself. Thus a pointer declaration may be written in general terms as :

Data-type *ptr;

Where ptr is the name of the pointer variable, and data-type refers to the data type of the pointer object.

For example, a C program contains the following declarations.int i,*ptri;float f,*ptrf;

                            The first line declares i to be an integer type variable and ptri to be a pointer variable whose object is an integer quantity. The second line declares f to be a floating-point type variable and ptrf to be a pointer variable whose object is a floating point quantity.

                            Within a variable declaration, a pointer variable can be initialized by assigning in the address of another variable, remember that the variable whose address is assigned to the pointer variable must have been declared earlier in the program, for example,

int i;int *ptri=&i;

                            The first line declares i to be integer type variable and the second line declares ptri to be a pointer variable whose object is an integer point quantity. In addition, the address of i is initially assigned to ptri.

The following program illustrates the use of pointer variable.

Page 76: Introduction to C Programming Language

Operation possible with pointers

                            C language allows arithmetic operations performed on pointer variables. The arithmetic operations available for use with pointer can be classified as

Unary operator: ++ (increment) and -- Binary operator; +(addition) and –(subtraction)

                          The size of pointer variable depends on the data type of the variable pointed to by the pointer.

Example:

                         If the pointer to an integer is incremented using the ++ operator, then the address contained in the pointer is incremented by two and not one, assuming that an integer occupies two bytes in memory. Similarly if the pointer points to a floating point variable the use of ++ operator increments the address by four. In general a pointer to some data type   d_type when incremented by an integer value i then the result will have the following value.

The following program illustrates this.

Page 77: Introduction to C Programming Language

I think you have already studied functions, now let's see how it works with pointers.

malloc()

             The malloc()  function dynamically allocates memory when required. This function allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error.span>

Format is as follows. void * malloc (size_t size);

Specifies in bytes the size of the area you want to reserve the argument. It returns the address as the return value of the dynamically allocated area. In addition, returns NULL if it fails to secure the area. The failure to ensure that the situation is usually that is out of memory.

The return type is of type void *, also receive the address of any type. The fact is used as follows.

double * p = (double *) malloc (sizeof (double));

The size of the area using the sizeof operator like this. The return value is of type void *, variable in the receiving side can be the pointer of any type in the host language C language called C + +, the pointer type to other type void * is, without casting, so can not be assigned, Use a cast. In C, a pointer type to void * type from another, so that the cast automatically, there is no need to explicitly cast originally.Of course, should not write because not explicitly given as well as portability to C + +, I wrote better.

In addition, the secured area is unknown at this point that's on it? That is the same as a normal state to declare a local variable. Thus, with reference values ??must not be left without initialization.

            With this feature, you get a pointer to an allocated block of memory. Its structure is:

code:

pointer = (type) malloc (size in bytes);

An example:

code:

int * p;p = (int *) malloc (sizeof (int));* p = 5;

Page 78: Introduction to C Programming Language

First we declare a pointer, which is still pointing nowhere. Then the pointer, not the content but the pointer itself is equal to a pointer type int that contains the memory address space for an int. Sizeof () gets the space it occupies what you want, if you put int in, such as 2 bytes, because we have assigned two bytes. This feature also serves to get the size of pointers, variables, or whatever it takes.Finally, now that the pointer is contained, we give a value.

For example:               int *ptr = malloc(sizeof(int) * 10);      // allocates 10 ints!

                 If it is unable to find the requested amount of memory, malloc() function returns NULL. So you should really check the result for errors:

int *ptr = malloc(sizeof(int) * 5000); if (ptr == NULL)       {       printf(" Out of memory!\n");       exit(1);       }

                 There are only two ways to get allocated memory back. They are exit from the program and calling free() to free function. If your program runs a while and keeps malloc()ing and never free()ing when it should, it is said to “leak” memory. Make sure to avoid memory leaks! free() that memory when you are done with it!

The following example illustrates the use of malloc() function.

Page 79: Introduction to C Programming Language

Standard C Library Functions in c programming language

The C, C + + has many features, when using the standard library functions, increasing the portability of programs.

Standard functions are divided into groups, all functions that belong together are declared in the header file (the one that says xxx.h), the letter "h" for header in English and is called heading.

To include any function belonging to these headers should write lines of code as shown as an example:

# Include

I designed this table to study the function libraries are obviously I've found in my books and systems.

LIBRARIES AND USE DESCRIPTIONS

Library Name

Description

assert.h Is to provide a definition of the assert macro, which prints an error message and aborts the program

Page 80: Introduction to C Programming Language

alloc.h There are functions to allocate, free memory, or obtain information from the memory blocks.

ctype.hThe functions that allow us to know the nature of a character, or to convert uppercase to lowercase and vice versa and integer values to ASCII codes.

dir.h This lets you sort, create, modify, move and delete directories

errno.hRepresent the numbers of error, an error occurs then you can query the value of the system varianble deerrno for more information about this error.

float.h Define the limits of the floating-point types

limits.h Define the boundaries of different types of integers

math.h Contains the standard math functions used in C and C + +

setjmp.h Defines the type of jmp_buf for some functions.

signal.h Contains state functions.

stdarg.h Defines functions that can be called with different numbers of arguments, so that they can write f (a) f (a, b).

stdef.h Define some special types

stdio.h Incorporate functions - Out E / S standard, types and macros

stlib.h Declare functions that are useful for different purposes, especially searching and sorting.

string.h This file contains functions for handling strings.

time.h Contains functions related to dates and times

Features Found in the Libraries

#Function Name

Type Library to which it belongs

Syntax Description Example

1 abs(i) int stdlib.h int abs(int i);Returns the absolute value of i

x = abs(-7) // x es 7

2 acos(d) double math.h double acos(double d);Returns the arc cosine of d

angle = acos (0.5) / / returned is phi angle / 3

3 asin(d) double math.h double asin(double d); Returns the arc sine of d angle = asin (0.707) / / about phi / 4

4 atan(d) double math.h double atan(double d); Returns the arc tangent of angle atan (1.0) / / angle is phi / 4

Page 81: Introduction to C Programming Language

long double tanl(long double d);

d. Calculates the arc tangent of x. Requires library called complex.h

5 atan(d1, d2) double math.hdouble atan(double d1, double d2);

Returns the arc tangent of d1/d2

angle = atan (y, x)

6 atof(s) double stdlib.hdouble atof(const char *cadena)

Convert string s to a double precision number. Requires llamda math.h library

double x, char * cad_dbl = "200.85" ... x = atof (cad_dbl) / / convert the string "200.85" a real value

7 atoi(s) int stdlib.h int atoi(const char *cadena)

Convert string s to an integer. The string must have the following format: [blank] [sign] [ddd] (still mandatory decimal digits).

nt i, char * cad_ent = "123" ... i = atoi (cad_ent) / / converts the string "123" to integer 123

8 atol(s) long stdlib.hlong atol(const char *cadena);

Convert string s to a long integer. The string must have the following format: [blank] [sign] [ddd] (still mandatory decimal digits).

long int i; char cad_ent = "9876543", ... i = atol (cad_ent) / / convert the string "9876543" to long integer

9 calloc(n, s) void(puntero)

malloc.h y stdlib.h o bien alloc.h y stdlib.h

void *calloc(size_t n, size_t s);

Allocate memory for a formation of n elements, each of s bytes. Returns a pointer to the beginning of the reserved space. If enough space exists for the new block or we is 0, calloc returns null.

long * buffer buffer = (long *) calloc (40, sizeof (long));

10 ceil(d) double math.h double ceil(double d);Returns a value rounded up to the next higher integer

rounding = ceil (5.1) / / rounding is 6

11 cos(d) double math.hdouble cos(double d); complex cos(complex d);

Returns the cosine of d coseno_x = cos (1.6543)

12 cosh(d) double math.hdouble cos(double d); complex cos(complex d);

Returns the hyperbolic cosine of d

d = 1.00; printf ("d =% f \ n \ n, d);

13difftime(11, 12)

double time.hdouble difftime(time_t hora2, time_t hora1)

Returns the time difference 11 (TIME2) - 12 (hour1), where 11 and 12 represent the time elapsed after a time base (see function time)

time_t start, end; clrscrl (); start = time (NULL); delay (5000) end = time (NULL) print ("Difference in seconds:% f \ n", difftime (start, end));

14 exit(u) void stdlib.h void exit(int estado) Close all files and buffers and the program ends.

exit(0);

Page 82: Introduction to C Programming Language

The value of u is assigned by the function to indicate the completion status.

15 exp(d) double math.hdouble exp(double d); complex exp(complex d)

Raise e to the power d ( e = 2.7182818 ... is the base of natural logarithms system (neperian))

d = 100.00, y = exp (d) printf ("The exponential x =% f. \ n \ n", y);

16 fabs(d) double math.h double fabs(double d);Returns the absolute value of d

y = fabs (-7.25) / / and is worth 7.25

17 fclose(f) int stdio.h int fclose(FILE *f);Close the file f. Returns 0 if the file was closed successfully.

int fclose (FILE "file");

18 feof(f) int stdio.h int feof(FILE *f);

Determines whether an end of file found. if so, returns a nonzero value, otherwise returns 0

feof (chips);

19 fgetc(f) int stdio.h int fgetc(FILE f); Read character from file f c + fgetc (fp)

20 fegts(s, i, f) char(puntero) stdio.hchar *fgets(char s, int s, FILE *f);

Reads a string s with characters i, f File

fgets (caddemo, 80, fp);

21 floor(d) double math.h double floor(double d);Returns a value rounded down to nearest integer less

x = floor (6.25) / / x is 6

22 fmod(d1, d2) double math.hdouble fmod(double d1, double d2);

Returns the remainder of d1/d2 (with the same sign as d1)

rest = fmod (5.0,2.0) / / rest equal to 1.0

23 fopen(s1, s2) file(puntero) stdio.h FILE *fopen(const char *s1, const char *s2)

Opens a file named s1, s2 type. Returns a pointer to the file. *

Way Action

"R"Open for reading

"W"Opens an empty file for writing

"A"Opens for writing at end of file

"R+" Open for reading /

if ((corriente2 = fopen ("data", "W +"))== NULL printf ("File not opened ... \ n");

Page 83: Introduction to C Programming Language

writing

"W+"Opens an empty file for read / write

"A+"Open for reading and add

"Rb"Open a binary file for reading.

"Wb"Open a binary file for writing

"Ab"Open a binary file to add

"Rb+"Open a binary file for read / write.

"Wb+"Open a binary file for read / write

"Ab+"

Open or create binary file for read / write

24 fprintf(f, ...) int stdio.hint fprintf(FILE *f, const char *formato [,arg,...]);

Escribe datos en el archivo f (el resto de los argumentos

fprintf(f1, "El resultado es %f\n",result);

25 fputc(c, f) int stdio.h int fputc(int c, FILE *f);Escribe un caracter en el archivo f

fputc(*(p++), stdout);

26 fputs(s, f) int stdio.hint fputs(const char *cad, FILE *f)

Escribe una cadena de caracteres en el archivo f

fputs("esto es una prueba", f1);

27fread(s, i1, i2, f)

int stdio.hsize_t fread(void *b, size_t t, size_t n, FILE *f);

Lee i2 elementos, cada uno de tamano i1 bytes, desde el archivo f hasta la cadena s

fread(buf, strlen(msg)+1, 1, flujo);

28 free(p) void malloc.h o void free(void Libera un bloque de memoria reservada cuyo

char *cad; // asignar memoria a la cadena

Page 84: Introduction to C Programming Language

stdlib.h *dir_memoria);principio esta indicado por p.

cad=(char *)malloc(50); ... free(cad); // liberar memoria

29 fscanf(f, ...) int math.hint fscanf(FILE *f, const char *formato, [, direccion,... ]);

Lee datos del archivo f ( el resto de los argumentos

fscanf(flujo, %s%f, cad, &f);

30 fseek(f, l, i) int stdio.hint fseek(FILE *f, long desplaza, int origen);

Mueve el puntero al archivo f una distancia de 1 bytes desde la posicion i (i puede representar el principio del archivo, la posicion actual del puntero o el fin del archivo. Notas

Origen Significado

SEEK_SETPrincipio de archivo

SEEK_CUR Posicion actual puntero

SEEK_END Final del archivo

fseek(f1,OL,SEEK_SET); // ir al principio

31 ftell(f) long int stdio.h long int ftell(FILE *f);Devuelve la posicion actual del puntero dentro del archivo f

ftell(fichen)

32fwrite(s, i1, i2, f)

int stdio.hsize_t fwrite(const void *p, size_t i1, size_t i2, FILE *f);

Escribe i2 elementos, cada uno de tamano 1 bytes, desde la cadena s hasta el archivo f

num=fwrite(lista,sizeof(char),25,flujo);

33 getc(f) int stdio.h int getc(FILE *f);Lee un caracter del archivo f

while(c=getc(fx) !=EOF { print ("%c",c); }

34 getchar( ) int stdio.h int getchar(void);Lee un caracter desde el dispostivo de entrada estandar

int c; while((*c=getchar()) != '\n') print ("%c",c);

35 gets(s) char(puntero) stdio.h char *gets(char *cad);

Lee una cadena de caracteres desde el dispositivo de entrada estandar

gets(nombre);

36 isalnum(c) int ctype.h int isalnum(int c); Determina si el argumento es

carac=getch(); if (isalnum(carac))

Page 85: Introduction to C Programming Language

alfanumerico. Devuelve un valor disitinto de cero si es cierto; en otro caso devuelve 0

print("%c letra|digito \n",carac); else printf("%c no letra|digito \n", carac);

37 isalpha(c) int ctype.h int isalpha(int c);

Determina si el argumento es alfabetico. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0.

int c; if (isalpha(c)) printf("%c es letra\n",c);

38 isascii(c) int ctype.h int isascii(int c);

Determina si el argumento es un caracter ASCII. Devuelve un valor disitinto de cero si es cierto; en otro caso devuelve 0

int c; if (isascii(c)) printf('%c es un ascii\n",c)

39 iscntrl(c) int ctype.h int isacntrl(int c);

Determina si el argumento es un caracter ASCII de control. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0

if(iscntrl(c)) printf"%c es un caracter de control\n",c);

40 isdigit(c) int ctype.h int isdigit(int c);

Determina si el numero es un digito decimal. Devuelve un valor disitinto de cero si es cierto; en otro caso devuelve 0

if(isdigit(c)) printf"%c es un digito\n",c);

41 isgraph(c) int ctype.h int isgraph(int c);

Determina si el argumento es un caracter ASCII grafico (hex 0x21 -0x7e; octal 041 -176). Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0

if(isgraph(c)) printf"%c es un caracter imprimible(no espacio)\n",c);

42 islower(c) int ctype.h int islower(int c);

Determina si el argumento es ua minuscula. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0

if(islower(c)) printf"%c es una letra minuscula\n",c);

43 isodigit(c) int ctype.h int isodigit(int c);

Determina si el argumento es un digito octal. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0

if(isodigit(c)) printf"%c es un digito octal\n",c);

44 isprint(c) int ctype.h int isprintint c); Determina si el el if(isprint(c)) printf("\n"c imprimible\n",c);

Page 86: Introduction to C Programming Language

argumento es un caracter ASCII imprimible (hex 0x20 -0x7e; octal 040 -176). Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0

45 ispunct(c) int ctype.h int ispunct(int c);

Determina si el argumento es un caracter de puntuacion. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0

if(ispunct(c)) printf"%c es un caracter de puntuacion\n",c);

46 isspace(c) int ctype.h int isspace(int c);

Determina si el argumento es un espacio en blanco. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0

if(isspace(c)) printf"%c es un espacio\n",c);

47 isupper(c) int ctype.h int isupper(int c);

Determina si el argumento es una mayuscula. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0

if(isupper(c)) printf"%c es una mayuscula\n",c);

48 isxdigit(c) int ctype.h int isxdigit(int c);

Determina si el argumento es un digito hexadecimal. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0

ifisxdigit(c)) print"%c es un digito hexadecimal\n",c)

49 labs(l) long int math.h long int labs(long int l);Devuelve el calor absoluto de 1

long lx=-51654,ly; ly=labs(lx);

50 log(d) double math.h double log(double d);Devuelve el logaritmo natural de d

hdouble x,y; x=10; y=log(x);

51 log10(d) double math.h double log10(double d);Devuelve el logaritmno (en base 10) de d

hdouble x,y; x=10; y=log10(x);

52 malloc(u) void(puntero) stdlib.h void *malloc(size_t u);

Reserva u bytes de memoria. devuelve un puntero al principio del espacio reservado

cadena=malloc(MAX_CHR);

53 pow(d1, d2) double math.h double pow(double d1, Devuelve d1 elevado a la double x=2.0, y=4.0, z;

Page 87: Introduction to C Programming Language

double d2); potencia d2 z=pow(x,y); //z sera 1.60

54 printf(...) int stdio.hint printf(const char *formato[,argumento,...]);

Escribe datos en dispositivo de salida estandar.

Codigo Formato

%c Caracter

%dEntero Decimal

%e

Real (double o float), notacion cientifica.

%fComa flotante

%sCadena de caracteres

%xHexadecimal sin signo

print("producto %d y %d es %d\n",x,y,x*y);

55 putc(c, f) int stdio.h int putc(int c, FILE *f);Escribe un caracter en el archivo f

putc('*',demo);

56 putchar(c) int stdio.h int putchar(int c);Escribe un caracter en el dispositivo de salida estandar

putchar('B');

57 puts(s) int stdio.h int puts(const char *cad)

Escribe una cadena de caracteres en el dispositivo de salida estandar

puts("Desea continuar (s/n);

58 rand( ) int stdlib.h int rand(void);Devuelve un entero positivo aleatorio

// visualizar 10 numeros aleatorios

for (i=0;i<10;i++) printf("%6d\",rand());

59 rewind(f) void stdio.h void rewind(FILE *f);Mueve el puntero al principio del archivo f

rewind(fx);

60 scanf(...) int stdio.h int scanf(const char *formato {,direccion,...]);

Lee datos en dispositivo de entrada estandar

Codigo Formato

%c Caracter

scanf('%d %f %c %s, &i, &fp, &c, s);

Page 88: Introduction to C Programming Language

%dEnetero Decimal

%x Hexadecimal

%iEntero Decimal

%f Numero Real

%o Octal

%p Puntero

%s Cadena

61 sin(d) double math.h double sin(double d); Devuelve el seno de d

double x, y; x=0.52; printf('x =%f radianes\n",x); y=cos(x); printf("el coseno de x =%f\n",y);

62 sinh(d) double math.h double sinh(double d);Devuelve el seno hiperbolico de d

y=sinh(x);

63 sqrt(d) double math.h double sqrt(double d);Devuelve la raiz cuadrada de d

printf("%lf",sqrt(25.0); //se visualiza 5

64 srand(u) void stdlib.h void srand(unsigned u);Inicializa el generador de numeros aleatorios

srand(semilla);

65strcmp(s1, s2)

int string.hint strcmp(const char*s1, const char *s2);

Compara dos cadenas de caracteres lexicograficamente. Devuelve un valor negativo si s1 < s2; 0 si s1 y s2 son identicas; y un valor positivo si s1 > s2

i=strcmp("MNP", "mnp"); // resultado < 0

i=strcmp("abc", "abc"); // resultado = 0 i=strcmp("xy", "abc"); // resultado > 0

char s1[80]="Mayo"; char s2[80]="Octubre"; int j; j=strcmp(s1,s2);

66strcmpi(s1, s2)

int string.hint strcmpi(const char*s1, const char *s2);

Compara dos cadenas de caracteres lexicograficamente, sin diferenciar mayusculas de minusculas. Devuelve un valor negativo si s1 < s2; 0 si s1 y s2 son identicas; y un valor positivo si s1 > s2

v=strcmpi(s1,s2);

67 strcpy(s1, s2) char string.h char *strcpy(char s1, const Copia la cadena de

Page 89: Introduction to C Programming Language

char s2);caracteres s2 en la cadena s1

char *s1="Pepe Luis"; char b[12]; strcpy(s2,s1); cout <<s2<< '\n';

68 strlen(s) int string.h size_t strlen(const char *s);Devuelve el numero de caracteres de una cadena

longitud=strlen(nombre); char s[81]="Cadena demo'; printf("La longitud de s es: %d\n" strlen(s));

69 strset(c, s) char(puntero) string.hchar *strset(char *cad, int c);

Pone todos los caracteres de s a c (excluyendo el caracter nulo del final \0)

char *cad="----"; strset (cad,'x'); // cad es ahora xxxx

70 system(s) int string.h system(comd);

Pasa la orden al sistema operativo. Devuelve cero si la orden se ejecuta correctamente; en otro caso devuelve un valor distinto de cero, tipicamente -1.

system(dir);

71 tan(d) double math.h double tan(double d); Devuelve la tangente de d y=tan(x);

72 tanh(d) double math.h double tanh(double d);Devuelve la tangente hiperbolica de d

a=tanh(x);

73 time(p) long int time.h time_t time(time_t *h);

Devuelve el numero de segundos transcurridos despues de un tiempo base designado

time(&hora);

74 toascii int ctype.h int toascii(int c);Convierte el valor del argumento a ASCII

c=toascii(entero);

75 tolower intctype.h o stdlib.h

int tolower(int c);Convierte una letra a minuscula

c=tolower('s'); //c se convierte en 's'

76 toupper intctype.h o stdlib.h

int toupper(int c);Convierte una letra a mayuscula

c=toupper('s'); //c se convierte en 'S'

C Preprocessor

                      Preprocessor directives are actually the instructions to the compiler itself. They are not translated but are operated directly by the compiler. Note that preprocessor statements begin with a #symbol, and are NOT terminated by a semicolon. Traditionally, preprocessor statements are listed at the beginning of the source file.They are also termed as macros.

The most common preprocessor directives are include directive define directive

1.include directive:

Page 90: Introduction to C Programming Language

                     The include directive is used to include files like as we include header files in the beginning of the program using #include directive like#include<stdio.h>#include<conio.h>

2.define directive:

                      It is used to assign names to different constants or statements which are to be used repeatedly in a program. These defined values or statement can be used by main or in the user defined functions as well. They are used fora. defining a constant b. defining a statementc. defining a mathematical expression

For example#define PI 3.141593#define TRUE 1#define floatingpointno float

Let us take a look at an example to understand how to use preprocessors in C Programming.


Recommended