50
Software Development Problem Definition Analysis & Design Coding Testing and debugging Implementation Modification and maintenance

c Programming

Embed Size (px)

Citation preview

Page 1: c Programming

Software Development

Problem Definition Analysis & Design Coding Testing and debugging Implementation Modification and maintenance

Page 2: c Programming

Software Development Cont…

Problem Definitiono What is to be done?o How much is to be done?

Analysiso Interviewing the persons involvedo Question/answero Documents readingo Observation / monitoring etc.

Page 3: c Programming

Software Development Cont…

o Design• ER diagram• Data flow diagram• Condition table• System flow chart

Designo Form Design – GUI – for inputo Report Design – for outputo Database Design – to store data

Page 4: c Programming

Software Development Cont…

Codingo As per the requirement

Testing and Debuggingo To identify the position of errors.o To remove the errors.

Page 5: c Programming

Software Development Cont…

Implementation Modification and Maintenance

Page 6: c Programming

Design a program to add two numbers.

/* program to add two numbers */#include <stdio.h> //include header fileint main( ){ int a, b, sum; printf(“Enter two values: ”); //display statement scanf(“%d%d”, &a, &b); //input statement sum = a + b; printf(“The sum is: %d“, sum); //output statement return 0;}

Page 7: c Programming

Some commands:

F1 details of error & helpCtrl+F1 Detailed help of a constructAlt + F9 Compilation onlyCtrl + F9 RunAlt + F5 user / result screenF2 SaveF9 Make “exe” file on hard diskF3 to open a new or existing file

Page 8: c Programming

The text inside /* and */ is called comment or documentation.

The statement starting with # (hash sign) is called pre-processor statement.

stdio.h is a header file.o Prototype or declaration only of the library

functionso Predefined constants

Page 9: c Programming

Header file does not contain the code of library functions. It only contains the header or prototype.

A program may contain many functions, but it essentially contains a main function.

The return type of main function is kept int type. A program should return value.o 0 (zero) in case of normal termination.Non-zero in

case of abnormal termination, i.e. termination due to some error.

Page 10: c Programming

Steps of Program Execution

Pre-processing Compilation

Linking Loading Execution

Alt + F9

Ctrl+ F9

Page 11: c Programming

Pre-processing:o Pre-processing statements are processed first o All the statements starting with #(hash) sign are preprocessing

statementso eg. #include and #define

Compilation: The syntactical validity of the complete program is checkedo If there is no error the compiler generates the object code (.obj)

Linking: Symbolic Links are resolved in this phaseo A function call is called symbolic link o A function can be user defined or ready made function in the libraryo The linker substitutes the name of the function with the address of

the first instruction of the function Execution: The Instruction of object code are executed one by

one. It has four major stepso Instruction Fetch o Instruction Decodeo Operand Fetch o Operand Execute

Page 12: c Programming

Types of Errors Syntax error: When there is the violation of the

grammatical ( Syntax) rule. Detected at the compilation time.o Semicolon not placedo Standard Construct not in proper formato Identifier not declared

Linker Error: When definition or code of a program is not found.o Path of header not properly definedo Library file not foundo The function name is misspelled

Page 13: c Programming

Types of Errors Cont... Runtime error: It is generated during execution phase. Due to

mathematical or some operation generated at the run time.o Division by zeroo Square root of negative numbero File not foundo Trying to write a read only file

Logical Error: Produced due to wrong logic of program. Tough to identify and even tougher to remove.o Variables not initializedo Boundary case errors in loopso Misunderstanding of priority and associativity of operators

Page 14: c Programming

Types of Statements in C Prog.

Preprocessing Statements: Also called compiler directives. The purpose depends on the type of commands.o # include statement inserts a specified file in our programo They don't exist after compilation

Declarative Statements: Used to declare user identifier i.e. to declare data types for exampe: int a, b;o These statements do not exist in the object code.o Only used to produce symbol table

Page 15: c Programming

Types of Statements in C Prog. Cont...

Executable Statements: The statements for which the executable or binary code is generated. Foro Input/Output Statements like printf(), scanf()o Assignment Statements. The syntax is lvalue=rvalueo Conditional Statements like if(a>b) max =a; else max=b;o Looping Statements. Also called Iterative statements or

repetitive statements.• For• while • do while

