Top Banner
C PROGRAMMING TUTORIAL By Ms. P. P. Jaini
74
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to c programming

C PROGRAMMINGTUTORIAL

By Ms. P. P. Jaini

Page 2: Introduction to c programming

OUTLINE Overview History Features Role of C Compiler Flowchart Sample C Program 1 Character Set Data Types Variables C is Case Sensitive C Token Sample C Program 2 Control Statements Common Programming Errors Assignment

2

Page 3: Introduction to c programming

OVERVIEW OF C C language is

Structured

High level

Machine independent

Follows top down approach

3

Page 4: Introduction to c programming

HISTORY ALGOL

In 1960’s First language using a block structure

BCPL In 1967 Basic Combined Programming Language

B In 1970 Added feature of BCPL

4

Page 5: Introduction to c programming

CONTD…

CEvolved from ALGOL, BCPL & B

Developed between 1969 and 1973 along with Unix

Developed at AT & T’s Bell Laboratories of USA

Designed and written by Dennis Ritchie

5

Page 6: Introduction to c programming

FEATURES C is PortableThis means a program written for

one computer may run successfully on other computer also.

C is fast This means that the executable program

obtained after compiling and linking runs very fast.

C is compact The statements in C Language are generally

short but very powerful.6

Page 7: Introduction to c programming

CONTD…

Simple / Easy

The C Language has both the simplicity of High Level Language and speed of Low Level Language. So it is also known as Middle Level Language

C has only 32 Keywords

C Compiler is easily available

C has ability to extend itself. Users can add their own functions to the C Library

7

Page 8: Introduction to c programming

ROLE OF C COMPILERCompiler: converts source to object code for a specific platformLinker: resolves external references and produces the executable

module Typically C programs when executing, have four different files

Source Code – file that is created by user and the executable statements are written. This file is saved with a file extension of ‘.c’.

Header files – contains the declaration of functions and pre-processors statements. Header files have ‘.h’ as their extension.

Object files – are the output from the compilers. ‘.o’ or ‘.obj’ are the typical extension to such files.

Binary executables – are an output of the process of linking. Binary executables have ‘.exe’ as their extension.

8

Page 9: Introduction to c programming

FLOWCHART Flow charts are symbolic diagrams of operations

and the sequence, data flow, control flow and processing logic in information processing.

These charts are used to understand any working sequence of the program.

Flow char is a graphical representation of algorithm. I

An algorithm defines as the step by step procedure or method that can be carried out for solving programming problems.

9

Page 10: Introduction to c programming

CONTD…Advantages of flowchart:-

It provides an easy way of communication because any other person besides the programmer can understand the way they are represented.

It represents the data flow.

It provides a clear overview of the entire program and problem and solution. 10

Page 11: Introduction to c programming

CONTD…

It checks the accuracy in logic flow.

It documents the steps followed in an algorithm.

It provides the facility for coding.

It provides the way of modification of running program.

They shows all major elements and their relationship.

11

Page 12: Introduction to c programming

FLOWCHART SYMBOLS

12

Page 13: Introduction to c programming

CONTD… Terminator This symbol represents the beginning and

end point in a program. We use start and stop option in it.

Input / Output Symbol This symbol is used to take any input or

output in the algorithm.

Process Symbol A rectangle indicates the processing,

calculation and arithmetic operations 13

Page 14: Introduction to c programming

CONTD… Decision Symbol It is used when we want to take any decision in

the program.

Connector Symbol This symbol is used to connect the various

portion of a flow chart. This is normally used when the flow chart is split between two pages

Data Flow Symbol This symbol is used to display the flow of the

program. It shows the path of logic flow in a program. 14

Page 15: Introduction to c programming

SAMPLE C PROGRAM

main() --------------Function name { ------------Start of Program

…. …. -------- Program statements ….

} --------------- End of Program

15

Page 16: Introduction to c programming

CONTD…

#include <stdio.h>

void main ( ) { printf ( “Hello, World!\n);

}

#include <stdio.h> int main ( void ) { printf ( “Hello, World!\n” ) ; return 0 ; }

/* Filename : hello.c Description : This program prints the greeting “Hello, World!” */

16

Page 17: Introduction to c programming

17

FLOWCHART FOR HELLO.C

int main (){ printf("Hello, world!\n");}

An oval denotes either the start or the end of the program, or a haltoperation within the program (which we’ll learn about later).

A parallelogram denotes either an input operation or an output operation.

An arrow denotes the flow of the program.

Start

End

Output “Hello, world!”

Page 18: Introduction to c programming

CONTD…

CommentsText surrounded by /* and */ is ignored by computerUsed to describe program

