Вы находитесь на странице: 1из 108

KGiSL - iTech

KGISL ITECH

a language designed for programming computers is an artificial language designed to express computations that can be performed by a machine, particularly a computer. a series of instructions written by a programmer according to a given set of rules or conventions (syntax ). is a notation for writing programs. All PL language can be divided into three categories Problem Oriented or High Level Languages Machine Oriented or Low Level Languages Middle Level Language
KGISL ITECH 2

Machine language
Natural language of a particular computer Consists of strings of numbers(1s, 0s) Instruct computer to perform elementary operations one at a time Machine dependant

KGISL ITECH

Assembly Language
English like abbreviations Translators programs called Assemblers to convert assembly language programs to machine language. E.g. add overtime to base pay and store result in gross pay LOAD ADD STORE BASEPAY OVERPAY GROSSPAY
KGISL ITECH 4

High-level languages
To speed up programming even further Single statements for accomplishing substantial tasks Translator programs called Compilers to convert high-level programs into machine language E.g. add overtime to base pay and store result in gross pay grossPay = basePay + overtimePay
KGISL ITECH 5

Procedural Programming Languages

every program comes with a starting phase, a list of tasks and operations, and an ending stage. made up of procedures, subroutines, or methods. Fortran, Basic
requires that programmers break program structure into small pieces of code. associated with a "top-down" approach to design. C, Pascal requires the designer to specify the data structures as well as the types of operations to be applied on those data structures. a program thus becomes a collection of cooperating objects, rather than a list of instructions. C++, Java, Python
KGISL ITECH 6

Structured Programming Languages

Object-Oriented Programming Languages

A language written by Brian Kernighan and Dennis Ritchie at Bell Laboratories. C is a general-purpose computer programming language developed in 1972. A Programming language (PL) C is a set of instructions used to communicate with the computer The set of instruction written in a PL is known as program

KGISL ITECH

Evolved from two previous languages


BCPL , B

BCPL (Basic Combined Programming Language) used for writing OS & compilers B used for creating early versions of UNIX OS Both were typeless languages

KGISL ITECH

C provides:
x Efficiency, x flexibility x many

high performance and high quality s/w

and power

high-level and low-level operations middle level and small size code

x Stability x Provide

libraries

functionality through rich set of function for other professional languages like
C C++ Java
KGISL ITECH 9

x Gateway

C is used:
x System x data

software Compilers, Editors, embedded systems compression, graphics and computational geometry, utility programs operating systems, device drivers, system level routines used in application programs

x databases, x Also

KGISL ITECH

10

C systems consist of 3 parts


Environment Language C Standard Library

Development environment has 6 phases


Edit Pre-processor Compile Link Load Execute
KGISL ITECH 11

Phase 1

Editor

Disk

Program edited in Editor and stored on disk Preprocessor program processes the code Creates object code and stores on disk Links object code with libraries and stores on disk
KGISL ITECH 12

Phase 2

Preprocessor

Disk

Phase 3

Compiler

Disk

Phase 4

Linker

Disk

Primary memory Phase 5 Loader

Puts program in memory

Primary memory Phase 6 CPU

Takes each instruction and executes it storing new data values

KGISL ITECH

13

Four stages
Editing: Writing the source code by using some IDE or editor Preprocessing or libraries: Already available routines compiling: translates or converts source to object code for a specific platform source code -> object code linking: resolves external references and produces the executable module

KGISL ITECH

14

Include files Global variable and function declaration Main function Function subprogram

KGISL ITECH

15

/* A first C Program*/ #include <stdio.h> void main() { printf(Learning C Programming is easy \n"); }

KGISL ITECH

16

Line 1: #include <stdio.h> As part of compilation, the C compiler runs a program called the C preprocessor. The preprocessor is able to add and remove code from your source file. In this case, the directive #include tells the preprocessor to include code from the file stdio.h. This file contains declarations for functions that the program needs to use. A declaration for the printf() function is in this file.

KGISL ITECH

17

Line 2: void main() This statement declares the main function. A C program can contain many functions but must always have one main function. A function is a self-contained module of code that can accomplish some task. Functions are examined later. The "void" specifies the return type of main. In this case, nothing is returned to the operating system.

KGISL ITECH

18

