C Programming Language
Rajesh Kulkarni
Recommended Text Book
Reference Text Books
Why Learn C?
Feature of C Program
1. Every c program requires a main() function
2. The execution of a function begins at ( and ends t )
3. Programs should written in lowercase and uppercase are used for defining symbolic constants.
4. All the words in a program line must be separated from other by
at least one space or tab or punctuation mark.
5. Every statement must ends with a semi colon.
6. C is a free form language
a=b;
a=b+1; can be written in one line as a=b; a=b+1;
Character Set
The Character set in C are grouped into
1.Letters A,B,C…….Z; a, b, c ……z.
2.Digits 0,1,2……..9.
3.Special characters @,#,$,^………….etc
4.White Spaces
C Tokens (KISSCO)
Smallest individual units in c programming known as Tokens
1.Keywords
2.identifiers
3.Strings
4.Special Symbols
5.Constants
6.Operators
Key words
These are pre defined words have a fixed meanings.
All key words must be written in lower case letters.
Every word in c is either a keyword or identifier
Auto break case char const
char continue default do double
else enum extern float for
goto if int long register
return short signed sizeof static
struct switch typedef union unsigned
void volatile while
Identifiers
Identifier refers to the names of variables ,functions ,and arrays.
Upper case and lower case letters are permited,but commonly lowercase letters we used.
It consists of letters and digits with letter as a first character.
Underscore also used as first letter
Constants
Constants in C refer to fixed values do not change during the execution of the program.
Integer constant: It refer to a sequence of digits, 0 through 9 preceded
by - or +. Ex: 149, -980, +45.
Real constants: the quantities which are represented by numbers
containing fractional part. Ex:0.78, 2.45.
It is also represented in exponential notation
Ex: the value 4356.78 can represented as 4.35678e3.
Single character constant: It contains a character enclosed within a pair
of single quote marks. Ex: '2' , 'a' .
String constant: It is a sequence of characters enclosed in double quotes.
Ex: "india" , "2*3", "n".
Back slash character constant (Escape sequences):
'\n' for new line
'\t' for horizontal tabulator
'\v ' for vertical tabulator
'\0' Null character.
Constants (Cont.)
Integer Constants
1.Decimal
2.Octal( Leading with 0)
3.HexaDecimal(Leading with 0x/oX)
Embedded spaces ,commas,nondigit characters are not permitted
Data Types
Data type size range
int 2 bytes -32,768 to 32,767
char 1 byte -128 to 128
float 4 bytes 3.4e-38 to 3.4e+38
double 8 bytes -1.7e-308 to1.7e+308
Variables
It is a data name that may be used to store value. Variable name may consist of letters ,digits, underscore(_) characters subject to the following conditions:
Variable must begin with letter.
Variable name should not be more than 8 characters.
Upper case and Lower case are significant.
Variable name should not be key word.
White space is not allowed.
Declaration of variables
Declaration tells to the compiler variable name with specifying data type.
a) Primary type : Syntax : data-type variable1,variable2,……..variable n;
Ex : float marks;
b) User defined type : C supports a feature known as type definition that
allows user to define an identifier.
Syntax : typedef data-type identifier;
Ex: typedef int units;
c) Enumerated data type: It contains enumeration constants represented
by identifiers.
Syntax: enum identifier { value 1,value 2,…..value n};
Ex: enum day { Monday, Tuesday,……Sunday};
d) Declaring variable as constant: The value of variable can be made to
remain constant.
syntax: const data-type variable = value;
Ex : const int max = 40;
e) Declaring variable as volatile :The value of variable may be changed
by some external reasons from out side.
Syntax : volatile data-type variable;
Ex : volatile int date ;
Declaration of Storage Classes
Automatic variable: Local variable known to only to the function in which is declared default is auto .
syntax : auto data-type variable;
Ex : auto int number;
Extern variables: Global variable known to all functions in the file. It is used to crossing files.
Syntax: extern data-type variable;
Ex: extern int number;
Static variables: Local variable, which exists and retains its value even after the control is transferred to the calling function.
Syntax : static data-type variable;
Ex : static int x;
Register variables: Local variable, which is stored in the CPU register. It is fast access variable.
Syntax : register data-type variable;
Ex : register int x;
Value can be assigned to variables using the assignment operator.
Syntax : data-type variable-name =constant;
Ex: int units =123;
Multiple assigning : Ex: x = y= z = max;
Type casting: C allows, if the operation are of different it types the lower type
is converted to the higher type to before operation proceed.
Syntax : (type-name) expression/value;
Ex: x = (int) 7.5 result = 7
Abstract data type: It is a tool which specifies the logical properties of a data type .
Syntax: abstract typedef < integer , integer > RATIONAL
Defining symbolic constants: This is useful when a constant will be used number
of places in a program.
# define symbolic-name value
Ex : #define MAX 100
# define PI 3.14159
Operators
Operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.
Expressions operators along with the variables or operands is said to be expressions.
1.Arithemetic Operators
2.Relational Operators
3.Logical Operators
4.Assignment Operators
5.Increment & Decrement Operators
6.Conditional Operators
7.Bitwise Operators
8.Special Operators
Operators (Cont.)
Operators (cont.)
Special Operators in C
C Special Conditional Expression
Associativity and Precedence Rules
Order of Evaluation
Order of Evaluation
Comments
Good CommentingChapter 11
Introduction to
Programming in C
C: A Middle-Level Language
C by Dennis ritchie at Bell in 1972
• It is a programming language closely associated with unix O.S.
Provides abstraction of underlying hardware
• operations do not depend on instruction set
• example: can write “a = b * c”, even though
LC-3 doesn’t have a multiply instruction
Provides expressiveness
• use meaningful symbols that convey meaning
• simple expressions for common control patterns (if-then-else)
Enhances code readability
Safeguards against bugs
• can enforce rules or conditions at compile-time or run-time
C…
It is an unambiguous and machine independent definition.
It is a general purpose programming language.
C is not tied to any particular hardware or system.
BCPL and B are type less languages while C is has data types.
C is single-threaded, does not offer multiprogramming, parallel operations, syncronisations, coroutines.
C
5/9 = 0
In C integer division truncates;
Any fractional part is discarded
In C % operator can not be applied on float.
In C % operator can not be applied with real operands.
% operator takes the sign of the I operand.
Mixed mode arithmetic: result is real if one of the operand is real.
C arithmetic
6/7 = 0 -6/-7 = 0
During integer division if both the operands are of same sign the result is truncated towards zero.
If one of them is negative then direction of truncation is implementation dependant. That is
-6/7 = 0 or 1 ( machine dependant)
During modulo division the sign of the result is always the sign of the first operand.
-14%3 = -2 14%-3 = 2 -14%-3 = -2
Features of C
Fast: 32 keywords and built in functions
Robust: built in functions, operators, middle level features
Efficient: data types and operators
Extensible: libraries, functions can be added
Portable: Can be run on any machine
Structured: modules, blocks make testing and debugging easier
C
Comments are used to enhance it’s readability and understanding.
Comments do not effect the execution size and speed.
Comments aid in debugging and testing.
C is a case sensitive language
\n new line character . It is like enter or carriage return key for typewriter
Structure of a C Program
• Function
function Heading(Argument list)
• Compound statement
compound statement = { …..}
{ expression statements seperated by semicolon ;}
• Comments anywhere = /*……*/
Structure of a C Program
• Documentation
nesting of comments not allowed
• Definition
symbolic constants
• Link section
links header files to source.Entire header file loaded.
• Global declaration .
• Function() { declaration part.. Exe part }
Structure…
The program will always begin by executing the main function.
The format of a C Program is
main() function starts
{……
………
………
………} function ends
Constants and Variables
Characters in C are letters, digits, special characters, white spaces
Tokens are smallest individual units of C. There are six tokens: Keywords, Identifiers, strings, special symbols, constants,Operators
Keywords: In ANSI C there are 32 keyword
Identifiers: names of variables, functions and arrays.
Strings: sequence of characters surrounded by double quotes.
keywords
Auto break case char const
char continue default do double
else enum extern float for
goto if int long register
return short signed sizeof static
struct switch typedef union unsigned
void volatile while
Constants and variables
Special symbols: @,#,$,^
Constants: Fixed values that do not change during the execution of the program.
Constants are divided as
• Numeric
Integer
Real
• Character
Single
String
Constants and variables
Integers: size is 2 to 4 bytes which is machine dependant.
Integers may be decimal(0..9), octal(0..7), hex(0..15)
Real: Fractional parts represented using mantissa and
exponent form
Single character constant: characters enclosed within a
single quote mark ‘5’, ‘x’
Printf(“%d”,’a’); Printf(“%c”,’a’); Printf(“%c”,97);
Constants and variables
String constants: characters enclosed in double quotes.
Backslash character constants: escape sequences like /n, /t, /f.
Variables
Variables are data names for data types.
They change during the execution of programs.
Variable names start with a letter or underscore.
variable length is 31 characters, usage is 8 characters.
variable name must not be a keyword.
White spaces are not allowed.
Data types
ANSI C supports four classes of data types
• Derived: arrays, functions, structures, pointers.
• User defined: typedef and enum.
• Primary: int, char, float, double.
• Empty data set: void. Itr indicates type returned by functions that generate no values
Data types.. Sizes and ranges
• Char 1 byte. -128 to 127
• Int 2 bytes. -32768 to 32767
• Float 4 bytes 3.4e-38 to 3.4e+38
• Double 8 bytes. 1.7e-308 to 1.7e+308
Preprocessor directives
#include
#include indicates to the compiler the nature of the library functions being used like printf().
Stdio.h is a header file consisting of library functions like printf() and scanf()
Printf() is a library function used to output information on to the screen.
Scanf() : a library function that accepts input from the k/b.
Preprocessor directives
Preprocessor directives are instructions to the compiler.
They begin with a # sign and can be placed anywhere in a program, but are most often placed at the beginning of a file.
#if #ifdef #ifndef #else #elif #include #define
#undef
#include “ “ OR #include<..>
#define identifier string
#define macroname macro substitution
#define RK “hi I am RK’
Preprocessor Directives
Printf(RK);
#define Yes 1
#define No 0
Printf(“%d %d %d”,Yes,No,Yes+No);
#ifndef HDR
#define HDR
#if
SYSTEM == MSDOS
#define HDR “msdos.h”
….#endif
Data types
Char 1 signed char 1 unsigned char 1
Int 2 signed int 2 unsigned int 2
short int 2 long int 4
Float 4
Double 8 long double 10
Data types
Sizeof() is a special operator which gives the size of the data
sizeof(char) 1
sizeof(int) 2
sizeof(float) 4
sizeof(double) 8
…
File.c compile file.obj link file.exe
Int data type occupies how many bytes…
.obj result in syntax errors while .exe result in linker errors.
Compilation vs. Interpretation
Different ways of translating high-level language
Interpretation
• interpreter = program that executes program statements
• generally one line/command at a time
• limited processing
• easy to debug, make changes, view intermediate results
• languages: BASIC, LISP, Perl, Java, Matlab, C-shell
Compilation
• translates statements into machine language
does not execute, but creates executable program
• performs optimization over multiple statements
• change requires recompilation
can be harder to debug, since executed code may be different
• languages: C, C++, Fortran, Pascal
Compilation vs. Interpretation
Consider the following algorithm:
• Get W from the keyboard.
• X = W + W
• Y = X + X
• Z = Y + Y
• Print Z to screen.
If interpreting, how many arithmetic operations occur?
If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single
arithmetic operation?
Compiling a C Program
Entire mechanism is usually called
the “compiler”
Preprocessor
• macro substitution
• conditional compilation
• “source-level” transformations
output is still C
Compiler
• generates object file
machine instructions
Linker
• combine object files
(including libraries)
into executable image
Compiler
Source Code Analysis
• “front end”
• parses programs to identify its pieces
variables, expressions, statements, functions, etc.
• depends on language (not on target machine)
Code Generation
• “back end”
• generates machine code from analyzed source
• may optimize machine code to make it run more efficiently
• very dependent on target machine
Symbol Table
• map between symbolic names and items
• like assembler, but more kinds of information
A Simple C Program
#include
#define STOP 0
/* Function: main */
/* Description: counts down from user input to STOP */
main()
{
/* variable declarations */
int counter; /* an integer to hold count values */
int startPoint; /* starting point for countdown */
/* prompt user for input */
printf("Enter a positive number: ");
scanf("%d", &startPoint); /* read into startPoint */
/* count down and print count */
for (counter=startPoint; counter >= STOP; counter--)
printf("%d\n", counter);
}
Preprocessor Directives
#include
• Before compiling, copy contents of header file (stdio.h)
into source code.
• Header files typically contain descriptions of functions and
variables needed by the program.
no restrictions -- could be any C source code
#define STOP 0
• Before compiling, replace all instances of the string
"STOP" with the string "0"
• Called a macro
• Used for values that won't change during execution,
but might change if the program is reused. (Must recompile.)
Comments
Begins with /* and ends with */
Can span multiple lines
Cannot have a comment within a comment
Comments are not recognized within a string
• example: "my/*don't print this*/string"
would be printed as: my/*don't print this*/string
As before, use comments to help reader, not to confuse
or to restate the obvious
main Function
Every C program must have a function called main().
This is the code that is executed
when the program is run.
The code for the function lives within brackets:
main()
{
/* code goes here */
}
Variable Declarations
Variables are used as names for data items.
Each variable has a type,
which tells the compiler how the data is to be interpreted
(and how much space it needs, etc.).
int counter;
int startPoint;
int is a predefined integer type in C.
Input and Output
Variety of I/O functions in C Standard Library.
Must include
printf("%d\n", counter);
• String contains characters to print and
formatting directions for variables.
• This call says to print the variable counter as a decimal integer, followed by a linefeed (\n).
scanf("%d", &startPoint);
• String contains formatting directions for looking at input.
• This call says to read a decimal integer and assign it to the
variable startPoint. (Don't worry about the & yet.)
More About Output
Can print arbitrary expressions, not just variables
printf("%d\n", startPoint - counter);
Print multiple expressions with a single statement
printf("%d %d\n", counter,
startPoint - counter);
Different formatting options:
%d decimal integer
%x hexadecimal integer
%c ASCII character
%f floating-point number
Examples
This code:
printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n", 43+59);
printf("43 plus 59 in hex is %x.\n", 43+59);
printf("43 plus 59 as a character is %c.\n", 43+59);
produces this output:
43 is a prime number.
43 + 59 in decimal is 102.
43 + 59 in hex is 66.
43 + 59 as a character is f.
Examples of Input
Many of the same formatting characters are
available for user input.
scanf("%c", &nextChar);
• reads a single character and stores it in nextChar
scanf("%f", &radius);
• reads a floating point number and stores it in radius
scanf("%d %d", &length, &width);
• reads two decimal integers (separated by whitespace),
stores the first one in length and the second in width
Must use ampersand (&) for variables being modified.
(Explained in Chapter 16.)
Data input and output
Library functions for input and output are getchar, putchar, scanf, printf, gets, puts
• In C there are no keyword to perform i/p and o/p. That is accomplished through library functions.
• Keyboards and printers are treated as files.
• Header file for standard input output is stdio.h
Int a;
Char b;
a = getchar(); b= getchar();putchar(a);putchar(b);
getch() does not echo character to screen.
Formatted input and output
printf(control string,arg1,arg2…);
printf(“this is %c %s”,”a string”);
%conversion character
%format specifier(c,d,e,f,g,I,o,s,u,x) %d %e %f %g %i %o
%u %x %D %E %G %O %I %X %U
%field width format specifier printf(“%10f”,num);
%field width.precision format code printf(“%12.5”,num);
ALGORITHM
Program design: At this stage define a problem and its solution.
problem specification: the program must be thoroughly understand the problem and the input output and special processing specification represent the most important information collection during this phase.
Solution: The solution method is to be developed.
Using planning tools: The solution method is described step by step when solution method had been outlined. It must be represent by using algorithm notations or flow charts symbols.
Coding: It is relatively easier to convert the algorithm into a program in a computer language i.e. C,C++.
ALGORITHM
Compiling: Translate the program into machine code. typing errors(syntax errors) are found quickly at the time of compiling the program most C implementations will generate diagnostic messages when syntax errors are detected during compilation.
Executing: Running the program the run time errors may occur during the execution of programs even though it is free from syntax errors.
Syntactic & Run time errors generally produce error messages when program executed. These are easy to find and can be corrected. The logical error which is very difficult to detect. These are existence of logically incorrect instructions. These errors can be know only after output is executed.
ALGORITHM
Testing and validation: Once program is written , a program must be tested and then validated. The program always must guarantee to produce correct results. In above stages a), b),c) are purely manual process. remaining all
stages related its computer.
ALGORITHM:
A method of representing the step by step logical procedure for solving program in natural language is algorithm
FLOWCHART
There is another way to write the steps involved in any process ,this is by making use of various symbols . The symbols form a diagram that represents the steps in a pictorial fashion similar to an algorithm. This is also very easy to understand such a diagram is flow chart.
Flowcharts help us understand the logic of an operation easily. They are good communication devices and also helps in algorithm maintenance.
The most common symbols using drawing flow charts are given below:
FLOWCHART SYMBOLS
..\cds lab theory pavan sir's.DOC
Some examples c1.doc
No comments:
Post a Comment