int main()Program’s execution starts from the main functionParenthesis used to indicate a function int means that main "returns" an integer valueBraces ({ and }) indicate a block

The bodies of all functions must be contained in braces

18

Page 19: Introduction to c programming

CONTD…o Preprocessor directives

#include <stdio.h>#include <conio.h>#include <stdlib.h>#include <string.h>

The #include directives “paste” the contents of the files like stdio.h and conio.h into your source code, at the very place where the directives appear.

19

Page 20: Introduction to c programming

CONTD… These files contain information about some library

functions used in the program:stdio stands for “standard I/O”, conio stands for “console I/O”stdlib stands for “standard library”,string.h includes useful string manipulation functions.

Want to see the files? Look in /TC/include

20

Page 21: Introduction to c programming

CONTD… #define MAX_COLS 20 #define MAX_INPUT 1000

The #define directives perform “global replacements”:

every instance of MAX_COLS is replaced with 20, and every instance of MAX_INPUT is replaced with 1000

21

Page 22: Introduction to c programming

CONTD…

commonly used stdio.h functions:

printf() – Output functionSyntax:

printf(“….”) ;

scanf() – Input functionSyntax:

scanf(“format specifier”, &var,&var2…); 22

Page 23: Introduction to c programming

CONTD…

commonly used conio.h functions:

clrscr()Used to clear the screen

getch()Used to get a character from ouput screen to

come into the edit screen.

23

Page 24: Introduction to c programming

CHARACTER SET

These are the characters that C recognizes.

Letters (upper case and lower case)A B C D E F G H I J K L MN O P Q R S T U V W X Y Za b c d e f g h i j k l mn o p q r s t u v w x y z

Digits0 1 2 3 4 5 6 7 8 9

Special Characters (punctuation etc)space (also known as blank)’ " ( ) * + - / : =! & $ ; < > % ? , .ˆ # @ ˜ ‘ { } [ ] \ | 24

Page 25: Introduction to c programming

CONTD… 256 characters are allowed in C.

A – Z : 65 to 90 26a – z : 97 to 122 260 – 9 : 48 to 57 10Special symbols[ #, &, `…] 32Control characters[\n, \t . ..] 34Graphic characters 128

Total 25625

Page 26: Introduction to c programming

DATA TYPES

1] Primary Integer Float Double Character

2] Derived Arrays Pointers Structure

o C support several different types of data, which may be represented differently within the computers memory.

o Types

3] User Defined typedef enum

26

Page 27: Introduction to c programming

CONTD… Primary Data Types

Data Types Byte Format Specifier 1] char 1 %c signed char 1 %c unsigned char 1 %c

2] short 2 %d short signed int 2 %d short unsigned int 2 %u

3] int 2 %d signed int 2 %d unsigned int 2 %u 27

Page 28: Introduction to c programming

CONTD… Data Types Byte Format Specifier

4] long 4 %l

long signed int 4 %ld

long unsigned int 4 %lu

5] float 4 %f

signed float 4 %f

unsigned float 4 %uf

6] double 8 %lf

7] Long Double 10 %Lf28

Page 29: Introduction to c programming

TYPE CASTING It is used to convert on data at a time.

We can have two types of type casting. Implicit Explicit

Implicit : This converts narrow type to wider type so that use can avoid the information to the system.

Explicit : Explicit type casting is done by the programmer manually. When the programmer wants a result of an expression to be in particular type, then we use explicit type casting. This type casting is done by casting operators ‘( )’ and data type.

29

Page 30: Introduction to c programming

CONTD…

#include <stdio.h>

void main ( ) { int base, height, area; base = 5;

height =3;

area = (base * height)/2; printf ( “Area = %d \n”, area); } Output : Area = 7 ……………………. Incorrect

30

Page 31: Introduction to c programming

CONTD… #include <stdio.h>

void main ( ) { int base, height, area; base = 5;

height = 3;

area = ((float) (base * height)/2); printf ( “Area = %d \n”, area); } Output : Area = 7.5 …………………….Correct

31

Page 32: Introduction to c programming

USER DEFINED DATA TYPE

[A] Type Definition

Allows user to define an identifier that would represent an existing data type

Syntax: typedef type identifier

Eg: typedef int units;

units batch1, batch2;

32

Page 33: Introduction to c programming

CONTD…

[B] Enumerated data type

Syntax: enum identifier { value1, value2... valuen}

Eg: enum day{ Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}

33

Page 34: Introduction to c programming

VARIABLES Variable names correspond to locations in the computer's

memory Data name that may be used to store a data value It may take different values at different times during

execution Eg:

char x;char y = ‘e’;

34

Page 35: Introduction to c programming

CONTD… Rules

