New C Notes Upto
New C Notes Upto
New C Notes Upto
NOTE:
The required ranges for signed and unsigned int are identical to those for signed and unsigned short. On compilers for 8 and 16 bit processors (including Intel x86 processors executing in 16 bit mode, such as under MS-DOS), an int is usually 16 bits and has exactly the same representation as a short. On compilers for 32 bit and larger processors (including Intel x86 processors executing in 32 bit mode, such as Win32 or Linux) an int is usually 32 bits long and has exactly the same representation as a long.
JNTUWORLD
C Operators Notes A signed short can hold all the values between SHRT_MIN and SHRT_MAX inclusive. SHRT_MIN is required to be -32767 or less, SHRT_MAX must be at least 32767. Again, many 2's complement implementations will define SHRT_MIN to be -32768 but this is not required. An unsigned short can hold all the values between 0 and USHRT_MAX inclusive. USHRT_MAX must be at least 65535. The short types must contain at least 16 bits to hold the required range of values. On many (but not all) C implementations, a short is smaller than an int. Programs which need to have very large arrays of integer values in memory, or store very large numbers of integers in files might save memory or storage space by using short in place of int if both of the conditions below are met: 1. Short is truly smaller than int on the implementation. 2. All of the required values can fit into a short. NOTE: On some processor architectures code to manipulate shorts can be larger and slower than corresponding code which deals with ints. This is particularly true on the Intel x86 processors executing 32 bit code, as in programs for Windows (NT/95/98), Linux, and other UNIX derivatives. Every instruction which references a short in such code is one byte larger and usually takes extra processor time to execute.
JNTUWORLD
C Operators Notes An unsigned long can hold all the values between 0 and ULONG_MAX inclusive. ULONG_MAX must be at least 4294967295. The long types must contain at least 32 bits to hold the required range of values.
JNTUWORLD
C Operators Notes An unsigned long long can hold all the values between 0 and ULLONG_MAX inclusive. ULLONG_MAX must be at least 18446744073709551615. The long types must contain at least 64 bits to hold the required range of values.
Values In <limits.h>
The standard header <limits.h> contains macros which expand to values which allow a program to determine information about the ranges of values each integer type can hold at run time. Each of these types (except for "plain" char, that is char without a signed or unsigned in front of it) must be able to contain a minimum range of values. Type signed char <limits.h> Constant SCHAR_MIN SCHAR_MAX Minimum Value -127 127 0 255 (note 1) -32767 32767 0 65535 -32767 32767 0 65535 -2147483647 2147483647 0 4294967295 -9223372036854775807 9223372036854775807
unsigned char
"plain" char
signed short
unsigned short
signed int
unsigned int
signed long
unsigned long
JNTUWORLD
C Operators Notes
ULLONG_MAX
0 18446744073709551615
Note 1: On implementations where default " plain" is signed, CHAR_MIN is equal to SCHAR_MIN and CHAR_MAX is equal to SCHAR_MAX. If "plain" char is unsigned, CHAR_MIN is 0 and CHAR_MAX is equal to UCHAR_MAX.
OPERATORS:
C includes a large number of operators which fall into different categories. These are Arithmetic Operators Relational Operators Logical Operators Assignment Operators Unary Operators Conditional Operators Bit-Wise Operators Arithmetic Operators: To solve most programming problems we need to perform arithmetic operations by writing arithmetic expressions. The following table shows all arithmetic operators provided by C. Arithmetic Meaning Declarations: int a=5, b=16 Operators Double c=3.0, d=7.5 Integer Examples Floating Point Examples + _ * / % Addition Subtraction Multiplication Division Remainder (Modulo Division) a + b is 21 a b is -11 b a is 11 b * a is 80 a / b is 5 b / a is 3 a % b is 5 b % a is 1 c + d is 10.5 c - d is -4.5 d c is 4.5 c * d is 22.5 c / d is 0.4 d / c is 2.5 Not Possible
Each operator manipulates two operands, which may be constants, variables, or other arithmetic expression. The arithmetic operators may be used with int or double data type 5 JNTUWORLD
C Operators Notes operands. On the other hand, the remainder operator also known as modulus operator can be used with integer operands to find the remainder of the division. When both operands in an arithmetic expression are integers, the expression is called as integer expression, and the operation is called integer arithmetic. When both operands in an arithmetic expression are floating point numbers, the expression is called floating point expression or real expression, and the operation is called floating point arithmetic or real arithmetic. The result of an integer arithmetic always have integer value. The remainder operator (%) requires that both operands be integers and the second operand be non zero. The division operator requires the second operand be nonzero. The result of integer division results in a truncated quotient (i.e. the decimal portion of the quotient will be dropped). If a division operation is carried out with two floating point numbers or with one floating point number and one integer, the result will be a floating point quotient. For example 7.5/5=1.5. If one of both operands are negative then the addition, subtraction, multiplication, and division operations will result in values whose signs are determined by the usual rules of algebra. The result of the remainder operation always gets the sign of first operand. For examples If a=14 and b=5 then a % b=4 If a=-14 and b=5 then a % b = -4 If a = -14 and b = 5 then a % b = -4 If a= -14 and b = -5 then a % b = 4 Operands the differ in type may undergo type conversion before the expression takes on its final value. In general, the final result will be expressed in the highest precision possible, consistent with the data type of the operands.
For example Operand 1 Short Int Double Double Operand 2 Int Float Float Int Result Int Float Double Double
JNTUWORLD
Relational Operators:
Relational Operators are used in C to compare values, typically in conditional control statements. The four relational operators in c are <,<=,>,>=. There are two equality operators = = and !=. They are closely associated with the relational operators. Relational Operator < <= > >= Equality Operators == != Meaning Less than Less than or equal to Greater than Greater than or equal to Meaning Equal to Not equal to
The double equal sign = = used to compare equality is different from the single equal to = sign which is used as an assignment operator. These six operators are used to form logical expressions, which represent conditions that are either true or false. The result of the expressions is of type integer, since true is represented by the integer value 1 and false is represented by the value 0. Declarations: Expression i< 4 (i + j <= 10 f >g f <= g j/i != 2 int i=3, j=7; flaot f=5.5,g=4.5 Interpretation True True True False False
Value 1 1 1 0 0
Among the relational and equality operators each operator is a complement of another operator in group.
JNTUWORLD
C Operators Notes Using complement operators we can simplify the expressions as Original Expression !(a<b) !(a>b) !(a!=b) !(a<=b) !(a>=b) !(a= =b) Logical Operators: In addition to arithmetic and relational operators, C has 3 logical operators for combining logical values and creating new logical values. These operators are Logical Operator Meaning ! NOT && Logical AND || Logical OR NOT: The NOT operator (!) is a unary operator (Operator that acts upon single operand). It changes a true value (1) to false (zero) and a false value to true. AND: The AND operator (&&) is a binary operator. Its result is true only when both operands are true; otherwise it is false. OR: The OR operator (| |) is a binary operator. Its result is false only when both the operands are false; otherwise true. Declarations: int i=3, j=7; double f=5.5 , g=4.5 char ch=T Expression Interpretation Value (i<= 5) && (ch = = T) True 1 (j < 8) || (ch = = L) True 1 (f + g) = = 10.0 | | I < 2 F >= 6 | | (i*j)<15 !(f>5.0) True False False 1 0 0 Simplified Expression a>=b a<=b a= =b a>b a<b a!=b
Assignment Operator:
Assignment operator assigns the value of expression on the right side of it to the variable on the left of it. The assignment expression evaluates the operand on the right side of the 8 JNTUWORLD
C Operators Notes operator (=) and places its value in the variable on the left. Assignment expressions that make use of assignment operator have the form: Identifier = expression; Where identifier represents a variable and expression represents a constant, a variable or a more complex expression. Ex: a = 2; Area = length * width; Note: If the two operands in an assignment expression are of different data types, then the value of the expression on the right side of assignment operator will automatically be converted to the type of the identifier on the left of assignment operator.
For example A floating value may be truncated if it is assigned to an integer identifier. A double value may be rounded if it is assigned to a floating point identifier. An integer value may be changed if it is assigned to a short integer identifier or to a character identifier.
Unary Operators:
The operators that act upon a single operand to produce a new value are known as unary operators. C supports the following unary operators. Operators: Minus operator Increment operator ++ Decrement operator - Size operator (type) operator
Minus operator
The most common unary operation is a unary minus, where a numerical constant, variable or expression is preceded by a minus sign. It is important to note that the unary minus operation is distinctly different from the arithmetic operator which denotes subtraction (-). The subtraction operator requires two separate operands. Ex: -123, -qty, -4E-8
JNTUWORLD
C Operators Notes
sizeof Operator:
In C, an operator sizeof is used to calculate size of various datatypes. These can be basic or primitive datatypes present in the language, as well as the ones, created by programmer. The sizeof opearator looks like a function, but it is actually an operator that returns the length, in bytes. It is used to get size of space any data-element/datatype occupies in memory. If type name is used, it always needs to be enclosed in parentheses, whereas variable name can be specified with or without parentheses. Ex: int i; sizeof i; sizeof(int);
10
JNTUWORLD
C Operators Notes
Conditional Expressions
Simple conditional operations can be carried out with the conditional operator (? :). The conditional operator (? :) is a ternary operator since it takes three operands. The general form of conditional expression is Test expression ? expression 1 : expression 2; Conditional operator works as follows: The test expression is implicitly converted to Boolean expression. It is evaluated. If the result of test expression is true(1), the expression 1 is evaluated and the conditional expression takes on value of expression 1. If the result of test expression is false (0), the expression 2 is evaluated and the conditional expression takes on value of expression 2.
Therefore the result of the conditional operator is the result of whichever expression is evaluated the first or the second. Only on of the last 2 expressions is evaluated in a conditional expression.
Bitwise operators
The bitwise operators are the bit manipulation operators. They can manipulate individual bits within the piece of data. These operators can operate on integers and characters but not on floating point numbers or numbers having double data type. Operator Description The bitwise complement operator is an unary operator. It complements each bit of the operand. The bitwise AND operator compares each bit of its first operand to the corresponding bit of its second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise the corresponding bit is set to 0. The bitwise inclusive OR operator compares each bit of its first operand to the corresponding bit of its second operand. If either of bits is 1 the corresponding result bit is set to 1, otherwise the corresponding bit is set to 0. Example Operand = 1111 0000 1111 0000 ~ operand Resulted Operand = 0000 1111 0000 1111 Operand 1 = 1111 1111 1111 0000 Operand 2 = 1111 0000 1111 0000 X= operand 1 & operand 2 Then X= 1111 0000 1111 0000 Operand 1= 0000 1111 0011 0000 Operand 2= 1111 1111 0000 1111 X=operand 1 | operand 2 Then X= 1111 1111 0011 1111
&
11
JNTUWORLD
C Operators Notes The bitwise exclusive OR operator compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1 the corresponding result bit is set to 1 otherwise result bit is set to 0. The bitwise shift left operator is a binary operator. The first operand is the value to be shifted and the second operand specifies the number of bits to shifted. The bitwise right shift operator is a binary operator. The first operand is the value to be shifted and the second operand specifies the number of bits to be shifted. Operand 1= 1111 0000 1100 0011 Operand 2= 1111 1111 0011 0011 X= operand 1 ^ operand 2 Then X= 0000 1111 1111 0000 Operand 1 = 1111 0000 1111 0001 Operand 2 = 1 X=operand 1 << operand 2 X= 1110 0001 1110 0010 Operand 1 = 1111 0000 1111 0000 Operand 2 = 2 X = operand 1 >> operand 2 X=00 1111 0000 1111 00
<<
>>
Right to left
3 4
12
JNTUWORLD
C Operators Notes Bitwise shift left, bitwise shift right Relational less than / less than or equal to Relational greater than / greater than or equal to Relational is equal to / is not equal to Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Ternary (Conditional) Ternary ? : = += Assignment %= &= ^= != <<= >>= Comma , -= Assignment Addition/Subtraction Assignment Multiplication/Division Assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise Shift left/right assignment Comma (separate Expression) Right to left 13
Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right
5 6 7 8 9 10 11 12
*= /=
Right to left
14
Left to right
15
The data entered by the user through the standard input device and processed data is displayed on the standard output device. I/O Functions: I / O functions are grouped into two categories. Unformatted I/O functions Formatted I/O function. The Formatted I/O functions allows programmers to specify the type of data and the way in which it should be read in or written out. On the other hand, unformatted I/O functions do not specify the type of data and the way is should be read or written. Amongst the above specified I/O functions scanf() and printf() are formatted I/O functions. Function Formatted Unformatted Input Output scanf() printf() getchar(),gets() putchar(),puts()
Formatted Output The printf function C provides the printf function to display the data on the monitor. This function can be used to display any combination of numerical values, single characters and strings. The general form of printf statement Function name Function arguments printf(my roll number is %d. \n, rollno) control string print list The %d is known as a placeholder or conversion character or format code or format specifier. At the time of display the value of the specified variable is substituted at the place of placeholder. In out example, value of rollno is substituted in place of %d. The printf uses different placeholders to display different type of data items.
Placeholder
%c %d
14
JNTUWORLD
C Operators Notes %e %f %g %i %o %s %u %x Floating point number with an exponent Floating point number without an exponent Floating point number either with exponent or without exponent depending on value. Trailing zeros and trailing decimal point will not be displayed. Singed decimal number Octal number, without leading zero String Unsigned decimal integer Hexadecimal number, without leading zero
There are certain letters which may be used as prefix for certain placeholders. These are h: the h letter can be applied to d,i,o,u and x placeholders. The h letter tells printf() to display short integers. As an example, %hu indicates that the data is of type short unsigned integer. l: the l letter can be applied to d,i,o,u and x placeholder. The l letter tells printf() to display long integers. As an example, %ld indicates that the data is of type long integer. When it is applied to f, it indicates double data type. L: the L letter, when applied to f indicates long double data type. Some important points to remember Control string must be enclosed within the double quotes. For every data item to be displayed there must be a placeholder corresponding to its data type. Multiple placeholders are allowed in the control string. In such a case they may be contiguous or separated by blank spaces or commas. The data items must be included in the print list and they must be separated by commas. Print list is not enclosed within double quotes. The comma must be used to separate the format string and the print list.
15
JNTUWORLD
C Operators Notes justified. We can force the information to be left justified by putting a minus sign directly after the %. For example
printf statement
1 2
printf(%d,x);
printf(%6d,x);
1 Right justified
printf(%-6d,x);
Left justified As shown in the above examples, if the number width in digits is less than the minimum field width the empty places are filled with spaces. However if the number width is greater than the minimum field width, the number is printed in the full, overriding the minimum field width specification. This is illustrated in the following list. It is also possible to pad the empty places with zeros. If we want to pad with zeros, we have to place a zero before the minimum field width specifier.
printf statement
printf(%3d,x); 1 2
printf(%06d,x);
As shown in the above examples, if the number width in digits is less than the minimum field width the empty places are filled with spaces. However if the number width is greater than the minimum field width, the number is printed in the full, overriding the minimum field width specification. This is illustrated in the following list. It is also possible to pad the empty places with zeros. If we want to pad with zeros, we have to place a zero before the minimum field width specifier.
16
JNTUWORLD
C Operators Notes
printf statement
printf(%3d,x); 1 2
printf statement
3
printf(%f,x);
Default precision is 6 3 4 5 6 . 1 2
printf(%7.2f,x);
Total 7 characters wide out of 2 are decimal point printf(%9.2f,x); 3 Right justified printf(%-9.2f,x); 3 4 5 6 . 1 2 4 5 6 . 1 2
C Operators Notes
When the precision is applied to strings, the number preceding period specifies the minimum field width and the number following the period specifies the number of characters of the string to be displayed. For examples %16.9s will display a string that will be at least sixteen characters long; however only first nine characters from the string are displayed with remaining blank characters. Let us see the important points related to formatted string display. When minimum field width is specified without negative sign, display is right justified. When only minimum field width is specified and it is less than the actual string length, the minimum field width is overridden and complete string is displayed. We can insert negative sign before minimum field width to get left justified display.
printf statement
printf(%s,str);
Output (assume str: THIS IS A TEST STRING containing 21 characters including blanks.)
T H I S I S A T E S T S T R I N G
printf(%24s, str);
T HI S
I S
T ES T
S T R I NG
printf(%24.14s ,str);
T H I S
I S
T ES T
Escape Sequences to enhance the readability of output The backslash symbol( \ ) is known as escape character. Since the newline character and the tab character begin with backslash they are called escape sequences. They are
Escape Sequences
\n \t
Function
Newline : Displays the message or variable values following it on the next line. Tab: Moves cursor to the next tab
18
JNTUWORLD
C Operators Notes Backspace: Moves cursor one position to the left of its current position. Form feed: Advances the computer stationary attached to the printer to the top of next page. Single Quote: Displays single quote Backslash: Displays backslash Double Quote: Displays double quote Carriage Return : Takes the cursor to the beginning of the line in which it is currently placed. Alert: Alerts the user by sounding the speaker inside the computer.
\b \f \ \\ \ \r \a
Functions
In structural programming, the program is divided into small independent tasks. These tasks are small enough to be understood easily without having to understand the entire program at once. Each task is designed to perform specific functionality on its own. When these tasks are performed, their outcomes are combined together to solve the problem. Such a structural programming can be implemented using modular programming. In modular programming, the program is divided into separate small programs called modules. Each module is designed to perform specific function. Modules make out actual program shorter, hence easier to read and understand. A defined function or set of similar functions is coded in a separate module or sub module, which means that code can be loaded into memory more efficiently and that modules can be reused in other programs. After a module has been tested individually, it is then integrated with other modules into the overall program structure. Each module can be subdivided according to software engineering principles. The following structural chart shows the relation between each module and its sub module. Such a design approach is called top-down design.
Main Module
Module 1
Module 2
Module 3
19
Module 1A Module 1B Module 1C Module 2A Module 2B Module 3A
JNTUWORLD
Module 3B
C Operators Notes
The main module is known as a calling module because it has submodule. Each of the sub module is known as called modules. However, modules 1, 2 and 3 also have sub modules therefore they are also calling modules. The communication between modules in a structure chart is allowed only through a calling module. If module 1 need to send data to module 2, the data must be passed through the calling module, main module. No communication can take place directly between modules that do not have a clling-called relationship. This means that in a structural chart, a module can be called by one and only one higher module. There are several advantages of modular / structural programming, some of them are
Easy Debugging: Since each function is smaller and has a logical clarity, it is easy to
locate and correct errors in it.
Basics of Functions
A function by definition, is a procedure or routine. In other words, its a self-contained block of code that executes a certain task. Although some languages do distinguish between procedure and function, whereas a function returns a value of some kind and a procedure does not, C combines both functionalities into its definition. In order to use function in the program we need to establish 3 elements that are related to the function. Function Declaration: All identifiers in C need to be declared before they are used. This is true for functions as well as variables. For functions the declarations needs to be before the first call of the function.
20
JNTUWORLD
C Operators Notes Function Definition: It is actual code for the function to perform the specific task. Function Call: In order to use function in the program we use function call to access the function. The program or function that calls the function is referred to as calling program or calling function.
void main() /* the main function */ { print_msg(); /* The function call */ } print_msg() /* the function definition */ { printf(this is a module called print_msg \n); }
21
JNTUWORLD