Line 3: { This opening bracket denotes the start of the program.

KGISL ITECH

19

Line 4: printf(Learning C Programming is easy\n"); printf () is a function from a standard C library that is used to print strings to the standard output, normally your screen. The compiler links code from these standard libraries to the code you have written to produce the final executable. The "\n" is a special format modifier that tells the printf to put a line feed at the end of the line. If there were another printf in this program, its string would print on the next line.

KGISL ITECH

20

Line 5: } This closing bracket denotes the end of the program.

Note
s

C is a Case Sensitive All C statements must be terminated by a semicolon ( ; )

KGISL ITECH

21

Comment should be enclosed between /* Single Line Comment is // It is used to increase the readability of the program.

*/

Any number of comments can be given at any place in the program. Comment cannot be nested. It can be split over more than one line
KGISL ITECH 22

\n \t \r \a \\ \ \? \ \0

new line tab carriage return alert backslash double quote Question Mark Quotation Mark Null

KGISL ITECH

23

Alphabets Digits Special-symbols

Constants Variables Keywords Instruction Program

KGISL ITECH

24

A character denotes any alphabet, digit or special symbol used to represent information.

KGISL ITECH

25

The alphabets, numbers and special symbol when properly combined form constants, variables and keywords A constant is a quantity that doesnt change A variable is a name given to the location in memory where the constant is stored
KGISL ITECH 26

C constants can be divided into two major categories


Primary Constants Secondary Constants
C Constants Secondary constants

Primary Constants

Integer Constant Real Constant Character Constant

Array, Pointer Structure, Union Enum

KGISL ITECH

27

An integer constant must have at least one digit It must not have a decimal point It could be either positive or negative If no sign precedes an integer constant, it is assumed to be positive

ex., 123, -321, +78

No commas or blanks are allowed within an integer constant

KGISL ITECH

28

Real constants (RC) must have at least one digit It must have a decimal point It could be either positive or negative Default sign is positive No commas or blank are allowed within a RC
Ex., 0.0083, -0.75, +247.0

KGISL ITECH

29

A Single character constant is either a single alphabet, a single digit or a single special symbol enclosed within single quotes The maximum length of a character constant can be 1 character Eg a, 1, 5, = (Valid) asd, 12 (Invalid)

KGISL ITECH

30

It is a sequence of characters enclosed in double quotes Characters may be letters, numbers, special characters enclosed in double quotes.
Eg., Hello! 1987 ?...! X

KGISL ITECH

31

Identifiers are names given to various program elements, such as variables, functions and arrays A variable name is any combination of alphabets, digits or underscores The first character in the variable name must be an alphabet
KGISL ITECH 32

Keywords are the reserved words They cannot be used as variable names. There are only 32 keywords available in c
double else enum extern float far void if int long near register return static struct switch typedef union unsigned do goto signed while default for

auto break case char const continue short

KGISL ITECH

33

There are basically four types of instructions in C


Type declaration instruction Eg: int sum; float ave; char name,code; Input/Output instruction Eg: scanf(), printf()

KGISL ITECH

34

Arithmetic instruction

Eg : x = sum +2;
Control instruction

Eg : while do statement for statement if statement

KGISL ITECH

35

C Supports several different types of data, each of which may be represented differently within the computers memory. Basic data types are listed below: Data Type int char float double Description integer quantity single character floating point number double-precision floating point number Typical Memory 2 bytes 1 bytes 4 bytes 8 bytes

KGISL ITECH

36

A variable is a data name that used to store a data value A variable may take different values at different times during execution A variable name should be meaningful Ex: Average Total Height 1.They must begin with a letter. Some system allows _ as the first character. 2.ANSI standard recognizes a length of 31 characters. 3.Length should not be normally more than 8 characters. 4.Upper case and lower case are significant. 5.It should not be a keyword. 6.White space is not allowed.

KGISL ITECH

37

Valid
John Value X1 ph_value mark

Invalid
123 % 25th (area) group 1
KGISL ITECH 38

Declaration does two things


It tells the compilers what the variable name is It specifies what type of data it holds

Declaration of must be done before they are used in the program Syntax :
<data type> <variable name>; Eg:
int count; int num,total; double ratio;

KGISL ITECH

39

auto local variable declared within a function static local variable which exist and retain value even after control is transferred to calling function extern Global variable known to all function register Local Variable which is stored in the register static and external variables are automatically initialized to zero Automatic (auto) variables contains undefined values called garbage unless they are initialized.

KGISL ITECH

40

Initialization Syntax:
<data type> <variable name> = <value> Eg:
int num = 5;

Values can be assigned using the assignment operator =


Eg:
int num; num = 5;

KGISL ITECH

41

An operator is a symbol (+,-,*,/) that directs the computer to perform certain mathematical or logical manipulations and is usually used to manipulate data and variables. Ex: a + b

KGISL ITECH

42

1. 2. 3. 4. 5. 6. 7. 8.

Arithmetic operators Relational operators Logical operators Assignment operators Increment and decrement operators Conditional operators Bitwise operators Special operators

KGISL ITECH

43

C operation Addition(+) Subtraction (-) Multiplication(*) Division(/) Modulus(%)

Algebraic f+7 p-c bm x/y, x , x r mod s y

C f+7 p-c b*m x/y r%s

KGISL ITECH

44

Operators in expressions contained within pairs of parentheses are evaluated first. Parentheses are said to be at the "highest level of precedence." ((a + b) + c) Multiplication, division and modulus operations are applied next. If an expression contains several multiplication, division and modulus operations, operators are applied from left to right. Multiplication, division and modulus are said to be on the same level of precedence. Addition and subtraction operations are applied last. If an expression contains several addition and subtraction operations, operators are applied from left to right. Addition and subtraction also have the same level of precedence. a * b + ( c d) / f
KGISL ITECH 45

Highest to lowest
() *, /, % +, -

KGISL ITECH

46

Algebra: a(b+c)+ c(d+e)

C: a * ( b + c ) + c * ( d + e ) ; Precedence: 3 1 5 4
KGISL ITECH

2
47

/* Program using Arithmetic operator */ #include<stdio.h> #include<conio.h> void main() { int a=5,b=6; // Initializing variables int c; clrscr(); // To clear the screen c=a+b; // + operator printf(The result is : %d,c); c=b%a; // % operator printf(The result is : %d,c); }

KGISL ITECH

48

Relational Operator compares two values. Values can be any built-in C data type. The comparison involves such relationship as equal to, less than and greater than. The result of the comparison is either true or false.
KGISL ITECH 49

Operator

Meaning Is less than Is less than or equal to Is greater than Is greater than or equal to Equal to Not equal to

< <= > >= == !=

KGISL ITECH

50

Operator

Meaning Logical AND Logical OR Logical NOT

&& || !

Logical expressions are a compound relational expressions -An expression that combines two or more relational expressions Ex: if (a==b && b==c)

KGISL ITECH

51

The

AND operator ( && ) requires both relationships to be true in order for the overall result to be true. either or both of the relationships are false, the entire result is false.

If

KGISL ITECH

52

Value of the expression a 0 0 1 1 b 0 1 0 1 a && b 0 0 0 1

KGISL ITECH

53

The OR Operator ( || ) takes two logical expressions and combines them. If either or both are true, the result is true. Both values must be false for the result to be false. a 0 0 1 1 b 0 1 0 1
KGISL ITECH

a|| b 0 1 1 1
54

The ( && ) and ( II ) operators always appears between two expressions. Also known as binary operators. The NOT operator ( ! ) is a unary operator. It precedes a single logical expression and gives its opposite as a result. Example if !( marks > 50) is same as if (marks <= 50)

KGISL ITECH 55

Syntax: v op = exp; Where v = variable, op = shorthand assignment operator exp = expression Ex: x=x+3 x+=3

KGISL ITECH

56

Simple assignment operator

Shorthand operator a + =1 a - =1 a * = m+n a / = m+n a %=b

a = a+1 a = a-1 a = a* (m+n) a = a / (m+n) a = a %b

KGISL ITECH

57

1. 2.

Increment ++ Decrement -The ++ operator adds a value 1 to the operand The operator subtracts 1 from the operand Eg: ++a or a++ --a or a--

KGISL ITECH

58

Let the value of a =5 and b=++a then a = b =6 Let the value of a = 5 and b=a++ then a =5 but b=6 i.e.:
1.

a prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left a postfix operator first assigns the value to the variable on left and then increments the operand.

2.

KGISL ITECH

59

When variable is not in an expression then Preincrementing and post-incrementing have the same effect Example int c = 5; ++c; printf(%d,c); // c = 6 and c++; printf(%d,c); // c= 6

are the same


KGISL ITECH 60

int c = 5; printf(%d,++c); c is changed to 6 Then prints out 6 printf(%d,c++); Prints out 5 (printf is executed before the increment) c then becomes 6
KGISL ITECH 61

/* Program using Increment operator */ #include<stdio.h> #include<conio.h> void main() { int a=5,b; // Initializing variables clrscr(); // To clear the screen b = a++; // Post Increment operator printf(The result is : %d,b); b = ++a; // Pre Increment operator printf(The res ult is : %d,b); }

KGISL ITECH

62

main() { int c; c = 5; printf(%d\n, c); printf(%d\n, c++); printf(%d\n\n, c); c = 5; printf(%d\n, c); printf(%d\n, ++c); printf(%d\n, c); } return 0;

5 5 6

5 6 6

KGISL ITECH

63

Syntax: exp1 ? exp2 : exp3 Where exp1,exp2 and exp3 are expressions Working of the ? : Operator: Exp1 is evaluated first, if it is nonzero(1/true) then the expression2 is evaluated and this becomes the value of the expression, If exp1 is false(0/zero) exp3 is evaluated and its value becomes the value of the expression Ex: m=2; n=3; r=(m>n) ? m : n;
KGISL ITECH 64

/* Program using Conditional operator */ #include<stdio.h> #include<conio.h> void main() { int a,b,c; // Initializing variables a=5; // Assigning values b=6; clrscr(); // To clear the screen c=(a>b)?a:b; // Conditional operator printf(The result is : %d,c); }
KGISL ITECH 65

The conditional operators can be nested as shown below void main() {

int k, num = 30; k=(num>5 ? (num <=10 ? 100 : 200) : 500); printf(%d,k); }

KGISL ITECH

66

Operator

Meaning Bitwise AND Bitwise OR Bitwise exclusive OR Shift left Shift right

& | ^ << >>

KGISL ITECH

67

void main() { clrscr(); int a=5,b=6; int c; c=a&b; printf(a&&b:%d,c); c=a|b; printf(a||b:%d,c); c=a^b; printf(a^b:%d,c); int d; d=c<<1; printf(c<<1:%d,d); d=c>>1; printf(c>>1:%d,c); }

// a = 0101 , b = 0110 // c = 0100 = 4 // c = 0111 = 7 // c = 0011 = 3 // d = 0110 = 6 // d = 0001 = 1

KGISL ITECH

68

1.

Comma operator ( ,) sizeof operator sizeof( ) Pointer operators ( & and *) Member selection operators ( . and ->)

2.

3.

4.

KGISL ITECH

69

One of the essential operations performed in a C language programs is to provide input values to the program and output the data produced by the program to a standard output device. scanf, which can be used to read data from a keyboard. printf, which sends results out to a terminal.

KGISL ITECH

70

70

Each program that uses standard input / out put function must contain the statement. #include<stdio.h> at the beginning. Single character input output:
getchar() putchar()

String input and output:


gets puts

KGISL ITECH

71

71

#include<stdio.h> #include<conio.h> int main() { clrscr(); printf (Welcome to KGISL ); return 0; }

KGISL ITECH

72

#include<stdio.h> #include<conio.h> int main() { int num; printf(Enter the value of num:); scanf(%d,&num); printf(The value of num is:%d,num); getch(); }

KGISL ITECH

73

#include<stdio.h> #include<conio.h> void main() { char c; c=getchar(); putchar( c ); getch(); }

KGISL ITECH

74

#include<stdio.h> #include<conio.h> void main() { char name[10]; puts(Enter your name); gets(name); puts(Your name is:); puts(name); getch(); }
KGISL ITECH 75

%c-

Reads a single character

%f- Reads a floating point value %s- Reads a string %h- Reads a hexadecimal integer %o- Reads an octal integer %i- Reads an integer value same as %d

KGISL ITECH

76

76

KGISL ITECH

77

C program is a set of statements, which are normally sequentially executed in the order in which they appear.
Conditional statements Looping statements. Unconditional statements

KGISL ITECH

78

One of the most important parts of any language is the ability to choose to execute statements based on the value of a particular variable. To execute a single statement or group of statement.

KGISL ITECH

79

There are four types of conditional statements.


Simple if statement Ifelse statement Nested if statement Switch case

KGISL ITECH

80

If Statement
if statement is a basic control flow structure of C programming language. if statement is used when a unit of code need to be executed by a condition true or false. If the condition is true, the code in if block will execute otherwise it does nothing. Only performs an action if the condition is true.

KGISL ITECH

81

Syntax if (Condition) { statements; } If the condition, whatever it is, is true, then the statement is executed.

KGISL ITECH

82

/* Demonstration of if statement */ void main( ) { int num ; printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; if ( num <= 10 ) printf ( Number is less than 10" ) ; }

KGISL ITECH

83

Ifelse Statement
To check more than one condition. Specifies an action to be performed both when the condition is true and when it is false

Syntax: if (condition) { true block of statements; } else { false block of statements; }


KGISL ITECH 84

#include<stdio.h> void main() { int a,b; clrscr(); printf(enter values of a and b:\n); scanf(%d%d,&a,&b); if(a>b) { printf(a is greater:%d,a); } else { printf(b is greater:%d,b); } getch(); }

KGISL ITECH

85

else-if ladder

For checking more than one conditions Syntax:


if(condition-1) { /* code block if condition-1 is true */ } else if (condition-2) { /* code block if condition-2 is true */ } else if (condition-3) { /* code block if condition-3 is true */ } else { /* code block all conditions above are false */ }

KGISL ITECH

86

#include<stdio.h> void main() { int a,b,c; clrscr(); printf(enter values of a,b,c:); scanf(%d%d %d,&a,&b,&c); if(a>b)&&(a>c) { printf(a is greater); } else if(b>a)&&(b>c) { printf(b is greater); }

else { printf(c is greater); } getch(); }

KGISL ITECH

87

Nested if statement

Syntax: if(condition) { if(condition) { if statement; } else { else stmt; } } else if { else if stmt; } else { else stmt; }
KGISL ITECH 88

void main() { int a,b,c; clrscr(); printf("Enter values of a,b,c:"); scanf("%d%d%d",&a,&b,&c); if (a > b) { if (a > c) { printf("A is greater"); } else { printf("C is greater"); } }

else if (b > c) { printf("b is greater"); } else { printf("c is greater"); } getch(); }

KGISL ITECH

89

Loops Cause a section of your program to be repeated a certain number of times. The repetition continues while a condition is true. When condition becomes false, the loops ends and control passes to the statements following the loop. Types of Loops for loop while loop do while loop

KGISL ITECH 90

The for allows us to specify three things about a loop in a single line. a)Setting a loop counter to an initial value. b)Testing the loop counter to determine whether its value has reached the number of repetitions desired. c)Increasing the value of loop counter each time the program segment within the loop has been executed.

KGISL ITECH

91

The general form of for statement is as under. for ( initialization expression; test expression; increment expression) { statement 1; statement 2; . . statement n; }

KGISL ITECH

92

void main ( ) { int j; for ( j=0; j < 15; j++ ) { printf(%d\n,j); } getch( ); }

KGISL ITECH

93

Loops can also be nested. The placing of one loop inside the body of another loop is called nesting. Syntax:

for( intialization; test _condition; Increment;) { for( intialization; test_condition;increment;) { statemet; } statement; }

KGISL ITECH

94

#include<stdio.h> void main ( ) { int i, j; clrscr ( ); for (j=1; j<=4; j++) { for (i=1; i<=5; i++) { printf(*); } printf(\n);; } getch ( ); }

KGISL ITECH

95

Loops can also be nested like if statements. void main ( ) { int r, c, sum; for ( r = 1; r<= 3; r++) { for( c =1; c <= 2; c++) { sum = r + c; printf(Sum:%d,sum); } } }
KGISL ITECH 96

The while loop allows programs to repeat a statement or series of statements, over and over, as long as a certain test condition is true. The while loop is an entry-condition loop Syntax:

while (test-condition) { statement }


KGISL ITECH 97

#include<iostream.h> void main() { int i=0; clrscr(); while(i<10) { printf(%d,i); i++; } getch(); }
KGISL ITECH 98

The do-while loop is similar to the while loop, except that the test condition occurs at the end of the loop. The do-while loop is an exit-condition loop.
Syntax

do { statement } while (condition);

KGISL ITECH

99

#include<iostream.h> void main() { int i=0; do { i++; printf(%d,i); }while(i<5); getch(); }


KGISL ITECH

Unconditional statement
This statement will be executed without any condition. Goto Break Continue

KGISL ITECH

The goto statement is a jump statement which jumps from one point to another point within a function. Syntax

goto <label name>;

KGISL ITECH

Example: goto statement


#include<stdio.h> #include<conio.h> intmain() { inta=0; n: printf("\n %d",a); a++; if(a<10) { goton; } getch(); return0; }

//Label

KGISL ITECH

break statement
Causes immediate exit from the loop Used in while, for, dowhile or switch statements

continue statement
Skips remaining statements in loop body and start from the beginning of loop
Used in for loop, while , dowhile loops

KGISL ITECH

void main ( ) { int k; for ( k= -5; k < 25; k= k+5) { printf(%d,k); printf(Good day\n);; } }

KGISL ITECH

void main ( ) { int k; for ( k= -5; k < 25; k= k+5) { printf(%d\n, k); break; printf(Good day); } }

KGISL ITECH

void main ( ) { int k; for ( k= -5; k < 25; k= k+5) { printf(%d, k); conitnue; printf(Good Day); } }

KGISL ITECH

Example: break & continue statement #include<stdio.h> void main() { int i; for(i=0;i<20;i++) { if(i==10) break;

if(i%2==0) continue; } printf(%d,i); }


KGISL ITECH