Must begin with a letter(), some system permits underscore as first character.

Length should be not more than 8 charactersUppercase and lowercase are significant, (i.e.) total

and TOTAL are differentVariable should not be a keywordWhite space is not allowed

35

Page 36: Introduction to c programming

C IS CASE SENSITIVE

C is case sensitive: it distinguishes between UPPER case (CAPITAL) and lower case (small) letters.

Keywords in C — for example, the keyword int — MUST be in lower case. For example:

#include <stdio.h>

int main (){ /* main */

int height_in_cm; height_in_cm = 160;

printf("My height is %d cm.\n",height_in_cm);

} /* main */36

Page 37: Introduction to c programming

C TOKENS Keywords Identifiers Constants Strings Special Symbol Operators

37

Page 38: Introduction to c programming

CONTD…

Keywords

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 goto sizeof volatile do if static while

KeywordsC uses 32 keywordhave fixed meaning and cannot be changed

38

Page 39: Introduction to c programming

CONTD… Constants

Quantity that does not change is called a constant.

TypesNumeric constants

Integer constants – 123, -33Real constants – 0.992, 3.5e2

Character constantsSingle character constants – ‘5’, ‘a’String Constants – ‘Hello’, ‘1999’

39

Page 40: Introduction to c programming

CONTD…Backslash Characters Constants

\n – Newline \b – Backspace \f – Form feed \t – Tab or horizontal tab \a – Audible alert \r – Carriage return \v – Vertical Tab \’ – Single Quote \” – Double Quote \? – Question Mark \\ - Backslash \0 - Null

40

Page 41: Introduction to c programming

CONTD…

IdentifiersNames of arrays, function and variable

OperatorsArithmeticRelationalLogicalBitwise

41

Page 42: Introduction to c programming

ARITHMETIC OPERATORS

C operation

Arithmetic operator

Algebraic expression

C expression

Addition + f + 7 f + 7 Subtraction - p – c p - c Multiplication * bm b * m Division / x / y x / y Modulus % r mod s r % s

CONTD….

42

Page 43: Introduction to c programming

CONTD…. Equality and Relational Operators

Standard algebraic equality operator or relational operator

C equality or relational operator

Example of C condition

Meaning of C condition

Equality Operators = == x == y x is equal to y

not = != x != y x is not equal to y Relational Operators > > x > y x is greater than y

< < x < y x is less than y

>= >= x >= y x is greater than or equal to y

<= <= x <= y x is less than or equal to y

43

Page 44: Introduction to c programming

CONTD….

Logical Operators:&& logical And || logical Or! logical Not

Bitwise Operators & bitwise And | bitwise Or ^ bitwise Xor ~ bitwise Not << shift left >> shift right 44

Page 45: Introduction to c programming

SAMPLE C PROGRAM 2/* Program for multiplication of two variables */

#include< stdio.h>#include < conio.h>void main(){int a,b,c;clrscr();printf(“Enter two numbers”);scanf(“%d%d”,&var1,&var2);c=a*b;printf (“\n Multiplication of two numbers is %d ”,c);getch();}

45

Page 46: Introduction to c programming

CONTD… OUTPUT:

Enter two numbers: 12 3

Multiplication of two numbers is 36

46

Page 47: Introduction to c programming

CONTROL STATEMENTS

These statements are used to control the flow of program by using these statements. We can have four types of control statements:-

decision making

case control statement or switch statement

looping / iteration statement

jump / branching statement 47

Page 48: Introduction to c programming

DECISION MAKING These statements are used when we want to

take any decision according to the condition or user requirement. These conditions are used by using ‘if’ statement. We can have four types of conditional statements

if if-else if – else if nested if

48

Page 49: Introduction to c programming

if if statement is simple decision making

statement, which is used to take any decision when the condition is true.

if (statement) { Statement; } if (expression / condition) Statement;

CONTD….

49

Page 50: Introduction to c programming

CONTD…. If-else This statement is used to make decision in C

language. If the given condition is true then the cursor will move to the true portion else it will move to the false portion.

if (condition) { Statement; } else { Statement; } 50

Page 51: Introduction to c programming

If else-if

if (condition)

{

Statement;

}

else if (condition)

{

Statement;

}

else if (condition)

{

Statement;

}

else

{

Statement;

}

51

Page 52: Introduction to c programming

SWITCH CASE / SELECT CASE

These statements are used with the replacement of if-else and these statements are used when we have multiple options or choices.

These choices can be limited and when we use switch case we can use only integer or character variable as expression.

52

Page 53: Introduction to c programming

Syntax: switch( expression){

case value-1:block-1;break;

case value-2:block-2;break;

----default:

default-block;break;

}statement -X;

53

Page 54: Introduction to c programming

LOOPING These statements are used to control the

flow of the program and repeat any process multiple times according to user’s requirement.

We can have three types of looping control statements.

while

do-while

for

54

Page 55: Introduction to c programming

CONTD…While It is an entry control loop statement, because

it checks the condition first and then if the condition is true the statements given in while loop will be executed.

SYNTAX:- Initialization; while (condition) { Statements; Incremental / decrement; }

55

Page 56: Introduction to c programming

CONTD…

Do-while

Do-while loop is also called exit control loop.

It is different from while loop because in this loop the portion of the loop is executed minimum once and then at the end of the loop the condition is being checked and if the value of any given condition is true or false the structure of the loop is executed and the condition is checked after the completion of true body part of the loop.

56

Page 57: Introduction to c programming

CONTD… SYNTAX:-

Initialization do { Statement; Increment / decrement; } while (condition)

57

Page 58: Introduction to c programming

CONTD….

For loop It is another looping statement or construct used

to repeat any process according to user requirement but it is different from while and do-while loop because in this loop all the three steps of constructions of a loop are contained in single statement.

It is also an entry control loop.

We can have three syntaxes to create for loop:-58

Page 59: Introduction to c programming

CONTD….

for (initialization; Test condition; Increment / decrement)

{ Statement; }…………………………………….for (; test condition; increment / decrement) { Statement; }………………………………………

59

Page 60: Introduction to c programming

CONTD….for (; test condition;) { Statement; Increment / decrement }

60

Page 61: Introduction to c programming

JUMPS STATEMENTS These are also called as branching statements.

These statements transfer control to another part of the program. When we want to break any loop condition or to continue any loop with skipping any values then we use these statements. There are three types of jumps statements.

Continue

Break

Goto61

Page 62: Introduction to c programming

CONTD…

Continue This statement is used within the body of

the loop. The continue statement moves control in the beginning of the loop means to say that is used to skip any particular output.

WAP to print series from 1 to 10 and skip only 5 and 7.

#include void main ( ) { int a;

62

Page 63: Introduction to c programming

CONTD…

clrscr ( ); for (a=1; a<=10; a++) { if (a= =5 | | a= = 7) continue; printf (“%d \n”,a); } getch ( ); }

63

Page 64: Introduction to c programming

CONTD…

Break This statement is used to terminate any

sequence or sequence of statement in switch statement. This statement enforce indicate termination. In a loop when a break statement is in computer the loop is terminated and a cursor moves to the next statement or block;

Example:

WAP to print series from 1 to 10 and break on 5

#include void main ( ) {

64

Page 65: Introduction to c programming

CONTD…

int a; clrscr ( ); for (a=1; a<=10; a++) { if (a= =5) break; printf (“%d \n”,a); } getch ( ); }

65

Page 66: Introduction to c programming

CONTD…Goto statement It is used to alter or modify the normal sequence

of program execution by transferring the control to some other parts of the program. the control may be move or transferred to any part of the program when we use goto statement we have to use a label.

Syntax: Forward Loop: goto label; …. …. label: statement; 66

Page 67: Introduction to c programming

CONTD…

Backward Loop: label:

statement …. …. goto label;

67

Page 68: Introduction to c programming

COMMON PROGRAMMING ERRORS Missing Semicolons

Eg: a = x+y …… is wrong c= b/d; …… is right

Misuse of SemicolonEg:

for(i = 1; i <= 10; i++); sum = sum + i;

is wrong

for(i = 1; i <= 10; i++) sum = sum + i;

is right68

Page 69: Introduction to c programming

CONTD…

Use of = instead of = = Missing Braces Missing Quotes Improper Comment Characters Undeclared Variables

And many more……

69

Page 70: Introduction to c programming

ASSIGNMENT Write a C program to swap two entered number.

Write a C program to perform all the arithmetic operations.

Write a C program to find the area of a circle, triangle and rectangle.

Write a C program to calculate the area of circle, triangle and rectangle.

Write a C program to get a number from user and print a square and cube of that number. 70

Page 71: Introduction to c programming

CONTD… Write a C program to display the greatest of

three number using if else statement.

Write a C program to find the number is positive or negative.

Write a C program to find the number is odd or even.

Write a program to display the spelling of number using switch case. 71

Page 72: Introduction to c programming

Write a C program to display the entered letter is vowel or a character.

Write a C program to display odd number from 1 to n using while loop and do while loop.

Write a C program to display even number from 1 to n using for loop.

CONTD…

72

Page 73: Introduction to c programming

QUERIES?

73

Page 74: Introduction to c programming

THANK YOU!!!

74