ANSI C - Government Arts College, Thiruvananthapuram · ANSI C American National Standards...
Transcript of ANSI C - Government Arts College, Thiruvananthapuram · ANSI C American National Standards...
-
ANSI C American National Standards Institute
-
Importance of C
1. Robust language: Rich built in functions and operators can help in developing complex programmes
2. Suitable for developing system software and business package: C compiler combines assembly language and high level language capabilities.
3. Fast and Efficient
4. Highly portable: Computer to computer portability, even to new operating system.
5. Structured programming: function modules or blocks.
6. Easy for debugging, testing and maintenance.
7. Ability to extent itself: Add our own functions to the C library.
-
Character set in C
Letters A … Z ( Upper case) a …. z (Lower case) Digits 0 … 9 White spaces Blank space Horizontal tab Carriage return New line Form feed
-
, Comma
. Period
; Semicolon
: Colon
? Question mark
‘ Apostrophe
“ Quotation mark
! Exclamation mark
| Vertical bar
/ Slash
\ Back slash
~ Tilde
_ Underscore
$ Dollar sign
% Percentage sign (Modulo)
& Ampersand
^ Caret
* Asterisk
- Minus sign
+ Plus sign
< Opening angle bracket (Less than sign)
> Closing angle bracket (greater than sign)
( Left parenthesis
) Right parenthesis
[ Left bracket
] Right bracket
{ Left brace
} Right brace
# Number sign (Hash)
Special characters
-
Basic Structure of C programs
Documentation section
Link Section
Definition section
Global declaration section
main () Function section
{
Declaration part
}
Sub program section
Function 1
Function 2
.
.
Function n
-
Basic C program
main ()
{
/*………printing begins……..*/
printf(“This is a model programme”);
/*………printing ends……..*/
}
Function name
Start of the programme
Programme statements
End of the programme
Comments
#include
main () { printf(“This is a model programme”); }
-
Constants
Constants
Numeric constants
Real constants Integer
constants
Character constant
Single character constant
String constants
Fixed values that do not change its value during the execution of a programme.
1233 -342 0 1322034032 +4323
0.0394 -0.234 +234.2343 456.0 1.6e-19
Mantissa e exponent
a 5 ; “
“hello” “1987” “Welldone”
-
Variables
Variable is a data name that may be used to store data value. The value in the variable can
change in different times during the execution of the programme.
Can take any name (Identifier) : Averaga, height, Total, class_strength, Employee_1 etc..
Rules for selecting identifier:
1. Letters digits and (_) Underscore are allowed.
2. They must begin with a letter. Some may permit use of _ as first character.
3. ANSI standard recognises length of the name as 31 characters. But still many compilers
takes only first 8 characters.
4. Uppercase and lower case are different.
5. It should not be a keyword
6. White space not allowed
-
Data types 1. Primary Data type (Fundamental data type)
Integer: int, short int, long int, unsigned int, unsigned short int, unsigned long int
Character: char, signed char,unsigned char
Floating : float, double, long double
Void : void
2. Derived Data type: Array, function, pointer etc. 3. User defined data type: typedef structure union
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Float 2 or 4 byte
16 bit or 32 bit machine
Double 8 byte 14 digit precision
-
Declaration of variables
Before using a variable, we must declare them to the compiler.
1. It tells the compiler what the variable name is
2. It specifies what type of data the variable hold and suitable memory is allotted.
Primary type declaration
data-type var1, var2, var3… varn; // Syntax
Eg: int count;
int number, total;
double ratio;
User defined data type declaration
typedef type identifier; // Syntax
Eg: typedef int units;
typedef char name;
units batch1, batch2;
name std1, std2;
-
Assigning values to variables
Variable_name = constant; //syntax
Eg: initial_value = 1;
final_value = 100;
interest = 9.34;
yes = ‘x’;
Initialisation (Assigning value before using the variable)
data-type variable_name = constant; // Syntax
Eg: int initial_value = 1;
int final_value = 100;
float interest = 9.34;
char yes = ‘x’;
‘=‘ assignment operator
-
Defining symbolic constants
#define symbolic_name valueofconstant //syntax
Eg: #define Strength 100
#define PASS_Mark 50
#define pi 3.14159
Rules
1. Symbolic_name should be an identifier.
2. No blank space between # and define
3. Blank space is required after #define and after symbolic_name
4. No end semicolon.
5. No equal sign on assigning values
6. #define may appear anywhere in the program but before the constant is used in the
program.
-
Declaring a variable as constant
const data-type identifier = value; //syntax
Eg: const int Strength = 100;
const int PASS_Mark = 50;
const float pi = 3.14159;
Declaring a variable as volatile :- means the value may change during the programme
volatile data-type identifier ; //syntax
volatile data-type identifier = value; //syntax
Eg: volatile int date;
volatile const int number = 100; // declared as both volatile
and constant
-
Input/Output functions
Input functions
stdio.h
Function Syntax Usage
getchar( ); Variable_name = getchar( ); char name;
name= getchar( );
scanf( );
scanf(“control string”, arg1, arg2, ,.. argn);
scanf(“control string”, &variable1, &variable2,..);
scanf(“%d”, &number);
scanf(“%d %d”, &nmb1, &nmb2);
scanf(“%2d %4d”, &nmb1, &nmb2); • Gets 2 digit integer for first number and
4 digit integer for second. • If more data added, it will be considered
for next input function.
Format string
Formatted input
scanf (“%d %c %f %s”, &count, &code, &ratio, name); Reading mixed data type
15 p 1.575 coffee
-
Input/Output functions
Output functions
stdio.h
Function Syntax Usage
putchar( ); putchar (variable_name);
char answer;
answer = ‘Y’;
putchar (answer);
printf( ); printf(“control string”, variable1, variable2,..); printf(“Programme in C”);
printf(“sum = %d”, 1234);
printf(“%d”, 9876);
printf(“%6d”, 9876);
printf(“\n”);
printf(“a= %d\n b= %d”, nmb1, nmb2);
9876
9876
% w.p type-specifier Minimum filed width of specifier
-
Rules of scanf( );
1. Each variable to be read must have a field specification.
2. All function arguments except the control string must be pointers to variables.
3. Format specificaions contained in the control string should match the arguments in
order.
4. scanf() ignores bondaries and simply looks for the next appropriate character.
5. Any unread data items in a line will be considered as part fo the data input line to the
next scanf() call.
6. Never end the format string with whitespace. IT IS AN ERROR.
7. scanf reads until:
• Whitespace character is found in a numeric specification or
• The maximum number of characters have been read or
• An error is detected or
• The end of file is reached.
8. scanf() returns the number of data received from the keyboard. In case of error the
returned integer will have lesser value than specified.
-
Code Meaning for scanf() Meaning for printf()
%c Read a single character Print a single character
%d Read a decimal integer Print a decimal integer
%e Read a floating point value Print a floating point value in exponential form
%f Read a floating point value Print a floating point value without exponential form
%g Read a floating point value Print a floating point value either e-type or f-type depending on value
%h Read a short integer
%i Read a decimal, hexadecimal or octal integer
Print a signed decimal integer
%o Read an octal integer Print an octal integer without leading zero
%s Read a string Print a string
%u Read an unsigned decimal integer Print an unsigned decimal integer
%x Read a hexadecimal integer Print hexadecimal integer, without leading 0x
%[..] Read a string of word(s)
- Left justified + precede the signed numeric with + or – # precede 0 or 0x and present floating point number with decimal point Ever if it is whole number
-
Operators
1. Arithmetic Operators +, -, *, /, % :- integer arithmetic and real arithmetic
2. Relational Operators =, ==, !=
3. Logical Operators &&, ||, !
4. Assignment operators =, +=, -+, *=, /=, %= a+=1 means a=a+1
5. Increment and decrement operators ++, --
6. Conditional operators ?: exp1?exp2:exp3 x = (a > b) ? a : b; ternary operator
7. Bitwise operators &, |, ^,
8. Special operators comma operator, sizeof operator,
-
If statement
if(test expression) { Statement block; } Statement -X
Statement block
Statement -X
Next statement
Entry
True
False
Test expression ?
-
If … else statement
if(test expression) { True block statements; } else { False block statements; } Statement – X Next statement
False block statement(s)
Statement -X
Next statement
Entry
True False Test expression ?
True block statement(s)
-
Nesting of If … else statement if(test condition 1) { if (test condition 2) { statement 1; } else { statement 2; } } else { if (test condition 3) { statement 3; } else { statement 4; } }
-
The else if Ladder
if(test condition 1)
Statement 1;
else if (test condition 2)
statement 2;
else if (test condition 3)
statement 3;
else if( test condition n)
statement n;
else
default statement;
statement.;
-
The switch statement switch ( expression )
{
case value-1:
block 1
break;
case value-2:
block 2
break;
……….
………..
default:
default block
break;
}
Next statement
-
The goto statement
Forward Jump
goto label;
………. ……….. ………
………. ……….. ………
………. ……….. ………
………. ……….. ………
label:
statement;
Backward jump
label:
statement;
………. ……….. ………
………. ……….. ………
………. ……….. ………
………. ……….. ………
goto label;
-
The while loop
while (test condition) { body of the loop; }
main ( )
{
int count, n=1;
printf(“Enter an integer value :”);
scanf(“%d”, &count);
printf(“Integers upto %d are”, n);
while(n
-
The do loop
do { body of the loop; } while (test condition);
main ( )
{
int count, n=1;
printf(“Enter an integer value :”);
scanf(“%d”, &count);
printf(“Integers upto %d are”, n);
do
{
printf(“\n %d”, n);
n = n+1;
}
while(n
-
The for loop
for( initialization condition; test condition; increment ) { body of the loop; } main ( )
{
int count, n;
printf(“Enter an integer value :”);
scanf(“%d”, &count);
printf(“Integers upto %d are”, n);
for (n=1; n
-
The jump statements
goto
Go to a label
break;
Breaks from a loop
Continue
Skip the remaining step and continue from the condition statement of a loop.
exit()
Exits from a program .
exit(0);
-
Array
List of items with same variable name. One dimensional array
[0]
[1]
[2]
[3]
[4]
X x[0], x[1], x[2], x[3], x[4] :- number of elements n. ie 0 to n-1 Allots separate memory location for each variable. 35
0
546
-1
6453
Declaration type array_name[size]; //syntax int height[10]; int x[5]; Initialisation 1. Compile time:
type array_name[size] = {list of values};
int x[5] = {35, 0, 546, -1, 6453}; 2. Run time: type array_name[size]; ………….. for(n=0;n
-
Two dimensional array
[0] [1] [2] [3]
[0] X[0][0] X[0][1] X[0][2] X[0][3]
[1] X[1][0] X[1][1] X[1][2] X[1][3]
[2] X[1][0] X[2][1] X[2][2] X[2][3]
[3] X[3][0] X[3][1] X[3][2] X[3][3]
[4] X[4][0] X[4][1] X[4][2] X[4][3]
columns
Ro
ws
type array_name[sizeofrow][sizeofcolumn]; int x[5][4];
for(i=0 ; i
-
main( ) { ………………….. ………………… function1( ); ………………….. ……………………… function2( ); ……………………… ………………………… function1( ); }
Functions in C
• Building block of a programme
• Sub programme of program.
• Modular programme
• Sub set of main program.
function1( ) {…………………….. ………………… }
function2( ) { ……………………. function3(); …………………… }
function3( ) {…………………….. ………………… }
-
Requirements of a function
1. Function definition
2. Function call
3. Function declaration
return_type function _name ( parameter,list ) { local variable declaration; //body of the function execution statements; ……………………………….. return (expression ); //return statement }
function_name ( arguments );
return_type function _name ( list, of, parameter, data-types );
-
Functions in C
float read_data ( void ); float mul (float , float); void write_data(float); main ( ) { float x, y,z; x = read_data ( ); y = read_data ( ); z = mul (x, y); write_data (z); }
float read_data (void) { float a; printf(“Enter a data \n”) scanf(“%f “, &a); return (a); } float mul (float p, float q) { float prod; prod = p * q; return (prod); } void write_data (float result) { printf (“The product of entered data is : %f”, result); :}
-
Standard library functions of ANSI C?
Assignment
-
Recursion function
factorial ( int n) { int fact; if (n ==1);; return(1); else fact = n*factorial(n-1); return (fact); }
Recursion is a process in which a function calls itself in its body.
Nesting of function
Nesting is a process in which a second function is called inside the body of a function.
-
Structure
Conveniently group different types of data in one bundle.
1. Structure definition
2. Structure variable declaration
struct structure_name, obj1, obj2, obj3;
3. Accessing structure members
object . variable
struct structure_name { data-type variable1; data-type variable2; . . }; // close with ‘;’ is very important
Struct book_details { char title[20]; char author[15]; int pages; float price; };
struct book_details, book1, book2;
book1.price = 395.50; book2.price = 982.00;
-
Pointer
Pointer is a datatype which contains the memory address. Pointers can access and manipulate data stored in the memory.
1. Accessing memory
& -operator
Eg: &a &p[5] etc.
2. Declaration of pointer
data_type * pt_name;
Eg: int *p; float *x;
3. Initialization of pointer variable
int quantity;
int *p;
p = &quantity;
4. Accessing a variable through its pointer
n = *p;
179
quantity
5000
Variable
Value
Address
5000
p
8000
Variable
Value
Address
-
File operations
1. Defining and opening a file FILE *fp; fp = fopen ( “filename”, “mode” );
2. Closing a file
fclose (file_pointer);
FILE *p1, *p2; p1 = fopen(“INPUTT”, “w”); p2 = fopen(“OUTPUT”, “r”); . . fclose (p1); fclose (p2);
fopen (), fclose(), getc(), putc(), fprintf(), fscanf(), putw(), getw(), fseek(), ftell(), rewind()
filename: primaryname ‘Period’ Extension
Prog.c
Text.out Inp.data
-
File operations
INPUT/OUTPUT Operations
getc(), putc() : handles one character at a time, similar to getchar and putchar. putc(variable, file_pointer); putc(a, fp1); variable = getc (file_pointer); b = getc (fp2);
fprintf(), fscanf() fprintf (file_pointer, “control string”, list); fprintf (fp1, “%d %s %f”, slno, name, price); fscanf (file_pointer, “control string”, list); fscanf (fp1, “%d %s %f”, slno, name, price);
getw and putw are integer oriented functionsused to read and write integer values.