o Function Call like y=sin(x);

Page 16: c Programming

Types of Statements in C Prog. Cont...

Special Statements: There are four special statementsobreakocontinueoreturnoexit

Page 17: c Programming

Keywords & Identifiers

The meaning of some words is reserved in a language which the programmer can use in predefined manner. Theses are called keywords or reserve words. For example: do, while, for, if, break, etc…

The programmer uses his words for preparing a program. These words are used to store final or intermediate results. These words are called identifiers. The programmer has to define the type of identifier he is using. For example: a, b, sum, etc.. These are two categories of identifiers.o Variable eg. int a;o Constant – literal eg #define PI 3.14

Page 18: c Programming

Rules and Conventions of Making Identifier

The first character must be an alphabet. Remaining characters may be alpha- numerals (alphabets + numeric digits):

No special character other than underscore “__” is permitted.

Space is not permitted. The maximum length is compiler defined. Reserve words can not be taken as identifiers.

Page 19: c Programming

Data Types in C Standard data type

o Simple data type• char • Int• float

o Structured/composite data type• array • struct• union

o Pointer

Page 20: c Programming

Data Types in C User Defined data type

o enumo typedef

The char holds a character or a small integer. It has two modifies:o Unsignedo Signed

The int holds a whole number. It has two types of modifiers:o Type 1:

• Signed• unsigned

o Type 2:• Short• Int• long

Page 21: c Programming

Data Types in C

The float can hold a number with fraction parts. It has three modifiers:o floato doubleo long double

Page 22: c Programming

Name Description Size Range

Char Character

Integral data type

1byte signed: -128 to 127unsigned: 0 to 255

short int (short)

Short Integer. 2bytes signed: -32768 to 32767unsigned: 0 to 65535

Int Integer 2bytes/4 bytes

signed: -32768 to 32767unsigned:- 0 to 65535

long int (long) Long integer. 4bytes signed: -2147483648 to 2147483647unsigned: 0 to 4294967295

float Floating point number. 4bytes 3.4e +/- 38 (7 digits)

double Double precision floating point number.

8bytes 1.7e +/- 308 (15 digits)

long double Long double precision floating point number.

10bytes ??

Page 23: c Programming

Character and integer data types use the same internal format. The only difference is the number of bytes allocated.

#include <stdio.h>int main( ){

char ch = 97; // char ch = ‘a’;int x = ‘A’; // int x = 65;printf(“\nCharacter: %c, Equivalent integer: %d”, ch, ch);printf(“\nEquivalent Character: %c, integer: %d”, x, x);return 0;

}

Page 24: c Programming

Operators available in C

Decreasing Priority

Associativity Operators Description

left-to-right . ( ) [ ] Highest priority operators

right-to-left ++, --, !, ~, +, -, *, &, sizeof( ) all unary operators

left-to-right * / % arithmetic operators

left-to-right + - arithmetic operators

left-to-right << >> bit shift operators

left-to-right <, <=, >, >=, relational operator

left-to-right = =, != relational operator

left-to-right & ampersand

bit wise operatorleft-to-right ^ caret

left-to-right | pipeline

left-to-right &&Logical operator

left-to-right | |

right-to-left ? : ternary/conditional operator

right-to-left =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>= assignment operator

left-to-right , sequencing operator

Page 25: c Programming

There are three types of operators available in C: unary – that requires only one operand.

o For example: &a, ++a, *a binary - that requires two operands.

o For example: a + b, a * b ternary - that requires three operands.

o For example: (a>b) ? a : b [ ? : ] Priority and associativity: The higher priority operator is operated first. If the

priority or precedence is same then associativity is applied. o a + b * c o (a + b) * co x = a + bo *a++ o a - b + co a *= b += c o a / b*c o a + b + c o x = a++ ?

Page 26: c Programming

Token

In a C source program, the basic element recognized by the compiler is the “token.”

Token is source-program text that the compiler does not break down into component elements. o keyword, identifier, constant, string-literal,

operator, punctuator

Page 27: c Programming

Operators in Details

The “/” (the division) operator:

Data type of op1 Data type of op2 Data type of result

int int int (fractional part truncated)

float int floatint float float

float float float

Page 28: c Programming

Operators in Details Modulus operator Increment / Decrement Operators ( ++, - -)

o Pre-increment ++ao Post – increment a++o Pre-decrement - -ao Post-decrement a - -

The expressions in which a single variable is incremented and decremented and used more than once, must be strictly avoided. These are confusing. Moreover, the compiler may behave in unpredictable manner.

Page 29: c Programming

Operators in Details

Assignment Operators: An assignment statement is used to assign the value of an expression to a single variable. The syntax is:

lvalue = rvalue

It can only be a single variable

a variable, a constant, an expression, function call

Page 30: c Programming

Printf()

Writes to the standard output (stdout) a sequence of data formatted as the format argument specifies. After the format parameter, the function expects at least as many additional arguments as specified in format.

The format tags follow this prototype: %[flags][width][.precision][length]specifier

Page 31: c Programming

specifier Output Example

c Character ad or i Signed decimal integer 392

e Scientific notation (mantissa/exponent) using e character 3.9265e+2

E Scientific notation (mantissa/exponent) using E character 3.9265E+2

f Decimal floating point 392.65g Use the shorter of %e or %f 392.65G Use the shorter of %E or %f 392.65o Signed octal 610s String of characters sampleu Unsigned decimal integer 7235x Unsigned hexadecimal integer 7faX Unsigned hexadecimal integer (capital letters) 7FA

p Pointer address B800:0000

n Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

% A % followed by another % character will write % to stdout.

Page 32: c Programming

flags description

- Left-justify within the given field width; Right justification is the default (see width sub-specifier).

+ Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.

(space) If no sign is going to be written, a blank space is inserted before the value.

#

Used with o, x or X specifies the value is preceded with 0, 0x or 0X respectively for values different than zero.Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written.Used with g or G the result is the same as with e or E but trailing zeros are not removed.

0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier).

The tag can also contain flags, width, .precision and modifiers sub-specifiers, which are optional and follow these specifications:

Page 33: c Programming

width description

(number)Minimum number of characters to be printed. If the value to be printed is shorter than this

number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

.precision description

.number

For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.For e, E and f specifiers: this is the number of digits to be printed after the decimal point.For g and G specifiers: This is the maximum number of significant digits to be printed.For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.For c type: it has no effect.When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.

.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument thas has to be formatted.

Page 34: c Programming

length description

h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).

lThe argument is interpreted as a long int or unsigned long int

for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.

L The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G).

Return Value: On success, the total number of characters written is returned. On failure, a negative number is returned.

Page 35: c Programming

Example/* fprintf example */#include <stdio.h>int main( ){ printf ("Characters: %c %c \n", 'a', 65); printf ("Decimals: %d %ld\n", 1977, 650000); printf ("Preceding with blanks: %10d \n", 1977); printf ("Preceding with zeros: %010d \n", 1977); printf ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100); printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416); printf ("Width trick: %*d \n", 5, 10); printf ("%s \n", "A string"); return 0; }Characters: a ADecimals: 1977 650000Preceding with blanks: 1977Preceding with zeros: 0000001977Some different radixes: 100 64 144 0x64 0144floats: 3.14 +3e+000 3.141600E+000Width trick: 10A string

Page 36: c Programming

scanf( ):scanf( ) statement is used to read data from standard input stream (stdin), the keyboard. The syntax is:scanf( format string with specifiers, variable names)The specifier list is same as that of printf( ).Example:

char x;int y;float z;scanf(“%c%d%f”, &x, &y, &z);

scanf( ) returns the number of values successfully read.

Page 37: c Programming

Expression There are two types of expressions: Arithmetic expression: Returns a value Relational / Logical / Conditional Expression: Returns

true or false if a relational expression is true, it returns numeric

value 1 if a relational expression is false, it returns numeric

value 0

Page 38: c Programming

Logical Operator

There are three logical operators && (AND), | | (OR), ! (NOT). These are used to combine the conditions.

Short circuit evaluation

Page 39: c Programming

The ‘if’ Statement

It is used to selectively execute a set of statements. The set of statements is executed, if the condition is true

s0;if (c)

s1;s2;

s0;if (c) {s1;s2;}s3;

Page 40: c Programming

if..else structure:

s0;if (c) {

s1;s2;}else {

s3;s4;}s5;

//ex6.c#include <stdio.h>int main(){

