Prepared by Mr. K. G. Page 1 Unit-1
Elements of C Language
1.1 Algorithm: In order to write computer programs without any logical error, it is recommended programmers prepare a rough writing showing the steps involved in the program. This is called algorithm.
An algorithm presents step-by-step instructions required to solve any problem. These steps can be shown diagrammatically using a flowchart.
Example:
1. Read a, b 2. Sum ← a + b 3. Product ← a × b 4. Print sum, product 5. Stop
Characteristics of Algorithm:
Finiteness: Finiteness implies that algorithm may have finite number of steps also the time taken to execute all the steps of the algorithm should be finite.
Definiteness: Each step of the algorithm is precisely defined, i.e. the actions to be carried out should be specified unambiguously.
Effectiveness: All the operations used in the algorithm are basic (division, multiplication, comparison etc) and can be performed exactly in a ‘fixed duration of time’.
Input: The term input means supplying initial data for algorithm. These data must be present before any operations can be performs. Generally the initial data is supplied by a READ instruction or a variable can be give initial values using SET.
Output: The term output refers to the result obtained when all the steps of algorithm have been performed. An algorithm must have atleast one output.
Advantages of Algorithm:
It is simple to understand step by step by step solution of the problem. It is easy to debug i.e. errors can be easily pointed out.
It is independent of programming languages.
It is compatible to computers in the sense that each step of algorithm can be easily coded into the equivalent in high level language.
1.2 Flowchart: Flowchart is a symbolic or diagrammatic representation of an algorithm. It uses several geometrical figures to represent the operations, and arrows to show the direction of flow. The flowcharts are read from left to right and top to bottom. Following are the commonly used symbols in the flowcharts.
Symbol Operation Meaning
Start/ Stop Represents the beginning and the end of the flowchart.
Input/ Output Represents the values to be given by the user and the results to be displayed.
Prepared by Mr. K. G. Page 2 Check/ decision
making Represents the logical checking to decide the flow sequence. Looping Represents the looping which is repeated based on a condition/
value of a variable.
Connector Represents the continuity of the flowchart in other place/ page. Arrows Represents direction of flow.
Example:
Flowcharting Rules:
1. First consider the main logic, and then incorporate the details. 2. Maintain a consistent level of detail for a given flowchart. 3. Do not include all details in a flowchart.
4. Words in the flowchart symbols should be common statement and easy to understand. Use meaningful descriptions in the flowchart symbols.
5. Be consistent in using names and variables in the flowchart. 6. Go from left to right and top to bottom in constructing flowcharts.
7. Keep the flowchart as simple as possible. The crossing of flow lines should be avoided as for as practicable.
8. If a new flowcharting page is needed it is recommended that the flowchart be broken at an input or output point. Moreover properly labeled connectors should be used to link the portions of the flowchart on different pages.
Advantages of Flowcharts 1. Better Communication 2. Effective Analysis 3. Effective Synthesis
4. Proper Program Documentation 5. Efficient Coding
6. Systematic Debugging 7. Systematic Testing
Prepared by Mr. K. G. Page 3 1.3 History of C: C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were taken from the earlier language B and B's earlier ancestors BCPL and CPL. CPL (Combined Programming Language) was developed with the purpose of creating a language that was capable of both high level machine independent programming and would still allow the programmer to control the behavior of individual bits of information. The one major drawback of CPL was that it was too large for use in many applications.
In 1967, BCPL (Basic CPL) was created as a scaled down version of CPL while still retaining its basic features. In 1970, Ken Thompson, while working at Bell Labs, took this process further by developing the B language. B was a scaled down version of BCPL written specifically for use in systems programming.
Finally in 1972, a co-worker of Ken Thompson, Dennis Ritchie, returned some of the generality found in BCPL to the B language in the process of developing the language we now know as C.
C's power and flexibility soon became apparent. Because of this, the UNIX operating system which was originally written in assembly language was almost immediately re-written in C (only the assembly language code needed to "bootstrap" the C code was kept).
During the rest of the 1970's, C spread throughout many colleges and universities because of its close ties to UNIX and the availability of C compilers. Soon, many different organizations began using their own versions of C causing compatibility problems.
In response to this in 1983, the American National Standards Institute (ANSI) formed a committee to establish a standard definition of C which became known as ANSI Standard C. Today C is in widespread use with a rich standard library of functions.
Why C is called as C language?
Because it is developed after the B language. The B language has been developed also in Bell Labs by Key Thompson. The C itself is improvement on the B language.
Why C is called Middle Level Language: C Programming language is called as Middle Level Language because
1. It gives or behaves as High Level Language through Functions - gives a modular programming and breakup, increased efficiency for reusability
2. It gives access to the low level memory through Pointers. Moreover it does support the Low Level programming i.e. Assembly Language.
As it is a combination of these two aspects, it is neither a High Level nor a Low level language but a Middle Level Language.
1.4 Advantages of C Language
C is a building block for many other currently known languages. Take a look at Python for example a fully Object-Oriented High-Level programming language. It is written in C (perhaps C++ too). That tells you if you ever want to know what is going on under the hood in other languages; understanding C and how it works is essential.
A lot of libraries are written in C and it's easy to find reference code, and to get support. The main advantage of C language is that there is not much vocabulary to learn, and that the
programmer can arrange for the program is very fast. C programming language is very easier to learn. C programming language is still a practical and compact language. It comprises a good semantic. Syntax is of C is clear also.
Prepared by Mr. K. G. Page 4 C language is very near to assembly programming i.e. the hard use of pointers for example is
a very powerful mechanism.
C has features that allow the programmer to organize programs in a clear, easy, logical way. For example, C allows meaningful names for variables without any loss of efficiency, yet it gives a complete freedom of programming style, including flexible ways of making decisions, and a set of flexible commands for performing tasks repetitively (for, while, do).
C is a portable language. 1.5 Disadvantages of C Language
C does not have OOPS feature that's why C++ is developed. If you know any other modern programming language then you already know its disadvantages.
There is no runtime checking in C language.
There is no strict type checking (for ex: we can pass an integer value for the floating data type).
C doesn't have the concept of namespace.
C doesn't have the concept of constructors and destructors. As the program extends it is very difficult to fix the bugs.
1.6 Library Functions: The C language has a wide range of library functions. A function is a self-contained program segment that carries out some specific task to carry out various commonly used operations or calculations. The other names of library functions are standard functions, built-in-functions or pre-defined built-in-functions, as they are not written (define) by the user or programmer, during development of the program.
Example: Suppose we want to calculate the square root of 9 in mathematics we will write
√9 gives 3
but in C programming, it will carried out by using library function sqrt() as follows:
sqrt(9) gives 3
1.7 Header Files: To use the library functions successfully, it is necessary to include certain specific information (regarding their definition and prototype) in our main portion of the program. These information are generally stored in special files which are supplied with the compiler. These special files that contain details of functions and types used in the library is called header file with extension .h in the include directory. Some commonly used header files are stdio.h and math.h. The suffix “h” generally designates a “header” file.
Note: Header files must be included at the beginning of the program of before the program can make use of library functions.
Function Data Type Task
ctype.h
isalnum(c) int Determine if argument is alphanumberic. Return nonzero value if true; 0 otherwise.
isalpha(c) int Determine if argument is alphanumeric. Return nonzero value if true; 0 otherwise.
isascii(c) int Determine if argument is an ASCII character. Return nonzero value if true; 0 otherwise.
iscntrl(c) int Determine if argument is an ASCII control character. Return nonzero value if true; 0 otherwise.
isdigit(c) int Determine if argument is a decimal digit. Return nonzero value if true; 0 otherwise.
Prepared by Mr. K. G. Page 5 Return nonzero value if true; 0 otherwise.
islower(c) int Determine if argument is lowercase. Return nonzero value if true; 0 otherwise.
isodigit(c) int Determine if argument is an octal digit. Return nonzero value if true; 0 otherwise.
isprint(c) int Determine if argument is a printing ASCII character. Return nonzero value if true; 0 otherwise.
ispunct(c) int Determine if argument is a punctuation character. Return nonzero value if true; 0 otherwise.
isspace(c) int Determine if argument is a whitespace character. Return nonzero value if true; 0 otherwise.
isupper(c) int Determine if argument is uppercase. Return nonzero value if true; 0 otherwise.
isxdigit(c) int Determine if argument is a hexadecimal digit. Return nonzero value if true; 0 otherwise.
toascii(c) int Convert value of argument to ASCII. tolower(c) int Convert letter to lowercase.
toupper(c) int Convert letter to uppercase. <math.h>
acos(d) double Return the arc cosine of d. asin(d) double Return the arc sine of d. atan(d) double Return the arc tangent of d. atan2(d1,d2) double Return the arc tangent of d1/d2.
ceil(d) double Return a value rounded up to the next higher integer. cos(d) double Return the cosine of d.
cosh(d) double Return the hyperbolic cosine of d. exp(d) double Raise e to the power h.
fabs(d) double Return the absolute value of d.
floor(d) double Return a value rounded down to the next lower integer. fmod(d1,d2) double Return the remainder of d1/d2 (with same sign as d1). labs(l) long int Return the absolute value of l.
log(d) double Return the natural logarithm of d. log10(d) double Return the logarithm (base 10) of d. pow(d1,d2) double Return d1 raised to the d2 power. sin(d) double Return the sine of d.
sinh(d) double Return the hyperbolic sine of d. sqrt(d) double Return the square root of d. tan(d) double Return the tangent of d.
tanh(d) double Return the hyperbolic tangent of d. <stdio.h>
fclose(f) int Close file f. return 0 if file is successfully closed.
feof(f) int Determine if an end-of-file condition has been reached. If so, return a non zero value; otherwise return 0.
fgetc(f) int Enter a single character from file f.
fgets(s,i,f) har* Enter string s, containing I characters, from file f.
fopen(s1,s2) file* Open a file named s1 of type s2. Return a pointer to the file. fprintf(f,…) int Send data items to file f.
fputc(c,f) int Send a single character to file f. fputs(s,f) int Send string s to file f.
fread(s,i1,i2,f) int Enter i2 data items, each of size i1 bytes, from file f to string s. fscanf(f,…) int Enter data items from file f.
fseek(f,l,i) int Move the pointer for file f a distance 1 bytes, from location i. ftell(f) long int Return the current pointer position within file f.
Prepared by Mr. K. G. Page 6 fwrite(s,i1,i2,f) int Send i2 data items, each of size i1 bytes from string s to file f. getc(f) int Enter a single character from file f.
getchar(void) int Enter a single character from standard input device. gets(s) char* Enter string s from standard input device.
printf(…) int Send data items to the standard output device. putc(c,f) int Send a single character to file f.
putchar(c) int Send a single character to the standard output device. puts(s) int Send string s to the standard output device.
rewind(f) void Move the pointer to the beginning of file f. scanf(..) int Enter data items from the standard input device. <stdlib.h>
abs(i) int Return the absolute value of i.
atof(s) double Convert string s to a double-precision quantity. atoi(s) int Convert string s to a integer.
atol(s) long Convert string s to a long integer.
calloc(u1,u2) void* Allocate memory foe an array having u1 elements, each of length u2 bytes. Return a pointer to the beginning of the allocated space. exit(u) void Close all files and buffers, and terminate the program. (value of u is
assigned by the function, to indicate termination status).
free(p) void Free a block of allocated memory whose beginning is indicated by p.
malloc(u) void* Allocate u bytes of memory. Return a pointer to the beginning of the allocated space.
rand(void) int Return a random positive integer.
relloc(p,u) void* Allocate u bytes of new memory to the pointer variable p. return a pointer to the beginning of the new memory space.
srand(u) void Initialize the random number generator.
system(s) int Pass command string s to the operating system. Return 0 if the command is successfully executed; otherwise, return a nonzero value typically -1.
1.8 Debugger: Debugger is a program which runs other programs in such a way as to let you see every step of program execution. A debugger will let you stop the program while it is running, change the program or program variables, and start the program running again.
Difference between Debugger and Compiler
Debugger Compiler
Debugger is another program that is used for testing and debugging purpose of other programs. Most of the time it is using to analyze and examine error conditions in application. It will be able to tell where exactly in your application error occurred, give you all needed addressed of variables, variable representation in code, stack trace and all other low level and sometimes high level information. Debugger allows you to run your code step by step, make breakpoints in application (to examine specific parts of code) and it can halt application after it crashed in order to examine the problem.
Compiler is special software or set software that translates source code from one computer language to another, in most cases from high-level programming language to low-high-level programming language.
Prepared by Mr. K. G. Page 7 1.9 COMPILERS, ASSEMBLERS and LINKERS
Normally the C’s program building process involves four stages and utilizes different ‘tools’ such as a preprocessor, compiler, assembler, and linker.
At the end there should be a single executable file. Below are the stages that happen in order regardless of the operating system/compiler and graphically illustrated in figure.
1) Preprocessing is the first pass of any C compilation. It processes include-files, conditional compilation instructions and macros.
2) Compilation is the second pass. It takes the output of the preprocessor, and the source code, and generates assembler source code.
3) Assembly is the third stage of compilation. It takes the assembly source code and produces an assembly listing with offsets. The assembler output is stored in an object file.
4) Linking is the final stage of compilation. It takes one or more object files or libraries as input and combines them to produce a single (usually executable) file. In doing so, it resolves references to external symbols, assigns final addresses to procedures/functions and variables, and revises code and data to reflect new addresses (a process called relocation).
5) The following Figure shows the steps involved in the process of building the C program starting from the compilation until the loading of the executable image into the memory for program running.
Here is a simple table showing input and output of each step in the compilation and execution process:
Input Program Output
Source Code Preprocessor Expanded Source Code Expanded Source Code Compiler Assembly Source Code Assembly Code Assembler Object Code
Object Code Linker Executable Code Executable Code Loader Execution
Prepared by Mr. K. G. Page 8
Figure Compile, link and execute stages for running program (a process)
Number of files created when c source file is compiled 1. .c // source code
2. .i // preprocessor 3. .obj // object file 4. .bak // backup file 5. .exe // executable file
Linker and Loader: Linker is a stage before loader. Linker is a person who is responsible for linking the different object file and the outcome will be a executable file. Loader is a person who reads the content of executable files and placed it into memory. This code shall be executed when the operating system control is coming to the loaded program.
Prepared by Mr. K. G. Page 9 Preprocessing - Using a Preprocessor program to convert C source code in expanded source code. "#includes" and "#defines" statements will be processed and replaced actually source codes in this step.
Compilation - Using a Compiler program to convert C expanded source to assembly source code.
Assembly - Using a Assembler program to convert assembly source code to object code. Linking - Using a Linker program to convert object code to executable code. Multiple units of
object codes are linked to together in this step.
Loading - Using a Loader program to load the executable code into CPU for execution. Here are examples of commonly used programs for different compilation and execution steps on a Linux system:
"cpp hello.c -o hello.i" - Preprocessor preprocessing hello.c and saving output to hello.i. "cc1 hello.i -o hello.s" - Compiler compiling hello.i and saving output to hello.s. "as hello.s -o hello.o" - Assembler assembling hello.s and saving output to hello.o. "ld hello.o -o hello" - Linker linking hello.o and saving output to hello.
"load hello" - Loader loading hello and running hello.
Simple Flowchart of Executing a C Program:
Running a Program Using Turbo C: Turbo C comprises turbo text editor and C compiler. Turbo C compiler is easy to learn and fast in compilation. It is an interactive compiler in MS-DOS environment. Consider the following steps to run C programs in Windows operating system.
Step 1: Select Start → Program → MS-DOS prompt
(or select MS DOS icon from the desktop, if displayed) Now the computer displays the system prompt (C:\>)
Prepared by Mr. K. G. Page 10 Step 2: Type C:\>tc
Now the turbo editor is displayed
Step 3: Type all the command lines or statements of the program.
Step 4: Press F2 key to save the program in suitable file name (e.g. hello.c) Step 5: Press F10 key to select the main menu.
Step 6: Select Compile option or press F9 key to compile and link the program. Step 7: Press F10 key and then select Run option to run the program.
Now the input values are entered and results are displayed. Then the control is transferred to the editing screen. Press Alt+F5 to switch to input/output screen to read the results.
Commonly Used Turbo Editing Commands/Key Controls: Cursor Control Keys
Arrow keys To move cursor in any direction (up, down, left and right)
Backspace To move cursor to the left by one place and erase the character in that position Space bar To move cursor/ character to the right by one place
Delete key To delete a character after the point the cursor is placed Enter key To move cursor to a new line
Insert key (on/off) To insert characters/lines Function Keys
F1 Help
F2 Save the program
F3 Open a new file or program
F4 Run program, but stop at the line where cursor is placed
F5 Zoom and unzoom editing window
F6 Switch to main menu
Ctrl+F9 Run program
ALT+F5 Switch between TC editing screen and output screen Alt+F6 Restore previous content of the screen window
Alt+F9 Compile the program
Alt+X Exit Turbo C
Prepared by Mr. K. G. Page 11 Editing Keys
Del Delete a character after the point the cursor is placed Ctrl+G Delete a character after the point cursor is placed
Ctrl+T To delete a string of characters from the pint the cursor is placed Ctrl+Y To delete a line where the cursor is placed
Block Operations
Ctrl+K+B Mark the beginning of a block Ctrl+K+K Mark the end of a block
Ctrl+K+C Copy the marked block in the current cursor position Ctrl+K+V Move the marked block to the current cursor position Ctrl+K+Y Delete the marked block
Ctr+K+H Remove the highlighted block marks
Compiling and Running on UNIX: UNIX operating system comprises a C language compiler called
cc. the commonly used editor in UNIX environment is vi editor. Consider the fillowing steps to run C programs in UNIX operating system.
Step 1: Type $vi hello.c to invoke the editor.
Note that hello.c is the file name of the program. Step 2: Press Esc+i to insert the program.
Step 3: Enter the C program using keyboard. Step 4: Press Esc to exit typing.
Step 5: Press Shift+: and then:wq to save the program. Step 6: Type cc hello.c to compile the program. Step 7: Type a.out to run the program.
1.10 Character Set: The C character set consists of the upper and lower case alphabets, digits, special characters and white spaces. The combination of alphabets and digits together form alphanumeric set. The complete character set is given below.
Alphabets: Uppercase: A, B,….., Z Lowercase: a, b,……, z Digits: 0 1 2 3 4 5 6 7 8 9 Special Characters:
, comma & ampersand
. period ^ caret
; semicolon * asterisk
: colon - minus sign
# number sign + plus sign
‘ apostrophe < opening angle bracket
“ quotation mark > closing angle bracket ! exclamation mark ( left parenthesis
| vertical bar ) right parenthesis
~ tilde [ left bracket
_ underscore ] right bracket
$ dollar sign { left brace
Prepared by Mr. K. G. Page 12 ? question mark
/ slash \ back slash
White Space Characters:
blank space newline carriage return formfeed horizontal tab vertical tab
1.11 Variables: A variable is an entity that has a value and is known to the program by a name. A variable definition associates a memory location with the variable name. A variable can have only one value assigned to it at any given time during the execution of the program. Its value may change during the execution of the program.
Example:
f=1.8*c+32
In above example, f and c are variable.
1.12 C-Tokens: A C-Token is the smallest individual unit of a C program. C has six types of tokens. 1. Keywords 2. Identifiers 3. Constants 4. Strings 5. Special Symbols 6. Operators
1.12.1 Keywords: Keywords are those words whose meaning has been fixed and is known to the compiler. We cannot change the meaning of the keywords. If we try to do then an error message will occur. Keywords serve as basic building blocks for program statements. All keywords must be written in lowercase.
Example:
auto break Case char Continue
default do double else Float
for goto if int Long
return static switch void While
1.12.2. Identifiers: Identifiers refers to the names of variables, functions, and arrays. They are the fundamental requirement of any language. Identifiers are user defined name and consists of a sequence of letters and digits, with a letter as a first character.
Both uppercase and lowercase letters are permitted although lowercase letters are commonly used. The underscore character is also permitted in identifiers. It is usually used as a link between two words in long identifiers. The following rules should be followed when an identifier is named:
(a) An identifier must begin with a letter and must be followed by letters and digits. (b) Underscore is permitted and considered as a letter.
(c) A declared keyword (such as int, char, void, if, for, while, etc) cannot be used as a variable name.
(d) C is case sensitive.
Example: a, b, name, str, no, n, fact etc.
1.12.3. Constants: Constant in C refers to fixed values that do not change during the execution of a C program. C supports several types of constants as shown in fig.
Prepared by Mr. K. G. Page 13
Figure Basic types of C constant
Numeric Constant: Integer and floating point constants are collectively referred as numeric constant. 1. Integer Constant: An integer constant refers to a sequence of digits. These are whole
numbers without any fractional part.
The following rules are allowed for constructing integer constant: (a) It must have atleast one digit.
(b) It must not contain a decimal point. (c) It may either plus or minus sign.
(d) When no sign is present it is assumes be positive. (e) Commas and blanks are not permitted.
There are three types of integers: (a) Decimal integer (base 10) (b) Octal integer (base 8)
(c) Hexadecimal integer (base 16)
2. Real Constant: These have fractional parts to represent quantities like average, height, area etc. which cannot be written in either fractional form or exponent form.
Example:
215.007 Fractional form
2.1565 e 2 Exponent form
3.44 E 3
The exponent form consists of two parts mantissa and exponent
Mantissa e exponent
The following rules are followed for constructing real constant in exponent form. (a) The mantissa and exponent are separated by e.
(b) The mantissa must be either an integer or a proper real constant.
(c) The mantissa may either plus or minus sign. When no sign is present it is assumes be positive.
(d) The exponent must be at least one digit integer.
Character Constant: Single character and string constants are collectively referred as character constant.
1. Single Character Constant: A single character contains a single quote marks. A character constant cannot be a length more than 1.
Examples: ‘3’ ‘x’ ‘;’ ‘ ‘ etc.
2. String Constant: A string constant is a sequence of character enclosed in double quotes. The character may be letters, numbers, special characters, and blank spaces.
Prepared by Mr. K. G. Page 14 An Important Difference: ‘A’ and ”A”
The notations ‘A’ and “A” have an important difference: the first (‘A’) is a character constant, while the second (“A”) is a 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 the ASCII code of A and another for the null character with the value 0, that terminates all strings.
1.12.4 Operands and Expression: The data items that operators act upon are called operands. Operation instructions are specified by operators (like +, −, *, / etc.) while operand can be variables or expressions.
Example: In a + b, a and b are operands while ‘+’ is the operator.
An expression is a combination of variables, constants and operators written according to the syntax of the language. In C, every expression evaluates to a value i.e. every expression result in some value of a certain type that can be assigned to a variable.
Example:
j=i=5;
1.12.5 Operator: An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. There are basically three types of operators.
a. Unary operators: Unary operators are those which are applied on a single operand. Some common unary operators are −, ++, − −, sizeof and cast i.e. (type) etc.
b. Binary operators: Binary operators are those which are applied on two operands. Some common binary operators are +, −, *, /, %, &&, ||, <, >, etc.
c. Ternary operator: Ternary operators are those which are applied on three operands. Ternary operator is ?: .
C operator can be classified into a number of categories: 1. Arithmetic operators
2. Relational operators 3. Logical operators 4. Assignment operators
5. Increment and decrement operators 6. Conditional operator
7. Bitwise operators 8. Special operators
1. Arithmetic Operators:
C provides all the arithmetic operators. They are listed in table.
The operators +, −, * and / all work the same way as they do in other languages.
The unary minus operator negate the value of a variable by putting minus (−) sign
prefix of the number or variable.
Operators Meaning
+ Addition
− Subtraction
Prepared by Mr. K. G. Page 15
/ Division
% Modulus (remainder)
1) Integer Arithmetic: An arithmetic operation involving only integer operands is called integer arithmetic. Example: int x = 3, y = 2; x + y = 5 x - y = 1 x * y = 6 x / y = 1 x % y = 1
2) Real Arithmetic: An arithmetic operation involving only real operands is called integer arithmetic. Example: float x = 3.0, y = 2.0; x + y = 5.0 x - y = 1.0 x * y = 6.0 x / y = 1.50
Note: % operator is not used when both operands are real.
3) Mixed-mode Arithmetic: When one of the operand is real and the other is integer, then the expression is called mixed-mode arithmetic expression.
Example: int y = 2; float x = 3.0; x + y = 5.0 x - y = 1.0 x * y = 6.0 x / y = 1.5 2. Relational Operators:
Relational operators are used to compare the values of operands (expressions) to produce a logical value.
A logical value is either true or false.
The relational operator returns zero values or nonzero values.
The zero value is taken as FALSE while the nonzero value is taken as TRUE.
Operators Meaning
< is less than
<= is less than equal to > is greater than >= is greater than equal to
== is equal to
Prepared by Mr. K. G. Page 16 3. Logical Operators:
Logical operators are used to connect more relational operations to form a complex expression called logical expression.
A value obtained by evaluating a logical expression is always logical, i.e. either TRUE or FALSE.
Operators Meaning Description
&& logical AND If both side of the condition is true, the whole expression results in true.
|| logical OR If either side of the condition is true, the whole expression results in true.
! logical NOT If the condition is true, the whole expression results in false and vice versa.
4. Assignment Operators:
The single “equal to” symbol (=) is called the assignment operator. It is an operator that assigns the value of the expression to the variable. Syntax:
variable = expression;
Example: x = 3; // x has value 3
Sorthand Assignment Operators: C has a rich set of sorthand assignment operators. Syntax:
variable op = expression;
Where
variable: It is any valid variable. op: It is a C binary operator.
The operator op = known as the sorthand assignment operator.
Operators Equivalent Assignment operator Description
a += 1 a = a + 1 Additional assignment (+=)
a -= 1 a = a – 1 Subtraction assignment (-=)
a *= n+1 a = a * (n+1) Multiplication assignment (*=)
a /= n+1 a = a / (n+1) Division assignment (/=)
a %= b a = a % b Modulus assignment (%=)
5. Increment and Decrement Operators:
Increment operator (++) is used to increase the value of an integer or char variable by 1. Decrement operator (− −) is used to reduce the value of an integer or char variable by 1. These are applied on a single variable. These are two types:
1) Prefix: The value is incremented / decremented first and then applied. 2) Postfix: The value is applied and the value is incremented / decremented.
Prepared by Mr. K. G. Page 17
Operators Meaning
++ variable Pre-increment operator
− −variable Pre-decrement operator variable ++ Post-increment operator variable − − Post-decrement operator Example: #include<stdio.h> main() { int i=3,j=4,k; k = i++ + --j; printf("i = %d, j = %d, k = %d",i,j,k); } Output: i = 4, j = 3, k = 6
Difference between Prefix and Postfix Operator
Prefix Operator Postfix Operator
1. A prefix operator first
incremented/decremented the value of operand by 1 and then applied.
A postfix operator applied first and then incremented/decremented the value of operand by 1.
2. Example:
int a = 1, b; b = ++a;
Here the value of variable a and b is 2 because first increment the value of variable a by 1 and then assign value of a to b.
Example:
int a = 1, b; b = a++;
Here the value of variables a is 2 and b is 1
because the value of a is first assign to b and then it is increment by 1.
6. Conditional Operators:
This is only one operator in C that takes three operands.
A conditional pair “? :” available in C to construct conditional expression of the form: Conditional expression
result = test-expression ? expression1 : expression2;
If test-expression is TRUE then expression1 is performed and assigned to result otherwise expression2 is performed and assigned to result.
Example: #include<stdio.h> main() { int i=2; int j=3; int k =(i>j) ? i : j; printf("\n k = %d",k); }
Prepared by Mr. K. G. Page 18 7. Bitwise Operators:
Bitwise operators are used to perform operations at binary digital level.
These operators are not commonly used and are used in special applic ations where optimized use of storage is required.
Operators Meaning
~ bitwise inversion (one’s complement) >> shift the bits to right
<< shift the bits to left & bitwise logical AND
| bitwise logical OR ^ bitwise XOR Example: #include<stdio.h> main() { char c1=1,c2=2,c3=3; c3=c1 & c2;
printf("\nBitwise AND i.e. c1 & c2 = %c",c3); c3=c1 | c2;
printf("\nBitwise OR i.e. c1 | c2 = %c",c3); c3=c1 ^ c2;
printf("\nBitwise XOR i.e. c1 ^ c2 = %c",c3); c3=~c1;
printf("\nOnes complement of c1 = %c",c3); c3=c1<<2;
printf("\nLeft shift by 2 bits c1 << 2 = %c",c3); c3=c1>>2;
printf("\nRight shift by 2 bits c1 >> 2 = %c",c3); }
Consider the following examples to understand the use of bitwise operators when a=13and b=6as 8-bit sort int (1 byte).
1) ~ Bitwise Inversion (One’s Complement): Let a=13; its binary equivalent is 00001101. Consider ~a;
which converts all 0’s to 1’s and all 1’s to 0’s.
The result obtained in this operation is 11110010(-14). 2) >> Shift the Bits to Right:
Let a=13; its binary equivalent is 00001101. Consider a>>2;
which shifts two bits to the right. That is, the zeros are inserted at the left to shift two bits at the right to move out as shown below.
Insert 2 bits at the left 00
00001101
Prepared by Mr. K. G. Page 19 The result obtained in this operation is 00000011(3).
3) << Shift the Bits to Left
Let a=13; its binary equivalent is 00001101. Consider a<<2;
which shifts two bits to the left. That is, the zeros are inserted at the right to shift two bits at the left to move out as shown below.
00 Insert 2 bits at the right
00001101
2 bits move out
The result obtained in this operation is 00110100 (52). Example:
#include <stdio.h>
void displayBits(unsigned value); void main()
{
unsigned number1=960;
printf("\nThe result of left shifting\n"); displayBits(number1);
printf("8 bit positions using the "); printf("left shift operator << is\n"); displayBits(number1 << 8);
printf("\nThe result of right shifting\n"); displayBits(number1);
printf("8 bit positions using the "); printf("right shift operator >> is\n"); displayBits(number1 >> 8);
}
void displayBits(unsigned value) { unsigned c; unsigned displayMask=1<<31; printf("%7u=", value); for(c=1;c<=32;c++) {
putchar(value & displayMask ? '1' : '0'); value <<= 1; if(c%8==0) { putchar(' '); } } putchar('\n'); } Output:
The result of left shifting
960 = 00000000 00000000 00000011 11000000
8 bit positions using the left shift operator << is 245760 = 00000000 00000011 11000000 00000000
Prepared by Mr. K. G. Page 20
The result of right shifting
960 = 00000000 00000000 00000011 11000000
8 bit positions using the right shift operator >> is 3 = 00000000 00000000 00000000 00000011
4) & Bitwise Logical AND:
Let a=13; its binary equivalent is 00001101
b=6; its binary equivalent is 00000110
a & bproduces result 00000100(4)
5) | Bitwise Logical OR
Let a=13; its binary equivalent is 00001101 b=6; its binary equivalent is 00000110
a | b produces result 00001111(15)
6) ^ Bitwise XOR
Let a=13; its binary equivalent is 00001101
b=6; its binary equivalent is 00000110
a ^ b produces result 00001011(11)
8. Special Operators: C supports some special operators of interest such as comma operator, sizeof
operator, pointer operators (& and *) and member selection operators (. and ->). ANSI committee has introduced two preprocessor operators known as “string-izing” and token-parsing” operators (#
and ##).
1) Comma Operator: The comma operator can be used to link the related expressions together. A comma-linked list of expressions are evaluated from left to right and the value of right most expression is the value of the combined expression.
Example: #include<stdio.h> main() { int i,j,k; k = (i = 10, j = 5, i+j); printf("k = %d",k); } Output: k=15
2) sizeof Operator: The sizeof operator returns the size of operand in bytes. The sizeof
operator always preceds its operand. Syntax:
sizeof(data type); sizeof(variable name);
Prepared by Mr. K. G. Page 21 #include <stdio.h> main() { int i=10; float f=3.14;
printf(“Size of int is %d\n”,sizeof(int));
printf(“Size of int variable is %d\n”,sizeof(i));
printf(“Size of float is %d\n”,sizeof(float));
printf(“Size of variable is %d\n”,sizeof(f));
printf(“Size of char is %d\n”,sizeof(char));
printf(“Size of double is %d”,sizeof(double));
}
Output:
Size of int is 2
Size of int variable is 2
Size of float is 4Size of variable is 4 Size of char is 1
Size of double is 8
3) Type Conversion: During programming, it is not necessary both the operands in an expression must be of same data type. In such situation when constants and variables of different types are mixed in an expression, they are converted to the same type, before evaluation, to maintain compatibility between data type. It can be either carried out by the following two methods:
(a) Implicit/Automatic/Silent conversion (b) Explicit conversion/Type casting/Casting
Thus, the process of converting one predefined data type into another is called type conversion.
(a) Implicit/Automatic/Silent conversion: This type of conversion is carried out by the compiler automatically, without programmer’s intervention. So it is also called silent conversion. It is generally applied on mixed mode expressions, i.e., where different data types are intermixed in an expressions. The table shown below lists the implicit type conversion rules.
Step No.
If either’s type is Then resultant type of other operand
Otherwise
1. long double long double Step 2
2. double double Step 3
3. float float Step 4
4. - integral promotion takes place
followed by step
-
5. unsigned long unsigned long Step 6
6. long int and other is unsigned int
(i) long int (provided long int can represent all values of unsigned int) (ii) unsigned long int (if all values of unsigned int can’t be represented by long int)
Step 7
Step 7
7. long long Step 8
Prepared by Mr. K. G. Page 22 operands are int
Promotion: When the variable of lower data type is converted to a higher type is called promotion.
Example:
float i; i=5;
Demotion: When the variable of higher data type is converted to a lower type is called demotion.
Example:
int i; i=5.5;
(b) Explicit Conversion/Type Casting/Casting: This conversion is done by the programmer explicitly, in which the programmer himself instruct the compiler to convert one type of variable into another. The operator used for this conversion is known as the cast operator and the process is known as casting.
Suppose we have
int i=7; float f=8.5;
Then the expression (i+f)%4 will be invalid because the result of (i+f) will be in floating-point and the modulus will not operated on floating-point variables.
So expression will become valid when we use casting ((int)(i+f))%4
forces the first operand to be an integer and is therefore valid resulting in the integer remainder. Example: #include <stdio.h> main() { double f1 = 12.23456; printf("%d \n", (int)f1); } Output: 12
1.13 Operator Precedence and Associativity: Operator has two important properties their precedence and their associativity.
Precedence (priority) rules help in removing the uncertainty about the order of performing operations while evaluating an expression.
Example: It is remains uncertain how to evaluate following expression either by method-1 or by method-2. Expression: 2+3*5 Method-1: (2+3)*5 5*5=25 Method-2: 2+(3*5) 2+15=17
Prepared by Mr. K. G. Page 23 According to precedence rule operator having highest precedence will be evaluate first after that operator having lower precedence will be evaluate. In the above expression method-2 will return the correct answer because multiplication operator has higher precedence than addition operators. Thus, expression will firstly evaluate 3*5 and then evaluate the expression where the result from the multiplication is added to 2 to produce answer 17.
Associativity: Associativity of an operator can be from left to right or right to left. Example: Consider the following expression:
total = price – discount + surcharge
The binary minus (-) and plus (+) operators have equal precedence and they have higher precedence than the assignment (+) operator. Therefore the order of evaluation proceeds left to right starting with ‘+’ and ‘-‘ operator according to their associativity. The evaluation computes the value (price – discount) add surcharge to the value and assign the value to total.
Table Operator for Precedence and Associativity
# Category Operator What it is (or does) Accociatvity
1. Highest () [] -> . Function call Array subscript
Indirect component selector Direct component selector
Left to right 2. Unary ! ~ + - ++ -- & * sizeof
Logical negation (NOT) Bitwise (1's) complement Unary plus Unary minus Preincrement or postincrement Predecrement or postdecrement Address Indirection
(returns size of operand, in bytes)
Right to left 3. Multiplicative * / % Multiply Divide Remainder (modulus) Left to right 4. Additive + - Binary plus
Binary minus Left to right
5. Shift <<
>>
Shift left
Shift right Left to right
6. Relational Less than
Less than or equal to Greater than
Greater than or equal to
Left to right
7. Equality ==
!=
Equal to
Not equal to Left to right
8. Bitwise AND & Bitwise AND Left to right
9. Bitwise XOR ^ Bitwise XOR Left to right
10. Bitwise OR | Bitwise OR Left to right
11. Logical AND && Logical AND Left to right
12. Logical OR || Logical OR Left to right
13. Conditional ?: (a ? x : y means "if a then x, else y") Right to left
14. Assignment = *= /= %= Simple assignment Assign product Assign quotient
Assign remainder (modulus)
Prepared by Mr. K. G. Page 24 += -= &= ^= |= <<= >>= Assign sum Assign difference Assign bitwise AND Assign bitwise XOR Assign bitwise OR Assign left shift Assign right shift
15. Comma , Evaluate Left to right
1.14 Formatted Input/Output Functions 1.14.1 printf() Function:
1. printf function is used to displays the output data using the standard output device (monitor). The output data can be any combination of numerical values, single character and strings.
2. printf returns the number of characters printed.
3. printf requires the backslash characters/escape sequences to display some special
characters. Escape sequences are control characters used to move the cursor and print characters such as ?, “, \ and so on.
Table Escape Sequences
Sequence Meaning
\a Beeps the speaker
\b Backspace (moves the cursor back, no erase)
\f Form feed (ejects printer page; may clear the screen on some computers) \n Newline, like pressing the Enter key
\r Carriage return (moves the cursor to the beginning of the line)
\t Tab
\v Vertical tab (moves the cursor down a line) \\ The backslash character
\' The apostrophe
\" The double-quote character
\? The question mark
\0 The "null" byte (that's 0, not the letter O) \Onn A character value in octal (base 8)
\xnnn A character value in hexadecimal (base 16)
4. printf can display variables by using the format specifiers listed in table.
printf Conversion Type Characters for Numeric data Types Format
specifier
Type of argument
Output
%d integer signed decimal integer
%i integer signed decimal integer
%o integer unsigned octal integer
%u integer unsigned decimal integer
%x integer unsigned hexadecimal integer
(with a, b, c, d, e, f)
%X integer unsigned hexadecimal integer
(with A, B, C, D, E, F) %f floating-point signed value of the form
Prepared by Mr. K. G. Page 25 [-]dddd.dddd
%e floating-point signed value of the form [-]d.dddd or e[+/-]ddd
%g floating-point signed value in either e or f form, based on given value and precision: Trailing zeros and the decimal point are printed if necessary %E floating-point same as e; with E for exponent
%G floating-point same as g; with E for exponent if e format is used
printf Conversion Type Character for Qualified Data Types Format
specifier
Type of argument
Output
%ld, %li long decimal long integer
%lu unsigned long decimal unsigned long integer
%hd, %hi short decimal short integer
%hu unsigned short decimal unsigned short integer
%le, %lf, %lg double signed, double
%Le,%Lf,%Lg long double signed, long double
%lo long octal long integer
%lx long hexadecimal long int
printf Conversion Type Character for Character Data Types Format
specifier
Type of argument
Output
%c char single character
%s sequence of char prints characters until a null-terminator is pressed or precision is reached
Syntax:
printf(“format string”, v1,v2,……,vn);
where “fomat string” is the control string which represents the format specification and
v1,v2,……,vn are variables whose values are to be displayed on the monitor.
Example: #include <stdio.h> void main() { int i = 0; i=printf("abcde\n");
printf("total characters printed %d\n",i); }
1.14.2 scanf() Function:
1. scanf function is used to read/input values of variable using the standard input device (keyboard).
Prepared by Mr. K. G. Page 26 scanf Conversion Type Characters for Numeric data Types
Type character
Expected input Type of argument
d decimal integer address of an integer
D decimal integer address of a long int
o octal integer address of an integer
O octal integer address of a long int
i decimal, octal or hexadecimal integer
address of an integer
I decimal, octal or hexadecimal integer
address of a long int
u unsigned decimal integer address of an unsigned integer U unsigned decimal long address of an unsigned long
x hexadecimal integer address of an integer
X hexadecimal integer address of a long int
e, E floating-point address of a float
f floating-point address of a float
g, G floating-point address of a float
scanf Conversion Type Character for Character Data Types Type
character
Expected input Type of argument
s character string name of the string
c Character address of a char variable
% % character no conversion done; scanf looks
for the % character in the input
3. Common scanf starts with a string argument and may contain additional arguments. Additional arguments must be pointers.
4. Search sets (%[…], %^[…]) are also used in formatted input. In this case scanf reads the input field up to the first character it meets that does not appear in the search set or inverted search set.
5. scanf returns the number of successful inputs. Syntax:
scanf(“format string”,& v1,&v2,….,&vn);
where “fomat string” is the control string which represents the format specification and
v1,v2,….,vn are variables whose values are to be read from keyboard.
Example: #include <stdio.h> void main() { int i = 0; int k,j=10;
printf("Input three integers and press enter to confirm."); i=scanf("%d%d%d",&j,&k,&i);
Prepared by Mr. K. G. Page 27
printf("The input values %d %d\n",j,k); }
1.14.3 More about Formatted Output Functions: Output values can be printed with specific width using command for formatted output. A simple format specification has the following form:
%w.p format-specifier
where w is an integer number that specifies the total number of columns for the output value and p is another integer number that specifies the total number of digits to the right of the decimal point or the number of characters to be printed from a string. We can make display left-justified in by placing a minus sign before the integer w. The default value for w is 1.
Example:
Output of Format Output
Integer Numbers printf(“%d”,9876); 9 8 7 6 . printf(“%6d”,9876); 9 8 7 6 . printf(“%2d”,9876); 9 8 7 6 . printf(“%-6d”,9876); 9 8 7 6 . printf(“%06d”,9876); 0 0 9 8 7 6 . Real Numbers printf(“%7.4f”,98.7654); 9 8 . 7 6 5 4 . printf(“%7.2f”,98.7654); . 9 8 . 7 7 . printf(“%-7.2f”,98.7654); 9 8 . 7 7 .. printf(“%f”,98.7654); 9 8 . 7 6 5 4 . . printf(“%10.2e”,98.7654); 9 . 8 8 e + 0 1 . printf(“%11.4e”,-98.7654); - 9 . 8 7 6 5 e + 0 1 . printf(“%-10.2e”,98.7654); 9 . 8 8 8 e + 0 1 . printf(“%e”,98.7654); 9 . 8 7 6 5 4 0 e + 0 1 . Strings printf(“%s”,”New Delhi”); N e w D e l h i . printf(“%12s”,”New Delhi”); N e w D e l h i . printf(“%12.6s”,”New Delhi”); N e w D e . printf(“%.6s”,”New Delhi”); N e w D e . printf(“%-12.7s”,”New Delhi”); N e w D e l . printf(“%5s”,”New Delhi”); N e w D e l h i .
1.14.4 More about Formatted Input Functions: Values can be read/input with specific width using command for formatted input. A simple format specification has the following form:
%w format-specifier
where w is an integer number that specifies the field width of the number to be read. Example:
Prepared by Mr. K. G. Page 28 Integer Numbers scanf(“%d%*d%d”,&a,&b,&c); scanf(“%2d%4d%3d”,&a,&b,&c); scanf(“%2d%4d”,&a,&b); 1 2 3 123456789 1234 5678 a=1, b=3, c=garbage a=12, b=3456, c=789 a=12, b=34
Real Numbers scanf(“%f%f”,&a,&b); 75.89 43.21e-1 a=75.89, b=4.321
Strings scanf(“%s”,&str); scanf(“%5s”,&str); scanf(“%[a-z]”,&str); scanf(“%[^aeiou]”,&str); New Delhi Delhi Abc123ef String str=New str= Delhi str=Abc str=Str
Note: * skip the input value.
#include <stdio.h> void main() { int month1; int day1; int year1; int month2; int day2; int year2;
printf( "Enter a date in the form mm-dd-yyyy: " ); scanf( "%d%*c%d%*c%d", &month1, &day1, &year1 );
printf( "month = %d day = %d year = %d\n\n", month1, day1, year1 ); printf( "Enter a date in the form mm/dd/yyyy: " );
scanf( "%d%*c%d%*c%d", &month2, &day2, &year2 );
printf( "month = %d day = %d year = %d\n", month2, day2, year2 ); }
Output:
Enter a date in the form mm-dd-yyyy: 01-01-2001 month = 1 day = 1 year = 2001
Enter a date in the form mm/dd/yyyy: 01/01/2002 month = 1 day = 1 year = 2002
When scanf Stops Scanning:
(i) scanf stops and skips to the next input field: The scanf function stops scanning and storing the current input field: it proceeds to the next if any one of the following situation occurs:
(a) An assignment-suppression character (*) appears after the % in the format specifier: the current input field is scanned but not stored.
(b) The number of characters specified by the width specifier have been read.
(c) The number of character read cannot be converted under the current format (for example, the character A is entered when the format is %i).
(d) The next character in the input field does not appear in the search set, or does not appear in the inverted search set.
(ii) scanf stops scanning entirely, and returns: The scanf function terminates under the following circumstances:
(a) The next character in the input field has a conflict with a corresponding non-whitespace character in the format string.
(b) The next character in the input field is EOF. (c) The format string specification has been exhausted.
Prepared by Mr. K. G. Page 29 (d) If a character sequence that is not a part of the format specifier occurs in the format string, it must match the current sequence of characters in the input field.
1.15 Character Input/Output Functions
1.15.1 getchar() Function: getchar() function is used to read one character at a time from the standard input device (keyboard). It has the following form:
char_variable=getchar(); Example: #include<stdio.h> void main() { char ch;
printf("Enter any character"); ch=getchar();
printf("Entered character is %c",ch); }
When this function is executed, the computer will wait for a key to be pressed and assigns the value to the variable ‘ch’ when the enter key is pressed.
1.15.2 put char() Function: putchar() function is used to display one character at a time on the monitor screen. It has the following form:
putchar(char_variable); Example: #include<stdio.h> void main() { char ch;
printf("Enter any character"); ch=getchar();
putchar(ch); }
When this function is executed, the computer will display the value of the char variable ‘ch’ on the monitor screen.
1.15.3 getch() Function: getch()function is used to read a character from the keyboard and it does not expect the enter key press. It has the following form:
char_variable=getch(); Example: #include<stdio.h> void main() { char ch;
printf("Enter any character"); ch=getch();
printf("Entered character is %c",ch); }
When this function is executed, the computer will wait for a key to be pressed from the keyboard. As soon as a key is pressed, the control is transferred to the next line of the program and the value is
Prepared by Mr. K. G. Page 30 assigned to the char variable ‘ch’. It is to be noted that the key (letter) pressed will not be displayed on the monitor screen.
1.15.4 putch() Function: putch() function is used to display a character on the monitor screen. It has the following form:
putch(char_variable); Example: #include<stdio.h> void main() { char ch;
printf("Enter any character"); ch=getchar();
putch(ch); }
When this function is executed, the computer will display the value of the char variable ‘ch’ on the monitor screen.
1.15.5 getche() Function: getche() function is used to read a character from the keyboard without expecting the enter key press. However any key pressed by the user will be displayed on the monitor. It has the following form:
char_variable=getche(); Example: #include<stdio.h> void main() { char ch;
printf("Enter any character"); ch=getche();
printf("Entered character is %c",ch); }
When this function is executed, the computer will wait for a key to be pressed from the keyboard. The value is assigned to the char variable ‘ch’.
Note: geche() is similar to getch() expect that getche() displays the key pressed from the keyboard on the monitor screen. The ‘e’ at the end of getche()stands for echo.
1.15.6 gets() Function: gets() function is used to read a string of characters including white spaces. Note that a string containing white spaces cannot be read using scanf() with “%s” format specifier. It has the following form:
gets(str_variable); Example: #include<stdio.h> void main() { char str[10];
printf("Enter any string"); gets(str);
Prepared by Mr. K. G. Page 31
printf("Entered string is %s",str); }
When this function is executed, the computer will wait for the string value. Enter string of characters and press the enter key. It is to be noted that C language will add a null character “\0” to the end of any character string.
1.15.7 puts() Function: puts() function is used to display a characters string on the monitor screen. It has the following form:
puts(str_variable); Example: #include<stdio.h> void main() { char str[10];
printf("Enter any string"); gets(str);
puts(str); }
When this function is executed, the computer will display the value of the character string variable
‘str’ on the monitor screen.
1.16 Data Types: For each variable you have to attach some data type. The data type defines: a. The amount of storage allocated to variables.
b. The values that they can accept.
c. The operations that can be performed on variables. ANSI supports following data types:
1. Basic\Standard\Primary\Fundamental Data Type 2. Derived Data Type
3. User-defined Data Type
1. Basic\Standard\Primary\Fundamental Data Types: All C compilers support four fundamental data types, namely character (char), integer (int), floating point (float), and double-precision floating point (double). Many of them also offer extended data type such as long int and long double. Table shows all the allowed combinations of basic data types and qualifiers and their size and range on a 16-bit machine.
Type Size Value Range Value Range in decimal
char or signed char 1 byte -27 to 27-1 -128 to 127
unsigned char 1 byte 0 to 28-1 0 to 255
int or signed int 2 bytes -215 to 215-1 -32768 to 32767
unsigned int 2 bytes 0 to 216-1 0 to 65535
short int or signed short int 1 byte -27 to 27-1 -128 to 127
unsigned short int 1 byte 0 to 28-1 0 to 255
long int or signed long int 4 bytes -231 to 231-1 -2147483648 to 2147483647
unsigned long int 4 bytes 0 to 232-1 0 to 4294967295
Float 4 bytes -231 to 231-1 3.4e-38 to 3.4e38
Double 8 bytes -263 to 263-1 1.7e-308 to 1.7e308
Prepared by Mr. K. G. Page 32 Qualifiers: Qualifiers modify the behavior of the variable type to which they are applied. For example
int i;
This declaration specifies that i is an integer which takes both positive and negative values, that is, i
is a signed integer by default. The above declaration could also be written as
signed int i;
But the qualifier signed is not necessary, since int is signed by default. If the variable i is used to hold only positive values we declare:
unsigned int i;
Here qualifier unsigned is applied to the data type int. This qualifier modifies the behavior of the integer so that the number contained in a variable of this type is unsigned.
Qualifiers can be classified into two types: Size qualifiers
Example: short and long. Sign qualifiers
Example: signed and unsigned.
const Qualifier: It is used to informs the compiler that variable is constant type and it can not be modified anywhere in the program.
Example:
const float pi=3.14;
2. Derived Data Types: Some derived data types in C are array, function, and pointer. These are called derived because these are derived by using some other data types.
Example:
int a[10];
3. User-Defined Data Types: The data types that are defined by the user with the existing data types are known as user defined data type. Some user-defined data types in C are typedef, and enum. Examples:
(a) typedef int units; units batch1, batch2;
(b) enum day {Monday, Tuesday, ……, Sunday}; enum day week_st, week_end;
Program: #include <stdio.h> #include <limits.h> #include <float.h> void main() {
printf("Variables of type char store values from %d to %d", CHAR_MIN,CHAR_MAX);
printf("\nVariables of type unsigned char store values from 0 to %u", UCHAR_MAX);
printf("\nVariables of type short store values from %d to %d", SHRT_MIN, SHRT_MAX);
printf("\nVariables of type unsigned short store values from 0 to %u", USHRT_MAX);
printf("\nVariables of type int store values from %d to %d", INT_MIN,INT_MAX);
Prepared by Mr. K. G. Page 33
UINT_MAX);
printf("\nVariables of type long store values from %ld to %ld", LONG_MIN, LONG_MAX);
printf("\nVariables of type unsigned long store values from 0 to %lu", ULONG_MAX);
printf("\nVariables of type long long store values from %lld to %lld", LLONG_MIN, LLONG_MAX);
printf("\nVariables of type unsigned long long store values from 0 to %llu", ULLONG_MAX);
printf("\n\nThe size of the smallest nonzero value of type float is %. 3e", FLT_MIN);
printf("\nThe size of the largest value of type float is %.3e", FLT_MAX);
printf("\nThe size of the smallest nonzero value of type double is %.3 e", DBL_MIN);
printf("\nThe size of the largest value of type double is %.3e", DBL_MAX);
printf("\nThe size of the smallest nonzero value of type long double i s %.3Le", LDBL_MIN);
printf("\nThe size of the largest value of type long double is %.3Le\n ", LDBL_MAX);
printf("\nVariables of type float provide %u decimal digits precision. ", FLT_DIG);
printf("\nVariables of type double provide %u decimal digits precision .", DBL_DIG);
printf("\nVariables of type long double provide %u decimal digits prec ision.", LDBL_DIG);
}
Output:
Variables of type char store values from -128 to 127
Variables of type unsigned char store values from 0 to 255 Variables of type short store values from -32768 to 32767 Variables of type unsigned short store values from 0 to 65535 Variables of type int store values from -2147483648 to 2147483647 Variables of type unsigned int store values from 0 to 4294967295 Variables of type long store values from -2147483648 to 2147483647 Variables of type unsigned long store values from 0 to 4294967295 Variables of type long long store values from -9223372036854775808 to 9223372036854775807
Variables of type unsigned long long store values from 0 to 18446744073709551615
The size of the smallest non-zero value of type float is 1.175e-38 The size of the largest value of type float is 3.403e+38
The size of the smallest non-zero value of type double is 2.225e-308 The size of the largest value of type double is 1.798e+308
The size of the smallest non-zero value of type long double is 3.362e-4932
The size of the largest value of type long double is 1.190e+4932 Variables of type float provide 6 decimal digits precision.
Variables of type double provide 15 decimal digits precision. Variables of type long double provide 18 decimal digits precision.
1.16.1 Overflow in char and unsigned char Data Types: Overflow means you are carrying out an operation such that the value either exceeds the maximum value or is less than the minimum value of the data type.
Example: