December 21, 2016 | Author: Chandrashekar Reddy.G | Category: N/A
C LANGUAGE PPT
By
Chandrashekar Reddy.G
[email protected] [email protected]
Contact +91406524833 +919985199433
Welcome
C
Introduction
C programming language was developed 1972 by Dennis
Ritchie in Bell Laboratories.
It‟s an offspring of “Basic combined programming” called „B‟ which was developed by Ken Thomson
B language was interpreter-based but it was very slow
So Dennis Ritchie modified the „B‟ language and named it as „C„
History… 1960
ALGOL
1967
BCPL
1970
B
1972
Traditional C
1978
K&R
1989
ANSI C
1990
ANSI/ISO C
International Group Martin Richards
Ken Thompson Dennis Ritchie Kernighan & Ritchie
ANSI Committee
ISO Committee
Benefits
C programs are efficient, fast & Highly portable
It can be written in one computer and can be run in another computer without any Modification.
Its easy for debugging, testing & maintenance because of structured programming
Functions can be used many Number of building blocks
COMPILER
A compiler is a computer program (or set of programs) that transforms source code written in a computer language (the source language) into another computer language (the target language, often having a binary form known as object code). The most common reason for wanting to transform source code is to create an executable program. The name "compiler" is primarily used for programs that translate source code from a high-level programming language to a lower level language (e.g., assembly language or machine code). A program that translates from a low level language to a higher level one is a decompiler. A program that translates between high-level languages is usually called a language translator,
DIFFERENCE BETWEEN COMPILER AND INTERPRETER 1.Compiler checks syntax of programme where as Interpreter checks the keywords of a prog. 2. compiler checks at a time all the prog, But interpreter checks simultaneously in the eidtor. 3.Interpretor provides colour coding to the prog and helps in self debugging while writing a prog.
Why
C used Widely
Pointers it allow reference to memory location
by a name
Memory allocation Allow static as well as dynamic memory location
Recursion Is a process in which a function can call itself
Bit Manipulation Allows manipulation of data in its lowest form of storage
DIFFERENCE BETWEEN STATIC AND DYNAMIC Static memory allocation: The compiler allocates the required memory space for a declared variable. By using the address of operator, the reserved address is obtained and this address may be assigned to a pointer variable. Since most of the declared variable have static memory is assigned during compilation time. Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically. If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation. memory is assined during run time.
Structure of the programming Documentation Section Link Section Definition Section Global Declaration Section Main() Function Section { Declaration Part Executable Part }
Subprogram Section (User-defined FUnctions)
ABOUT PRINTF: Printf The printf statement allows you to send output to standard out. Here is program that will help you learn more about printf: #include int main() { int a, b, c; a = 5; b = 7; c = a + b; printf("%d + %d = %d\n", a, b, c); return 0; }
ABOUT SCANF:
The scanf function allows you to accept input from standard in, which for us is generally the keyboard.
For Example: #include int main()
{ int a, b, c;
printf("Enter the first value:"); scanf("%d", &a);
printf("Enter the second value:"); scanf("%d", &b); c = a + b;
printf("%d + %d = %d\n", a, b, c); return 0;
}
Simple Programs # include # include Void main() { /*Program to Display The Content*/ clrscr(); printf(“Good Morning..! Have a Nice Day”); getch(); }
Simple Programs # include
# include Void main()
{ /*Program for Addition*/ int a,b,c;
clrscr(); printf(“Enter the value of A :”);
scanf(“%d”,&a); printf(“Enter the value of B :”);
scanf(“%d”,&b); c=a+b; printf(“The Value of C is :”,c);
}
Character Set
The Character that can be used to form words, numbers and expression depends upon the computer on which the program runs. Letters Digits Special Character White Space
,
.Comma
&
.Ampersand
.
.Period
^
.Caret
;
.Semicolon
*
.Asterisk
:
.Colon
-
.Minus Sign
?
.Question Mark
+
.Plus Sign
'
.Aphostrophe
<
.Opening Angle (Less than sign)
"
.Quotation Marks
>
.Closing Angle (Greater than sign)
!
.Exclaimation Mark
(
.Left Parenthesis
|
.Vertical Bar
)
.Right Parenthesis
/
.Slash
[
.Left Bracket
\
.Backslash
]
.Right Bracket
~
.Tilde
{
.Left Brace
-
.Underscore
}
.Right Bracket
$
.Dollar Sign
#
.Number Sign
%
.Percentage Sign
.
.
Keywords
“Keywords” are words that have special meaning to the C compiler. These keywords cannot be used as identifiers in the program
auto
double
int
struct
break
else
long
switch
case
enum
register
typedef
char
extern
return
union
const
float
short
unsigned
continue
for
signed
void
default
go to
size of
volatile
do
if
static
while
Identifiers Identifiers" are the names you supply for variables, types, functions, and labels in your program. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Rules: First character must be an alphabet (or underscore). Must consist of only letters, digits or underscore. Only first 31 characters are significant. Cannot use a keyword. Must not contain white space .
Constants Constants
Numeric Constants
Integer
Character Constants
Real
Single Character
String
Data Types
This enables the programmer to select the appropriate data type as per the need of the application ANSI C supports three classes of data types
Primary data types Derived data types
User-defined data types
Data Type
Bytes
Default Range
signed char
1
-128 to 127
Unsigned char
1
0 to 255
short signed int
2
-32768 to 32767
short unsigned int
2
0 to 65535
long signed int
4
-2147483648 to 2147483647
long unsigned int
4
0 to 4294967295
Float
4
-3.4e38 to +3.4e38
Double
8
-1.7e308 to +1.7e308
long double
10
-1.7e4932 to +1.7e493
Operator and Expressions
Operator indicates an operation to be performed on data that yields a value 1.
2. 3.
4. 5.
6. 7. 8.
Arithmetic operators (+,-,*,/,%) Relational operators (>,=,>, < >=
Relational is equal to/is not equal to
left-to-right
&
Bitwise AND
left-to-right
^
Bitwise exclusive OR
left-to-right
|
Bitwise inclusive OR
left-to-right
&&
Logical AND
left-to-right
||
Logical OR
left-to-right
?:
Ternary conditional
right-to-left
Assignment Addition/subtraction assignment Multiplication/division assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise shift left/right assignment
right-to-left
Comma (separate expressions)
left-to-right
== !=
= += *= %= ^= =
BACKSLASH CODES FOR IN CHARACTER CONSTANTS AND STRINGS
\a alert, audible alarm, bell
\b Backspace,
\f Form feed, new page,
\n New line, carriage return and line feed
\o Octal constant
\r Carriage return, no line feed,
\t Horizontal tab, tab
\v Vertical tab,
\x Hexadecimal constant,
\" Quote character
\„ Apostrophe character
\\ Backslash character
\? Question mark character
FORMAT COMMANDS FOR PRINTF() SCANF() FPRINTF(), FSCANF() SPRINTF() SSCANF()
%c a single character, char
%d a decimal number, int , %hd is for short %ld is for long
%e a floating point number, float in scientific notation, %E for 1.0E-3 %le is for double, %Le is for long double
%f a floating point number with decimal point %10.4f 10 wide .dddd %lf is for double, %Lf is for long double
%g a floating point number, %f or %e as needed, %G for capital E %lg is for double, %Lg is for long double
%h an unsigned hexadecimal short integer (scanf only), old usage
%i an integer, int %hi is for short int, %li is for long int
%n pointer to integer to receive number of characters so far, int *i
%o an unsigned octal number, unsigned int %ho and %lo for short and long
%p a pointer, void **x
%s a string ( must be null terminated ! ), use %s for scanf
%u an unsigned decimal integer (printf only), unsigned int %hu %lu
%x a hexadecimal number, %X for capital ABCDEF.
PREPROCESSOR DIRECTIVES:
#include "mine.h"search current working directory first
#include search command line directory then system
#define TRUE 1macro substitution, usually use capitals
#define min(a,b) (ac) { printf(“b is the biggest no”); } else { Printf(“c is the biggest no”); }
Nested if Construct i) If(expr) { if(expr2) statement 1; }
ii) If(expr) { if(expr1) statement1; else statement2; } else { if(expr2) statement3; else if(expr3) statement4; else statement5; }
Example for Nested if A=5 b=10 c=20
If(a>b) { if(a>c) { printf(“a is the biggest no”); } else { printf(“c is the biggest no”); } } Else if(b>c) { printf(“b is the biggest no”); } Else { printf(“c is the biggest no”); }
evencount = oddcount = 0; if ( (num % 2) == 0 ) { printf(“%d is an even number.\n”, num); ++evencount; if( (num % 4) == 0 ) printf(“It is divisible by 4\n”); if( num == 0 ) { printf(“It is zero.\n”); printf(“That isn‟t interesting.\n”); } } else { printf(“%d is an odd number.\n”, num); ++oddcount; if( (num % 9) == 0 ) printf(“It is divisible by 9\n”); else printf(“It is not divisible by 9\n”); }
Switch Construct Syntax: switch (expr) /* expr is a boolean expression { case C1: {statement0;break;} case C2: {statement1;break;} default: /* optional */ {DefaultStatement;break;} } Note : C1 & C2 represent values. It is the type of int or char only.
Example for Switch Construct Int a; Scanf (“%d”,&a); Switch (a) { case 1: printf (“you entered : %d”,1); break; case 2: printf(“you entered : %d “,2); break; case 3: printf (“you entered : %d “,3); break; default: /*optional*/ printf (“you entered except 1,2,3”); }
Char a; Scanf(“% c”,&a); Switch (a) { case „a‟: printf(“you entered : a”); break; case „b‟: printf(“you entered : b”); break; case „c‟ : printf(“you entered : c”); break; default: /* optional*/ printf(“you entered except a,b,c”); }
Loop Control Statements • Looping is deciding how many times to take certain action. • In looping process in general would include the following four steps 1. Setting and initialization of a counter. 2. Exertion of the statements in the loop. 3. Test for a specified conditions for the execution of the loop. 4. Incrementing the counter.
• Types while-statement do-while statement for-statement
While Constructs Syntax:
while (expr) Statement;
while(expr) { statement1; statement2; }
where expr is Boolean Note:
True Boolean values are any integer different from zero; False Boolean value is the integer zero.
Example for While Construct i=0;
#include
while(i main() { int *ptr1,*ptr2; int a,b,x,y,z; a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2 –6; y=6*- *ptr1/ *ptr2 +30; printf(“\nAddress of a +%u”,ptr1); printf(“\nAddress of b %u”,ptr2); printf(“\na=%d, b=%d”,a,b); printf(“\nx=%d,y=%d”,x,y); ptr1=ptr1 + 70; ptr2= ptr2; printf(“\na=%d, b=%d”,a,b); }
Pointer to arrays An array is actually very much like pointer. We can declare the arrays first element as a[0] or as int *a because a[0] is an address and *a is also an address the form of declaration is equivalent. The difference is pointer is a variable and can appear on the left of the assignment operator that is lvalue. The array name is constant and cannot appear as the left side of assignment operator.
Pointer to arrays /* A program to display the contents of array using pointer*/ main() { int a[100]; int i,j,n; printf(“\nEnter the elements of the array\n”); scanf(“%d”,&n); printf(“Enter the array elements”); for(I=0;I< n;I++) scanf(“%d”,&a[I]); printf(“Array element are”); for(ptr=a,ptr< (a+n);ptr++) printf(“Value of a[%d]=%d stored at address %u”,j+=,*ptr,ptr); } Strings are characters arrays and here last element is \0 arrays and pointers to char arrays can be used to perform a number of string functions.
File I/O in C
Files in C
In C, each file is simply a sequential stream of bytes. C imposes no structure on a file.
A file must first be opened properly before it can be accessed for reading or writing. When a file is opened, a stream is associated with the file. Successfully opening a file returns a pointer to (i.e., the address of) a file structure, which contains a file descriptor and a file control block.
Files in C
The statement: FILE *fp1, *fp2 ; declares that fptr1 and fptr2 are pointer variables of type FILE. They will be assigned the address of a file descriptor, that is, an area of memory that will be associated with an input or output stream. Whenever you are to read from or write to the file, you must first open the file and assign the address of its file descriptor (or structure) to the file pointer variable.
Opening Files
Syntax:
FILE *fp; fp=fopen(“filename”,”mode”);
The statement: fp1 = fopen ( "mydata", "r" ) ; would open the file mydata for input (reading).
Opening Files
The statement: fp = fopen ("results", "w" ) ; would open the file results for output (writing). Once the files are open, they stay open until you close them or end the program (which will close all files.)
Testing for Successful Open
If the file was not able to be opened, then the value returned by the fopen routine is NULL. For example, let's assume that the file mydata does not exist. Then: FILE *fptr1 ; fptr1 = fopen ( "mydata", "r") ; if (fptr1 == NULL) { printf ("File 'mydata' did not open.\n") ; }
Open Mode "r“ Open text file for reading only "w“ Truncate to 0 length, if existent, or create text file for writing only. "a“ Append; open or create text file only for writing at end of file "r+“ Open text file for update (reading and writing) "w+“ Truncate to 0 length, if existent, or create text file for update "a+“ Append; open or create text file for update, writing at end of file
File operation functions in C Function Name
Operation
fopen()
Creates a new file for use Opens a new existing file for use
Fclose()
Closes a file which has been opened for use
getc()
Reads a character from a file
putc()
Writes a character to a file
File operation functions in C fprintf()
Writes a set of data values to a file
fscanf()
Reads a set of data values from a file
getw()
Reads a integer from a file
putw()
Writes an integer to the file
File operation functions in C fseek()
Sets the position to a desired point in the file
ftell()
Gives the current position in the file
rewind()
Sets the position to the begining of the file
getc() & putc() #include< stdio.h > main() { file *f1; printf(“Data input output”); f1=fopen(“Input”,”w”); /*Open the file Input*/ while((c=getchar())!=EOF) /*get a character from key board*/ putc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/ printf(“\nData output\n”); f1=fopen(“INPUT”,”r”); /*Reopen the file input*/ while((c=getc(f1))!=EOF) printf(“%c”,c); fclose(f1);
getw() & putw() #include< stdio.h > main() { FILE *f1,*f2,*f3; int number I; printf(“Contents of the data file\n\n”); f1=fopen(“DATA”,”W”); for(I=1;I< 30;I++) { scanf(“%d”,&number); if(number==-1) break; putw(number,f1); } fclose(f1); f1=fopen(“DATA”,”r”); f2=fopen(“ODD”,”w”); f3=fopen(“EVEN”,”w”);
getw() & putw() while((number=getw(f1))!=EOF)/* Read from data file*/ { if(number%2==0) putw(number,f3);/*Write to even file*/ else putw(number,f2);/*write to odd file*/ } fclose(f1); fclose(f2); fclose(f3); f2=fopen(“ODD”,”r”); f3=fopen(“EVEN”,”r”); printf(“\n\nContents of the odd file\n\n”); while(number=getw(f2))!=EOF) printf(“%d%d”,number); printf(“\n\nContents of the even file”); while(number=getw(f3))!=EOF) printf(“%d”,number); fclose(f2); fclose(f3); }
Reading From Files
In the following segment of C language code:
int a, b ; FILE *fptr1, *fptr2 ; fptr1 = fopen ( "mydata", "r" ) ; fscanf ( fptr1, "%d%d", &a, &b) ; the fscanf function would read values from the file "pointed" to by fptr1 and assign those values to a and b.
End of File The end-of-file indicator informs the program when there are no more data (no more bytes) to be processed. There are a number of ways to test for the end-offile condition. One is to use the feof function which returns a true or false condition:
fscanf (fptr1, "%d", &var) ; if ( feof (fptr1) ) { printf ("End-of-file encountered.\n”); }
End of File
There are a number of ways to test for the end-offile condition. Another way is to use the value returned by the fscanf function: int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == EOF ) { printf ("End-of-file encountered.\n”) ; }
Writing To Files
Likewise in a similar way, in the following segment of C language code: int a = 5, b = 20 ; FILE *fptr2 ; fptr2 = fopen ( "results", "w" ) ; fprintf ( fptr2, "%d %d\n", a, b ) ; the fprintf functions would write the values stored in a and b to the file "pointed" to by fptr2.
Closing Files
The statements: fclose ( fptr1 ) ; fclose ( fptr2 ) ; will close the files and release the file descriptor space and I/O buffer memory.
Reading and Writing Files #include int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ; fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ; fclose (outfile) ;
Reading and Writing Files infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf ("%6.2f%2d%5.2f\n", a, b, c) ; printf ("%6.2f,%2d,%5.2f\n", e, f, g) ; } 12345678901234567890 **************************** 13.72 5 6.68 13.72, 5, 6.68
fseek() int fseek ( Stream, Offset, Whence);
where stream -- file pointer offset -- no of position in bytes whence– from position **whence must be one of the values 0, 1, or 2 Whence value: 0 Beginning of the file 1 Current position 2 End of the file.
ftell() & rewind() Ftell(); FILE *stream; long ftell (stream);
Rewind():
FILE *stream; void rewind (stream);
Pre Processing
in C
Pre Processing Refers before compiling the c program. Loads the template before compiling. Syntax #Macro Template Macro Expansion
Types of Macros Defining Macros File Inclusion Conditional Macros Special cases
Defining Macros #define (parameterlist) main() { …………… ……. }
Defining Macros Example: #include #define PI 3.14 #define AREA(radius) (PI*radius*radius) main() { float areas[3]={AREA(1),AREA(2),AREA(3)}; int count; for (count=0; count