int a = 0, b = 5, c = 0;if (c=a) printf(“\n Hello”);else printf(“in world”);if (c = b) printf(“\nHello”);else printf(“\nWorld”);return 0;}

OUTPUT ?

Page 41: c Programming

Type ConversionA variable/value of one type can be converted into variable/value of another type. There are two cases: Implicit conversion: Values can be converted by assigning one expression into the other. There are two types:o widening conversiono narrowing conversion

char short int longfloat double long doubleAssignment in forward direction is widening conversion; no data is lost in it. Assignment in backward direction is called narrowing conversion; data loss is possible in this case.

char a = 10;int b, c;float d = 2.6;b = a; // widening conversion, no data lossc = d; // narrowing conversion, data loss, c gets value only 2Narrowing conversion must be type casted. c = (int)d;

Page 42: c Programming

Explicit conversion (Type Casting): Type casting is used to convert the data type of an identifier to another data type temporarily.

#inlcude <stdio.h>int main( ) {int a=11, b=2;float c;c = (float)a / b;printf(“\n%f”, c);return 0;}

Page 43: c Programming

The switch statement The C allows multiple choice of a selection of items at one level of a conditional where it is a far neater way of writing multiple if statements: switch (expression) {

case item1: statement1; break; case item2: statement2; break; case itemn: statementn; break; default: statement; break;}

Page 44: c Programming

The sizeof( ) operator: It returns the size of its argument in bytes.The argument may be: An identifier A constant A standard data type User defines data type#include <stdio.h>int main( ){ int a, b, c;

double x;

a = sizeof(int);b= sizeof( 4);c= sizeof(x);printf( “%d%d%d%”, a,b,c);return 0;

}

#include <stdio.h>

int main( ){int a, b, c;

b=10, c = 20;

a = sizeof(b + c);

printf( “%d”, a);return 0;

}

#include <stdio.h>

int main( ){int a, b, c;

b=10, c = 20;

a = sizeof(b + c);

printf( “%d”, a);return 0;

}

#include <stdio.h>

int main( )

{

int a, b, c;

b=10, c = 20;

a = sizeof(b + c);

printf( “%d”, a);

return 0;

}

Page 45: c Programming

Low Level Operators and Bit FieldsMany programs (e.g. systems type applications) must actually operate at a low level where individual bytes must be operated on.Bitwise Operators X=00000010 Table: Bitwise

operators& AND| OR^ XOR~ One's

Compliment  10  01

<< Left shift>> Right Shift

Page 46: c Programming

Shifting is much faster than actual multiplication (*) or division (/) by 2. So if you want fast multiplications or division by 2 use shifts.

#include <stdio.h>

int main() {

char x = 12, y=10, a, b, c, d;clrscr();a = x | y;printf("\n%d", a);b = x & y;printf("\n%d", b);c = x ^ y;printf("\n%d", c);d = ~x;printf("\n%d", d);return 0;

}

Page 47: c Programming

The for loopFor loop consist of two parts. Header body – C statements that are to be executed repeatedly.The header contains three sections:

o Initializationo Condition o Statement

s0;for ( s1; c; s2) s3;s4;

Page 48: c Programming

Break and continue Statement: Break is used at two places:• inside switch..case statement• inside the loopAs soon as break statement is encountered, the execution comes out of the

structure immediately. If break is inside the loop, the loop is terminated. As soon as continue statement is encountered, the execution comes to the

condition checking immediately, that is, the statements below continue are skipped.

s0;for ( s1; c1; s2) { s3;

if (c2)break;s4;

}s5;

s0;for ( s1; c1; s2) {

s3;if (c2)continue;s4;

}s5;

Page 49: c Programming

While Loop:It is an entry control indefinite type loop.

s0;while (c)s1;s2;

s0;

while (c)

{

s1;

s2;

}

s3;

s0;

while (c)

s1;

s2;

s3;

s0;

while (c);

s1;

s2;

Page 50: c Programming

do .. while :It is exit control and indefinite type loop.

Difference between while and do-while : In while the condition is checked at the beginning

and in do while the condition is checked at the last. It is possible that the stmt inside while may not be

executed even for a single time, if the condition is false for the first time. In do-while the stmt inside the loop are executed at least once.

s0;

do

s1;

while (c);

s2;