LEARN
C PROGRAMMING
STEP BY STEP
-Gopal Raha
Many people are really interested in learning and implementing C programs on their favorite platforms like DOS/Windows or Linux. If you are the one looking for a step-by-step guide to get started, this tutorial is for you.
LEARN
C PROGRAMMING
STEP BY STEP
Dedicated to
My Dad,Mom and Gore Sir,
Who inspire me to write this book.
Preface
What is a programming language?--Human beings need language to communicate between them. Similarly to communicate with computers we need a programming language. All the events in life can be communicated to computers with the help of programming language. C is the basic of all programming language. Before the introduction of C we had only Machine level languages. C is just like any other communication Language.
If you learn C programming thoroughly you can easily learn other programming languages. To learn C we just need to know the syntax of C program only. i.e order in which we have to write the contents.This book is intended to introduce C programming to beginning programmers. Over several years of studying, I have noted a large number of students appear to have difficulty in grasping the fundamentals of C Language. So I am trying to explain them with the help of simple examples.
This book will help you get a quick start with C programming. This book is a guide for the beginners and also for those who have little knowledge on C Programming fundamentals.
There are different types of programming languages such as Structure oriented, Object oriented etc. C is the most commonly used Structure oriented programming language. Compiler for some languages are developed using C only. With the help of this tutorial I am trying to explain all the basics of C.In order to successfully complete this tutorial, you won't need any prior knowledge of the C programming language. First of all I will start with the most basic concepts and take you up to the highest level of C programming including the usually intimidating concepts of structures, union,file, pointers and dynamic memory allocation,etc.
Once you have mastered C, you will find Object Oriented Language such as c++,java, etc are easy to learn.
So let's start our Journey...
-AUTHOR
Contents
1. Introduction 5 2. Turbo C++ IDE 6 3. A Basic C Program 8 4. Fundamentals 12 5. Input/Output Functions 37 6. Control Statements 44 7. Arrays 58 8. Strings 65 9. Functions 92 10. Storage Classes 98 11. Structure 102 12. Union 107 13. Pointers 11014. Dynamic memory allocation 114
15. File 126
16. Graphics 138
17. The C Preprocessor 183
18. Standard Library Functions 185
19. Examples 187
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
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.
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 program All 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.
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 ; }
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. 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, like
int 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.
Fundamentals
1. 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; The following are illegal (it's your job to recognize why): float :e;
float 9PI; float .3.14; float 7g; Example :
2. Keywords
Keywords are standard identifiers that have standard predefined meaning in C. Keywords are all lowercase, since uppercase and lowercase characters are not equivalent it's possible to utilize an uppercase keyword as an identifier but it's not a good programming practice.
Points to remember
1. Keywords can be used only for their intended purpose. 2. Keywords can't be used as programmer defined identifier. 3. The keywords can't be used as names for variables. The standard keywords are given below:
3. 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:
character integer
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 qualifiers 2. 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.
4. 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:
5. 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:
6. 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:
7. 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:
8. 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.
9. 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:
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 :
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).
10. 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.
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).
11. 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.
12. 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.
13. 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:
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 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;
14. 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. 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:
15. 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 statement goto statement for statement while statement do-while statement break statement continue statement expression statement compound statement return statement null statement
16. Symbolic constant in c Language
A symbolic constant is name that substitute for a sequence of character that cannot be changed. The character may represent a numeric constant, a character constant, or a string. When the program is compiled, each occurrence of a symbolic constant is replaced by its corresponding character sequence. They are usually defined at the beginning of the
program. The symbolic constants may then appear later in the program in place of the numeric constants, character constants, etc., that the symbolic constants represent.
For example
, a C program consists of the following symbolic constant definitions. #define PI 3.141593
#define TRUE 1 #define FALSE 0
#define PI 3.141593 defines a symbolic constant PI whose value is 3.141593. When the program is preprocessed, all occurrences of the symbolic constant PI are replaced with the replacement text 3.141593.
Note that the preprocessor statements begin with a #symbol, and are not end with a semicolon. By convention, preprocessor constants are written in UPPERCASE.
Example: 1
#include<stdio.h> #include<conio.h> #define TRUE 1 #define PI 3.141593 void main() { float a; float b; float c; float d=PI; clrscr(); if(TRUE) { a=100; b=a*10; c=b-a; } printf("\na=%f\nb=%f\nc=%f\nPI=%f",a,b,c,d); getch(); }Example: 2
17. 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 6. Comma operators 7. Unary operators 8. Bitwise Operators
18. Comments
Comments are added to make a program more readable to you but the compiler must ignore the comments. Everything that is inside /* and */ is considered a comment and will be ignored by the compiler. You must not include comments within other comments, so something like this is not allowed: [*].
/* this is a /* comment */ inside a comment, which is wrong! */
Input/Output Function
1. 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:
2. 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);
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".
3. 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.
4. 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
%d Data item is displayed as a signed decimal integer. %i Data item is displayed as a single decimal integer. %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.
5. putchar
putchar function displays a single character on the screen. prototype: int putchar(int c);
6. 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.
Control Statement
1. if statements
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) statement1
else
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:
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.
2. 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) { 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:
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 .
3. 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.
4. 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++)
;
5. 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.
6. 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 is do { 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.
7. 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.
8. 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.
9. 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.
1. 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 element numbers [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 ].
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 */ 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.
2. Two 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;
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.
[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:
3. Three dimensional array in c
programming
The declaration form of Three-dimensional array is Data_type Array_name [size1][size2][size3]; Example:
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...
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; }
1. 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";
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.
2. string function : strlwr()
Syntax:
char * strlwr(char *str)
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' 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"
3. 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(); 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' str[28] <- 'garbage value' str[29] <- 'garbage value'
so after using the function strupr(str) the value of string str is"WWW.CPROGRAMMINGEXPERT.COM"
4. 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; } Here
str1[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. 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'