the curly braces {} define the beginning and end of a program block ..... and Mathews Leon (2001), Introduction to Infor
BASICS OF C PROGRAMMING Shalini Bhaskar Bajaj
C Character Set •
Alphabets
A, B, …….Z, a, b, …….z
•
Digits
0, 1, …. ,9
•
Special Symbols
~!@#$%^&*()_+{}|:“?-=[]\;‘,./
Shalini Bhaskar Bajaj
2
Constants, Variables and Keywords Can be formed by properly using alphabets, digits and symbols •
Constant
that never changes
•
Variable
that may change
•
Keyword
that carries special meaning
Shalini Bhaskar Bajaj
3
Type of Constants Constants
Primary Constants
Secondary Constants
Integer Constant Real Constant Character Constant
Array Pointers Structures Unions etc.
Shalini Bhaskar Bajaj
4
Rules for Constructing Integer Constants •
Must have at least one digit
•
Must not have a decimal point
•
Can be either +ve or –ve
•
No commas or blank spaces are allowed
Examples: -200, 543, 1, -1, 34
Shalini Bhaskar Bajaj
5
Rules for Constructing Real Constants •
Must have at least one digit
•
Must have a decimal point
•
Can be either +ve or –ve
•
No commas or blank spaces are allowed
Examples: -200.43, 543.9, 1.7, -1.24567, 34.972
Shalini Bhaskar Bajaj
6
Rules for Constructing Character Constants •
Single alphabet or single digit or single special character within single inverted commas
•
Both commas should point to left
Examples: ’A’, ’a’, ’3’, ’#’
Shalini Bhaskar Bajaj
7
Rules for Constructing Variable Names •
First character must be an alphabet or underscore
•
No special symbol other than underscore is used
•
No comma or blank spaces are allowed in variable names
•
Length of variable name can be from 1 to 31 characters
Examples: abc, addition, matrix_multiplication, x123, z1, _a2, _1
Shalini Bhaskar Bajaj
8
C Keywords or Reserved Words •
Only 32 keywords are available
•
Their meaning is already known to the compiler
•
Keywords cannot be used as variable names
List of Keywords/Reserved words
Keywords/Reserved Words auto double
struct break
do static
default char
switch const
int
case
long
float
void
extern
short
if
continue
signed
enum
sizeof
unsigned
volatile
union
typedef
Shalini Bhaskar Bajaj
register return for goto
while else
9
Fundamental Data Types Storage requirement is hardware dependent For 16-bit processor: •
char
I byte
•
int
2 bytes
•
float
4 bytes
•
double
8 bytes
For altering the size
–
short and long
For altering the sign
–
signed and unsigned Shalini Bhaskar Bajaj
10
Data Types char int float double
unsigned char, signed char signed int, unsigned int, long int, short int, signed short int, unsigned short int, signed long int, unsigned long int
long double
Shalini Bhaskar Bajaj
11
Data Type - int Points to remember: •
The storage size of int data type is 2 or 4 or 8 byte. It varies depend upon the processor in the CPU that we use.
•
If we are using 16 bit processor, 2 byte(16 bit) of memory will be allocated for int data type. Like wise, 4 byte(32 bit) of memory for 32 bit processor and 8 byte(64 bit) of memory for 64 bit processor is allocated for int.
•
int(2 byte) can store values from -32,768 to +32,767 int(4 byte) can store values from -2,147,483,648 to +2,147,483,647.
Shalini Bhaskar Bajaj
12
Data Types The range of the data types is in accordance with 16-bit processor. S.No C Data types Storage Size Range 1 char 1 –127 to 127 2 int 2 –32,767 to 32,767 3 float 4 1E–37 to 1E+37 with six digits of precision 4 double 8 1E–37 to 1E+37 with ten digits of precision 5 long double 10 1E–37 to 1E+37 with ten digits of precision 6 long int 4 –2,147,483,647 to 2,147,483,647 7 short int 2 –32,767 to 32,767 8 unsigned short int 2 0 to 65,535 9 signed short int 2 –32,767 to 32,767 10 long long int 8 –(2power(63) –1) to 2(power)63 –1 11 signed long int 4 –2,147,483,647 to 2,147,483,647 12 unsigned long int 4 0 to 4,294,967,295 13 unsigned long long int 8 2(power)64 –1 Shalini Bhaskar Bajaj
13
Commonly used Conversion Characters for Data Input Conversion Character
Data Type
%d
Integer
%c
Character
%f
Floating point or Real number
%s
String
%x
Hexadecimal
%o
Octal
%lf
Double floating point
%Lf
Long double
%u
Unsigned integer
%g, %G
Floating point number in exponential notation Shalini Bhaskar Bajaj
14
Escape Sequences Escape Sequence
Character
\a
Bell (speaker beeps)
\b
Backspace (non-erase)
\f
Form feed/clear screen
\n
New line
\r
Carriage Return
\t
Tab
\v
Vertical tab
\\
Backslash
\?
Question mark
\'
Single quote
\"
Double quote Shalini Bhaskar Bajaj
15
Input and Output functions Input/Output Functions
Formatted
output printf()
Unformatted
input scanf()
output putch() putchar() puts()
Shalini Bhaskar Bajaj
input getch() getche() getchar() gets()
16
Formatted output - printf() printf() is used to display output on the standard output device Syntax: printf (“Control String”, list of variables); or printf(“Content to be printed”); e.g. int r = 4; printf(“The result is %d”, r); Output: The result is 4
e.g. printf(“Hello World”);
Output: Hello World Shalini Bhaskar Bajaj
17
Formatted Input – scanf() scanf() is used to read input from the standard device.
Syntax: scanf(“Control String”, list of addresses of variables); e.g. int a, b, c; scanf(“%d %d %d”, &a, &b, &c);
e.g. int a; float b; char c; scanf(“%d %f %c”, &a, &b, &c); Shalini Bhaskar Bajaj
18
Unformatted Input – getch() It returns a character just entered from the standard input device. The entered character is not echoed on the computer screen. Syntax:
variable_name = getch(); e.g. char var;
var = getch();
Shalini Bhaskar Bajaj
19
Unformatted Input – getche() It returns a character just entered from the standard input device. The entered character is echoed on the computer screen. It does not wait for enter key to be pressed.
Syntax: variable_name = getche(); e.g. char var; var = getche();
Shalini Bhaskar Bajaj
20
Unformatted Input – getchar() It returns a character just entered from the standard input device. The entered character is echoed on the computer screen. It waits for enter key to be pressed. Syntax:
variable_name = getchar(); e.g. char var;
var = getchar();
Shalini Bhaskar Bajaj
21
Unformatted Input – gets() Reads string from the standard input device. It overcomes the drawback of the scanf() function for receiving a multiword string Syntax: gets(variable_name); e.g. char var[40]; gets(var);
Shalini Bhaskar Bajaj
22
Unformatted Output – putchar() It prints the character constant or character variable to the standard output device.
Syntax: putchar(variable name); e.g. char ch =‘A’ ; putchar(ch); putchar(‘a’); Output: Aa Shalini Bhaskar Bajaj
23
Unformatted output – puts() Displays only one string at a time on the screen
Syntax: puts(s); e.g.
char s[40]; puts(“Enter the name:”); gets(s); Output:
printf(“\n”);
puts(“Name entered is:”);
Enter the name: Akshaya Singh Name entered is: Akshaya Singh
puts(s); Shalini Bhaskar Bajaj
24
Limitation of scanf() scanf() cannot receive multiword input
char s[40];
char s[40];
puts(“Enter the name:”);
printf(“Enter the name:”);
gets(s);
scanf(“%s”, s);
printf(“\n”); puts(“Name entered is:”);
printf(“\nName entered is: %s”, s);
puts(s);
Output: Output:
Enter the name: Akshaya Singh
Enter the name: Akshaya Singh
Name entered is: Akshaya
Name entered is: Akshaya Singh Shalini Bhaskar Bajaj
25
Important Points •
program execution begins at main()
•
keywords are written in lower-case
•
statements are terminated with a semi-colon
•
text strings are enclosed in double quotes
•
C is case sensitive, use lower-case and try not to capitalize variable names
•
\n means position the cursor on the beginning of the next line
•
printf() can be used to display text to the screen
•
the curly braces {} define the beginning and end of a program block Shalini Bhaskar Bajaj
26
C - Operators An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C language is rich in built-in operators and provides the following types of operators: •
Arithmetic Operators
•
Relational Operators
•
Logical Operators
•
Bitwise Operators
•
Assignment Operators
•
Misc. Operators Shalini Bhaskar Bajaj
27
Arithmetic Operators For calculations, let A = 20 and B = 40 Operator
Description
Example
+
Adds two operands
A + B will give 60
-
Subtracts second operand from the first
A - B will give -20
*
Multiplies both operands
A * B will give 800
/
Divides numerator by de-numerator
B / A will give 2
%
Modulus Operator and remainder of after an integer division
B % A will give 0
++
Increments operator increases integer value by one
A++ will give 21
--
Decrements operator decreases integer value by one
A-- will give 19
Shalini Bhaskar Bajaj
28
#include void main() { int a = 21; int b = 10; int c ; c = a + b; printf("Line 1 - Value of c is %d\n", c ); c = a - b; printf("Line 2 - Value of c is %d\n", c ); c = a * b; printf("Line 3 - Value of c is %d\n", c ); c = a / b; printf("Line 4 - Value of c is %d\n", c ); c = a % b; printf("Line 5 - Value of c is %d\n", c ); c = a++; printf("Line 6 - Value of c is %d\n", c ); c = a--; printf("Line 7 - Value of c is %d\n", c ); }
Output generated: Line 1 - Value of c is 31 Line 2 - Value of c is 11 Line 3 - Value of c is 210 Line 4 - Value of c is 2 Line 5 - Value of c is 1 Line 6 - Value of c is 21 Line 7 - Value of c is 22
Shalini Bhaskar Bajaj
29
Relational Operators Operator == != >
= B) is not true. (A < B) is true.
(A >= B) is not true. (A b ) { printf("Line 3 - a is greater than b\n" ); } else { printf("Line 3 - a is not greater than b\n" ); } /* Lets change value of a and b */ a = 5; b = 20; if ( a = a ) { printf("Line 5 - b is either greater than or equal to b\n"); } }
Shalini Bhaskar Bajaj
31
Logical Operators Let variable A holds 1 and variable B holds 0, then: Operator &&
Description Called Logical AND operator. If both the operands are non-zero, then condition becomes true.
Example (A && B) is false.
||
Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true.
!
Called Logical NOT Operator. !(A && B) is true. Use to reverses the logical state of its operand. If a !(A || B) is false. condition is true then Logical NOT operator will make false. Shalini Bhaskar Bajaj
(A || B) is true.
32
#include main() { int a = 5; int b = 20; int c ; if ( a && b ) { printf("Line 1 - Condition is true\n" ); } if ( a || b ) { printf("Line 2 - Condition is true\n" ); }
/* lets change the value of a and b */ a = 0; b = 10; if ( a && b ) { printf("Line 3 - Condition is true\n" ); } else { printf("Line 3 - Condition is not true\n" ); } if ( !(a && b) ) { printf("Line 4 - Condition is true\n" ); } }
Output generated:
Shalini Bhaskar Bajaj
Line 1 - Condition is true Line 2 - Condition is true Line 3 - Condition is not true Line 4 - Condition is true 33
Bitwise Operators Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows
p 0 0 1 1
q 0 1 1 0
p&q 0 0 1 0 Shalini Bhaskar Bajaj
p|q 0 1 1 1
p^q 0 1 0 1 34
Bitwise Operators Assume if A = 60; and B = 13; now in binary format they will be as follows: A = 0011 1100 B = 0000 1101 ----------------A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011
Shalini Bhaskar Bajaj
35
Bitwise Operators Operator Description & | ^ ~
Example
Binary AND Operator copies a bit to the result if it exists in both (A & B) will give 12, which is operands. 0000 1100 (A | B) will give 61, which is Binary OR Operator copies a bit if it exists in either operand. 0011 1101 Binary XOR Operator copies the bit if it is set in one operand but (A ^ B) will give 49, which is not both. 0011 0001 (~A ) will give -61, which is Binary Ones Complement Operator is unary and has the effect of 1100 0011 in 2's 'flipping' bits. complement form.
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. Shalini Bhaskar Bajaj
A >> 2 will give 15 which is 0000 1111 36
#include void main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */
Output generated: Line 1 - Value of c is 12 Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15
int c = 0; c = a & b; /* 12 = 0000 1100 */ printf("Line 1 - Value of c is %d\n", c ); c = a | b; /* 61 = 0011 1101 */ printf("Line 2 - Value of c is %d\n", c ); c = a ^ b; /* 49 = 0011 0001 */ printf("Line 3 - Value of c is %d\n", c ); c = ~a; /*-61 = 1100 0011 */ printf("Line 4 - Value of c is %d\n", c ); c = a > 2; /* 15 = 0000 1111 */ printf("Line 6 - Value of c is %d\n", c ); }
Shalini Bhaskar Bajaj
37
Assignment Operators Operator Description
Example
=
Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assign value of A + B into C
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C=C +A
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
C -= A is equivalent to C=C –A
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
C *= A is equivalent to C=C *A
/=
Divide AND assignment operator, It divides left operand with the C /= A is equivalent to right operand and assign the result to left operand C=C/A Shalini Bhaskar Bajaj
38
Assignment Operators Operator Description
Example
%=
Modulus AND assignment operator, It takes modulus using C %= A is equivalent to C = C % A two operands and assign the result to left operand
> 2
&=
Bitwise AND assignment operator
C &= 2 is same as C = C & 2
^=
bitwise exclusive OR and assignment operator
C ^= 2 is same as C = C ^ 2
bitwise inclusive OR and assignment operator
C |= 2 is same as C = C | 2
|=
Shalini Bhaskar Bajaj
39
#include main() { int a = 21; int c ; c = a; printf("Line 1 - = Operator Example, Value of c = %d\n", c ); c += a; printf("Line 2 - += Operator Example, Value of c = %d\n", c ); c -= a; printf("Line 3 - -= Operator Example, Value of c = %d\n", c ); c *= a; printf("Line 4 - *= Operator Example, Value of c = %d\n", c ); c /= a; printf("Line 5 - /= Operator Example, Value of c = %d\n", c ); c = 200; c %= a; printf("Line 6 - %= Operator Example, Value of c = %d\n", c ); c = 2; printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );
c &= 2; printf("Line 9 - &= Operator Example, Value of c = %d\n", c ); c ^= 2; printf("Line 10 - ^= Operator Example, Value of c = %d\n", c ); c |= 2; printf("Line 11 - |= Operator Example, Value of c = %d\n", c ); }
Output generated:
Line 1 - = Operator Example, Value of c = 21 Line 2 - += Operator Example, Value of c = 42 Line 3 - -= Operator Example, Value of c = 21 Line 4 - *= Operator Example, Value of c = 441 Line 5 - /= Operator Example, Value of c = 21 Line 6 - %= Operator Example, Value of c = 11 Line 7 - = Operator Example, Value of c = 11 Line 9 - &= Operator Example, Value of c = 2 Line 10 - ^= Operator Example, Value of c = 0 Line 11 - |= Operator Example, Value of c = 2
Shalini Bhaskar Bajaj
40
Misc Operators --- sizeof & ternary Operator Description
sizeof()
Example
Returns the size of an variable.
sizeof(a), where a is integer
&
Returns the address of an variable.
&a; will give actual address of the variable.
*
Pointer to a variable.
*a; will pointer to a variable.
Conditional Expression
If Condition is true ? Then value X : Otherwise value Y
?:
Shalini Bhaskar Bajaj
41
#include main() { int a = 4; short b; double c; int* ptr; /* example of sizeof operator */ printf("Line 1 - Size of variable a = %d\n", sizeof(a) ); printf("Line 2 - Size of variable b = %d\n", sizeof(b) ); printf("Line 3 - Size of variable c= %d\n", sizeof(c) ); /* example of & and * operators */ ptr = &a; /* 'ptr' now contains the address of 'a'*/ printf("value of a is %d\n", a); printf("*ptr is %d.\n", *ptr); /* example of ternary operator */ a = 10; b = (a == 1) ? 20: 30; printf( "Value of b is %d\n", b ); b = (a == 10) ? 20: 30; printf( "Value of b is %d\n", b ); } Shalini Bhaskar Bajaj
Output generated: Line 1 - Size of variable a = 2 Line 2 – Size of variable b = 2 Line 3 – Size of variable c = 8 value of a is 4 *ptr is 4. Value of b is 30 Value of b is 20
42
Operators Precedence in C Category Postfix Unary Multiplicative Additive Shift Relational Equality
Operator () [] + - ! ~ ++ - - (type)* & sizeof */% +> < >= == !=
Shalini Bhaskar Bajaj
Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right
43
Operators Precedence in C Category Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional Assignment Comma
Operator & ^ | && || ?: = += -= *= /= %=>>=