Transcript

UNIT 2

C PROGRAMMING BASICS

What is C?

• Language written by Brian Kernighan and Dennis Ritchie

• C has been used as a general – purpose language because of its popularity

• It was written to become first “portable” language

Why use C?

• Mainly because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be: • Operating Systems • Language Compilers • Assemblers • Text Editors • Print Spoolers • Network Drivers • Modern Programs • Data Bases • Language Interpreters • Utilities

Mainly because of the portability that writing standard C programs can offer

History

• 1960 : - • ALGOL was found by International group of computer users. • COBOL was found for commercial application usage. • FORTRAN was found for scientific applications.

• In 1967: -• Basic Combined Programming Language (BCPL)• developed by Martin Richards at Cambridge University.• a single language which can program all possible applications,

• In 1970: - • a language called B was developed by Ken Thompson at AT & T’s Bell Labs.

History• In 1972: -

• Dennis Ritchie at Bell Labs developed a language with some additional features of BPCL and B called C.

• In 1978: -• Publication of The C Programming Language by Kernighan & Ritchie caused a

revolution in the computing world.• In 1983: -

• the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI C", was completed late 1988.

Why C Still Useful?• C characteristics:

Highly structured language

Handle bit-level operations

Machine independent language-highly portable

Supports variety of data types and powerful set of operators

Supports dynamic memory management by using concept of pointers• C is used to develope:

System software - Compilers, Editors, embedded systems

data compression, graphics and computational geometry, utility programs

databases, operating systems, device drivers, system level routines

there are zillions of lines of C legacy code

Also used in application programs

Programming languages • Some understandable directly by computers• Others require “translation” steps • Various programming languages

• Machine language• Assembly language• High-level language

• 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 dependent

Programming languages• Assembly Language

• English like abbreviations• Assemblers:

• Translators of programs • Convert assembly language programs to machine language.

• E.g. add overtime to base pay and store result in gross pay

LOAD BASEPAY

ADD OVERPAY

STORE GROSSPAY

Programming languages• High-level languages

• To speed up the programming process• Single statements for accomplishing substantial tasks• Compilers - convert high-level programs into machine

language

• E.g. add overtime to base pay and store result in gross paygrossPay = basePay + overtimePay

Basics of C Environment• C systems consist of 3 parts

• Environment• Language• C Standard Library

• Development environment has 6 phases Edit - Writing the source code by using some IDE or editor Pre-processor - Already available routines Compile - translates or converts source to object code for a

specific platform ie., source code -> object code Link - resolves external references and produces the executable

module Load – put the program into the memory Execute – runs the program

Basics of C Environment

Editor DiskPhase 1

Program edited in Editor and storedon disk

Preprocessor DiskPhase 2

Preprocessor program processesthe code

Compiler DiskPhase 3

Creates object code and stores on disk

Linker DiskPhase 4

Links object code with libraries and stores on disk

Basics of C Environment

LoaderPhase 5

Puts program in memory

Primary memory

CPUPhase 6

Takes each instructionand executes it storingnew data values

Primary memory

Executing a C Program

Steps involved in execution are

• Creating the program

• Compiling the program

• Linking the program with functions that are needed from the C library

• Executing the program

Executing a C ProgramEditProgram

SourceCode

Compile

ObjectCode

Link ObjectCode Executable

LibraryFiles

Basics Structure of C ProgramDocumentation section

Link section

Definition section

Global declaration section

main() function section { Declaration part Executable part }

Subprogram section (user defined function)

Simple C Program

/* A first C Program*/

#include <stdio.h>

void main()

{ printf("Hello World \n");

}

Simple C Program

• 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 print function is in this file.

Simple C Program

• Line 2: void main()

• This statement declares the main function. • 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. • "void" specifies the return type of main. In this case, nothing is

returned to the operating system.

Simple C Program

• Line 3: { • This opening bracket denotes the start of the

program.

Simple C Program

• Line 4: printf("Hello World\n");

• printf is a function from a standard C library that is used to print strings to the standard output, normally your screen.

• 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.

Simple C Program

• Line 5: } • This closing bracket denotes the end of the

program.

C Character Set• Characters are the basic building blocks in C program,

equivalent to ‘letters’ in English language• Characters can be used to form words, numbers and

expressions• Characters in C are grouped into following categories

• Letters ex:a…z,A…Z• Digits ex:0…9• Special characters ex:,,&,@,_,+,-,…..• White spaces ex:blank space

horizontal tab new line…….

C Tokens• In a passage of text, individual words and punctuation marks

are called tokens• In a C source program, the basic element recognized by the

compiler is the "token."• C Tokens are

Keywords - int, float, while Identifiers - sum, main Constants - 100, -55.5 Strings - “ABC”, “Hello” Operators - +, -, *, /, ++ Special symbols - {, },[, ]

Keywords• All keywords are reserved words have fixed meanings and

these meanings cannot be changed• Have special meaning to the compiler, cannot be used as

identifiers in our program.• Keywords serve as basic building blocks for program statement• Keywords must be written in lowercase• Displayed in BLUE color in MS Visual C++

Some KeywordsKeywords

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

Identifiers • Refer to the names of variables, functions and arrays• User defined names and consist of a letters and

digits, with a letter as a first character

Rules for Identifiers• First character must be an alphabet• Must consist of only letters, digits and underscore• Only first 32 characters are significant• Cannot use a keyword• Must not contain white space • Case sensitive-Identifier Sub differ from sub

Identifiers

Examples of legal identifier:

Student_age, Item10, counter, number_of_character

Examples of illegal identifier

Student age (embedded blank)

continue (continue is a reserved word)

10thItem (the first character is a digit)

Principal+interest (contain operator character +)

1. Avoid excessively short and cryptic names such as x or wt. Instead,

use a more readable and descriptive names such as student_major

and down_payment.

2. Use underscores or capital letters to separate words in identifiers

that consist of two or more words. Example, student_major or

studentMajor are much easier to read than studentmajor.

Recommendations for Constructing Identifiers

Constants• Constants refers to fixed values that do not change during the

execution a program

Types of ConstantsNumeric Constants

Integer Constants - 234, 045, 0x2A, 0X3B Real Constants - 2.345, 0.64e-2

Character Constants

Single Character Constants ‘5’, ‘A’ String Constants “Hello”

Integer Constant

Positive or negative whole numbers with no fractional part

Optional + or – sign before the digit.

It can be decimal (base 10), octal (base 8) or hexadecimal (base 16)

Hexadecimal is very useful when dealing with binary numbers

Example:

const int MAX_NUM = 10;

const int MIN_NUM = -90;

const int Hexadecimal_Number = 0xf87;

Rules for Decimal Integer Constant

1. Decimal integer constants must begin with a nonzero decimal digit, the only exception being 0, and can contain decimal digital values of 0 through 9. An integer that begins with 0 is considered an octal constant

2. If the sign is missing in an integer constant, the computer assumes a positive value.

3. Commas are not allowed in integer constants. Therefore, 1,500 is illegal; it should be 1500.

Example of legal integer constants are –15, 0, +250 and 7550

Example of illegal constants0179 is illegal since the first digit is zero

1F8 is illegal since it contains letter ‘F’

1,700 is illegal since it contains comma

Floating Point Constant

• Positive or negative decimal numbers with an integer part(optional), a

decimal point, and a fractional part (optional)

Example 2.0, 2., 0.2, .2, 0., 0.0, .0

• It can be written in conventional or scientific way

• 20.35 is equivalent to 0.2035E+2 (0.2035 x 102 )

• 0.0023 is equivalent to 0.23e-2 (0.23 x 10-2)

• E or e stand for “exponent”

• In scientific notation, the decimal point may be omitted.

Example: -8.0 can rewritten as -8e0

Floating Point Constant

• C support 3 type of Floating-point: float (4 bytes), double (8 bytes), long double (16 bytes)

• By default, a constant is assumed of type double

• Suffix f(F) or l(L) is used to specify float and long double respectively

Example:const float balance = 0.125f;const float interest = 6.8e-2Fconst long double PI = 3.1412L;const long double planet_distance = 2.1632E+30l

• A character enclosed in a single quotation mark

• Example:• const char letter = ‘n’;• const char number = ‘1’;• printf(“%c”, ‘S’);

• Output would be: S

How to write a single quotation mark?‘’’ is ambiguous, so escape character – back slash \Example:

‘\’’

Character Constants

String Literals

• A sequence of any number of characters surrounded by double quotation marks.

• Example:• “Human Revolution”

• How to write special double quotation mark?• “”” is ambiguous, so use escape character

• Example: printf(“He shouted, \“Run!\””);output: He shouted, “Run!”

- The escape character along with any character that follow it is called Escape Sequence

Backslash Character Constants

Escape Sequence

Name Meaning

\a Alert Sounds a beep

\b Back space Backs up 1 character

\f Form feed Starts a new screen of page

\n New line Moves to beginning of next line

\r Carriage return Moves to beginning of current line

\t Horizontal tab Moves to next tab position

\v Vertical tab Moves down a fixed amount

\\ Back slash Prints a back slash

\’ Single quotation Prints a single quotation

\” Double quotation Prints a double quotation

\? Question mark Prints a question mark

Backslash Character Example

Program

#include<stdio.h>void main(){printf("\nabc");printf("\rdef");printf("\bghi\n");printf("Hai\tHello");}

Output

deghiHai Hello

Variables• A variable is a data name used for storing a data value• The value may be changed during program executionRules for defining variables• Must begin with a character• Should not be a C keyword• May be combination of lower and upper characters• Should not start with a digit• Maximum characters upto 31 characters

ExampleSum, avg_wt, item

Declaration of Variables• Syntax for declaring a variable is as follows

data-type v1,v2,….vn;

Example

int i,j,sum;float avg;double ratio;unsigned int fact;

DATATYPE• Datatype is the most important attributes of an identifier. It

detemines the possible values.• Classification of Datatypes

-Basic Datatypes-Derived datatypes-User-defined datatypes

Basic/Primitive Datatypes:Character (char)Integer (int)Single-precision floating point (float)Double-precision floating point (double)No value available (void)

Derived Datatypes:Array type (char[], int[])Pointer type (char*, int*)Functiontype (int(int,int), float(int))

• User-defined datatypesIt provides flexibility to the user to create new datatypes.

Newly created called User-defined datatypes.StructureUnionEnumeration

Syntax: data_type variable_name

Example:int age;char ch;float avg;int a,b,c;

Data Types Initializing Variables• Variables declared can be assigned or initialized using an assignment

operator ‘=‘Syntax:

variable_name=constant;or

data_type variable_name=constant;Example:

int age; char ch=‘A’;age=10; float avg=10.5;

Data Types in CType Keyword

Bytes

Range

character char 1 -128...127

integer int 2 -32768...32767

short integer short 2 -32768...32767

long integer long 4 -2,147,483,648...2,147,438,647

long long integer

long long 8-9223372036854775808 … 9223372036854775807

unsigned character

unsigned char 1 0...255

unsigned integer

unsigned int 2 0...4,294,967,295

unsigned short integer

unsigned short 2 0...65535

unsigned long integer

unsigned long 4 0...4,294,967,295

single-precision float 4 1.2E-38...3.4E38double-

precisiondouble 8 2.2E-308...1.8E308

Expressions• Operands

It specifies an entity on which an operation is to be performed. It may be a variable name, a constant, a function call or a macro name

eg: a=printf(“Hello”)+2• Operators

It specifies the operation to be applied to its operands.

Simple Expression and Compound Expression

• An Expression has only one operator called Simple expression

eg: a+2

• An Expression has more than one operator called Compound Expression.

eg: b=2+3*5

Properties Of Operators• Precedence• AssociativityPrecedence:• Priority allotted to the operator• Each operator in C has a precedence associated with it.• In compound expression, if the operator involved

different precedence, the operator of highest precedence operates first.

Ex: 8+9*2-10=8+18-10=26-10=16

Associativity: • Expression having operators with equal precedence • associativity property decides which operation is

performed first• In compound expression, when several operators of

the same precedence appear together, the operators are evaluated according to their associativity.

Types: Left to Right Right to left 12*4/8%2 x=8+5%2

= 48/8%2 =8+1 = 6%2 =9

= 0

• Operators has same precedence- same associativity

• If operators are left-to-right, applied in a left-to-right order

• If operators are right-to-left, applied in a right-to-left order

• Multiplication and division operators are left-to-right associative

Operators• An operator is a symbol that tells the computer to perform

certain mathematical or logical manipulations

Classification of Operators:

Number of operands on which an operator operates

The role of an operator

Classification based on Number of operands • Unary- it operates on only one operand

Eg: &, sizeof operator, !, ~, ++, --• Binary – it operates on two operands

eg: *, /, <<, ==,&&, &• Ternary- it operates on three operands

eg: ?:

Classification based on Role of Operator

Arithmetic Operators +, -, *, /, %Relational Operators <, <=, >, >=, ==, !=Logical Operators &&, ||, !Assignment Operators =Increment and Decrement Operators ++,--Conditional Operators ?=Bitwise Operators &,|, ^, <<, >>Special Operators ,, sizeof, &, * ., ->

Arithmetic OperatorsC Operation Algebraic C

Addition (+) f + 7 f + 7

Subtraction (-) p – c p – c

Multiplication (*) bm b * c

Division (/) x / y x / y

Modulus (%) r mod s r % s

Arithmetic Operators ExampleProgram#include <stdio.h>#include <conio.h>void main(){int x,y, a,s,m,d,r;clrscr();printf(“Enter two numbers:”);scanf(“%d%d”,&x,&y); a = x + y; printf(“a = %d\n",a); s = x - y; printf(“s = %d\n",s); m = x * y; printf(“m = %d\n",m);

d = x / y; printf(“d = %d\n",d); r = x % y; printf("r = %d\n",r);}

OutputEnter two numbers:10 20a = 30s = -10m = 200d = 0r = 10

Binary Arithmetic operators• It is used in 3 different modes

Integer mode

Relational Operators• Greater than >• Less than <• Greater than or equal to >=• Less than or equal to <=• Equal to ==• Not equal to !=

Condition true return 1Condition false return 0

Relational Operators ExampleProgram#include<stdio.h>#include<conio.h>void main(){int x,y,r;clrscr();printf(“Enter 2 nos. x & y:”);scanf(“%d%d”,&x,&y);r=(x==y);printf("%d\n",r);r=(x!=y);printf("%d\n",r);r=(x>y);printf("%d\n",r);r=(x>=y);printf("%d\n",r);

r=(x<y);printf("%d\n",r);r=(x<=y);printf("%d\n",r);}

Output Enter 2 nos. x & y: 10 20

010011

Logical Operators

Operator Example Meaning

&& (Logical AND)(Condition1) &&

(Condition2)Both conditions should

satisfy to proceed

|| (Logical OR)(Condition1) || (Condition2)

Either one condition satisfied proceed to

next operation

! (Logical NOT) !(Condition1)The condition not

satisfied proceed to next operation

Logical Operators

Example

if ((x>20) && (x<100)) printf("x is inside open interval 20-

100");

if ((x<5) || (x>20)) printf("x is not inside closed interval 5-20");

if (!(x>20)) printf("x is smaller or equal to 20");

Logical Operators Example//Greatest of 3 numbers using

logical operators

#include<stdio.h>#include<conio.h>void main(){int x,y,z;clrscr();printf(“Enter 3 nos. x ,y,z:”);scanf(“%d%d%d”,&x,&y,&z);if((x>y)&&(x>z)) printf(“x is greatest”);if((y>x)&&(y>z)) printf(“y is greatest”);if((z>x)&&(z>y)) printf(“z is greatest”); }

Output

Enter 3 nos. x ,y,z: 40 20 30x is greatest

Enter 3 nos. x ,y,z: 10 40 30y is greatest

Enter 3 nos. x ,y,z: 10 20 30z is greatest

Assignment operators

Operator Example Meaning

= a = b a = b

+ = a + = b a = a + b

- = a - = b a = a – b

* = a * = b a = a * b

/ = a / = b a = a / b

% = a % = b a = a % b

Increment/Decrement operators

Operator Example Meaning

++ a++ First does the operation and increments the value

+ + ++a First Increments the value and does the operation

-- a--First does the operation

and decrements the value

-- --aFirst decrements the value and does the

operation

Increment/Decrement operators

Programvoid 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);

}

Output

556

566

c=10x=c++ + ++c;x=? C=?

Conditional OperatorConditional Operator (?:) is ternary operator (demands 3 operands), and is used in certain situations, replacing if-else condition phrases. Conditional operator’s syntax is:

condition?expression1:expression2;

If condition is true, expression1 is executed. If condition is false, expression2 is executed.

Example:

int a, b, c;...c = a > b ? a : b; // if a>b "execute" a, else b and

assign the value to c

Bitwise Operators

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ One’s Complement

<< Left Shift

>> Right Shift

Bitwise Operators ExampleLet A=0x56 and B=0x32

A & B ( Bitwise AND )0 1 0 1 0 1 1 00 0 1 1 0 0 1 0---------------------0 0 0 1 0 0 1 0 ---------------------

A ^ B ( Bitwise XOR )0 1 0 1 0 1 1 00 0 1 1 0 0 1 0---------------------0 1 1 0 0 10 0---------------------

A | B ( Bitwise OR )0 1 0 1 0 1 1 00 0 1 1 0 0 1 0---------------------0 1 1 1 0 1 1 0 ---------------------

~ A ( Complement )0 1 0 1 0 1 1 0---------------------1 0 1 0 1 0 0 1---------------------

Bitwise Operators ExampleLet A=0x56

A << 2 ( Left Shift )

0 1 0 1 0 1 1 0 << 2 0 1 0 1 0 1 1 0 0 0 ( 0x158 )

A >> 2 ( Right Shift )

0 1 0 1 0 1 1 0 >> 1 0 1 0 1 0 1 1 ( 0x2B)

NOTE: For multiply given number by two, left shifted by one time, i.e., a<<1 For divide given number by two, right shifted by one time, i.e., a>>1

Bitwise Operators ExampleWrite a program to shift inputed data by three bits left and rightProgramvoid main(){ int x,y; clrscr(); printf(“Enter value of x:”); scanf(“%d”,&x); y=x<<3; printf(“Left shifted data=%d”,y); printf(“Right shifted data=%d”,x>>3);}Output: Enter value of x:16

Left shifted data=128Right shifted data=2

Special Operators• C supports some special operators such as comma operator, size of

operator, pointer operators (& and *) and member selection operators (. and ->).

• The size of and the comma operators are discussed here. The remaining operators will see in pointer chapter

Comma Operator• The comma operator can be used to link related expressions

together. A comma-linked list of expressions are evaluated left to right and value of right most expression is the value of the combined expression.

Example value = (x = 10, y = 5, x + y); for (n=1, m=10, n <=m; n++,m++) t = x, x = y, y = t;

Special Operators

Sizeof Operator• The operator sizeof gives the size of the data type or variable in

terms of bytes occupied in the memory. The operand may be a variable, a constant or a data type qualifier.

• The size of operator is normally used to determine the lengths of arrays and structures when their sizes are not known to the programmer. It is also used to allocate memory space dynamically to variables during the execution of the program.

Example int sum;m = sizeof(sum); 2

n = sizeof(long int); 4 k = sizeof(235L); 4

ExpressionsArithmetic Expressions

• An expression is a combination of variables constants and operators written according to the syntax of C language.

Algebraic Expression

C Expression

a x b – c a * b – c

(m + n) (x + y) (m + n) * (x + y)

3x2 +2x + 1 3*x*x+2*x+1

Expressions

Evaluation of Expressions • Expressions are evaluated using an assignment statement of the

form Variable = expression; Variable is any valid C variable name. The expression is evaluated first and then replaces the

previous value of the variable on the left hand side. All variables used in the expression must be assigned values

before evaluation is attempted.

Examplex = a * b – c y = b / c * a z = a – b / c + d;

Decision Making - Branching• Decision making statements are used to skip or to execute a group of

statements based on the result of some condition.

• The decision making statements are,

− simple if statement

− if…else statement

− nested if

− else … if ladder

− switch statement

− goto• These statements are also called branching statements

Simple if statementSyntax:

if(condition){Statements;}

if(condition)

Statements;

False

True (Bypass)

Simple if - Example# include <stdio.h> void main () {

int number;

printf("Type a number:");

scanf("%d",&number);

if (number < 0)

number = -number;

printf ("The absolute value is %d",number);

}

Output

Type a number -50The absolute value is 50

if - else statementSyntax:

if(condition){True block statements;}else{False block statements;}

if(condition)

True Block Statement

False

True

False Block Statements

if – else Example# include <stdio.h>

void main ()

{

int num;

printf ("Type a number:");

scanf ("%d", &num);

if (number < 0)

printf(“The number is negative”);

else

printf(“The number is positive”);

}

Output

Type a number 50The number is positive

if – else Example#include<stdio.h>void main(){Int num;printf ("Enter a number:");scanf ("%d",&num);if (num%2==0) printf ("The number is EVEN.\

n");else printf ("The number is ODD.\n");}

Output

Enter a number 125The number is ODD

Nested if Statement• if statement may itself can contain another if statement is known as nested if statement.Syntax:

if(condition1){

if(condition2){

True block statement of condition1 & 2;}else{

False block statement of condition2;}

}else{

False block statements of condition1;}

Nested if Statementcondition1

True Block Statements of condition 1 & 2;

False

True

False Block Statements of condition 1;

if(condition2)

True

False Block Statements of condition 2;

False

Nested if Example# include <stdio.h>void main(){ int n1,n2,n3,big; printf (“Enter 3 numbers:"); scanf ("%d %d %d", &n1,&n2,&n3); if (n1 > n2) {

if(n1 > n3)big = n1;

elsebig = n3;

} if(n2 > n3)

big = n2; else

big = n3; printf(“The largest number is: %d”,big);}

Output

Enter 3 numbers:10 25 20The largest number is: 25

Else - if Ladder StatementSyntax

if (condition1)

statement block 1;

else if (condition2)

statement block 2;

else if (condition3)

statement block 3;

:

:

else if (condition)

statement block n;

else

default statement;

Else - if Ladder StatementIf(condition1)

Default Statements;

True

False

Statements1;

Else if(condition2)True

Statements2;

False

Else if(condition3)

Statements3;

False

True

Else - if Ladder Example#include <stdio.h>void main () { int mark; printf ("Enter mark:"); scanf ("%d", &mark); if (mark <= 100 && mark >= 70)

printf ("\n Distinction"); else if (mark >= 60)

printf("\n First class"); else if (mark >= 50)

printf ("\n Second class"); else

printf ("Fail"); }

Output

Enter mark: 75Distinction

Switch StatementSyntaxswitch ( expression ){

case value1: program statement;......break;

case value2: program statement;.......break;

…….…….

case valuen: program statement;.......break;

default: program statement;.......break;

}

Switch StatementSwitch (Expression)

Case 1 Statements

Case 2 Statements

Case 3 Statements

Case 4 Statements

Switch Statement Example#include <stdio.h> void main () { int num1, num2, result; char operator; printf ("Enter two numbers:"); scanf ("%d %d", &num1, &num2); printf ("Enter an operator:"); scanf ("%c", &operator); switch (operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*':

result = num1 * num2;

break;       case '/':

if (num2 != 0) result = num1 / num2;break;

     default:          printf ("\n unknown operator");          break; } printf (“Result=%d", result);}

Output

Enter two numbers:10 20Enter an operator:+Result=30

Switch Statement Example#include<stdio.h>#include<conio.h>#include<string.h>void main(){char st[100];int i,count=0;clrscr();printf("Enter line of text:");gets(st);for(i=0;st[i]!='\0';i++){ switch(st[i]) {case 'a': count++; break;case 'e': count++; break;

case 'i': count++; break;case 'o': count++; break;case 'u': count++; break;}}printf("\n Number of vowels: %d",count);getch();}

Output

Enter line of text: Hello WorldNumber of vowels: 3

goto statement•The goto statement used to transfer the program control unconditionally from one statement to another statement.•The general usage is as follows:

goto label; Label:………… …………

.............. …………………… …………………… …………

Label: Statement; goto label; …………

•The goto requires a label in order to identify the place where the branch is to be made. •A label is a valid variable name followed by a colon.

goto statement example #include <stdio.h> void main () {

int n, sum = 0, i = 0;

printf ("Enter a number:");

scanf ("%d", &n);

inc: i++;

sum += i;

if (i < n)goto inc;

printf ("\n 1+2+3+…+%d = %d",n,sum)

}

Output

Enter a number:5

1+2+3+…+5=15

Looping statements• The test may be either to determine whether the i has repeated the

specified number of times or to determine whether the particular condition has been met.

• Type of Looping Statements are

• while statement

• do-while statement

• for statement

while statement

Syntax

while (test condition) {

body of the loop; }

While(test condition)

Body of the i;

False

True

while statement example#include<stdio.h>void main(){int n,x,sum=0;printf("Enter a number: ");scanf("%d",&n);while(n>0){x=n%10;sum=sum+x;n=n/10;}printf("Sum of digits of a number=%d",sum);}

OutputEnter a number: 275Sum of digits of a number=14

while statement example#include<stdio.h>void main(){int num,r,sum=0,temp;printf("Enter a number: ");scanf("%d",&num);temp=num;while(num!=0){ r=num%10; sum=sum+(r*r*r); num=num/10;}

if(sum==temp) printf("%d is an Armstrong number“

,temp);else printf("%d is not an Armstrong number“

,temp);}

OutputEnter a number: 275275 is an Armstrong number

Enter a number: 153153 is an Armstrong number

do..while statement• Since the body of the i is executed first and then the i condition is

checked we can be assured that the body of the i is executed at least once.

Syntax do{

body of the loop; } while (test condition);

do..while statement

While(test condition)

Body of the loop

False

True

do

do..while statement example#include<stdio.h>void main(){ int num=0, rev_num=0; printf(“Enter the number:”); scanf(“%d”,&num); do { ld=num%10; rev_num=rev_num*10+ld; num=num/10; } while(num>0); printf(“\nReversed number is %d”,rev_num);}

OutputEnter the number:275Reversed number is 572

while and do..while comparisonWhile Do…while

1) Syntax:

while(condition)

{

Body of the loop

}

1) Syntax:

do

{

Body of the loop

}while(condition);

2) This is decision making and

looping statement

2) This is also -decision

making and looping statement

3) This is the top tested loop3) This is the bottom tested

loop

4)Loop will not be executed if

the condition is false in first

check

4) Loop will be executed

atleast once even though the

condition is false in first check

for statement■ The for loop is most commonly and popularly used looping statement in C. The

for loop allows us to specify three things about the loop control variable i in a

single line. They are,

■ Initializing the value for the i

■ Condition in the i counter to determine whether the loop should continue or

not

■ Incrementing or decrementing the value of i counter each time the program

segment has been executed.Syntax

for(initialization; test condition;increment/decrement){

body of the loop; }

for statement

test condition

Initialization;

False

True

Increment/Decrement;

Body of the loop

for statement example// Number 1 to 10 divisible by 2 but not

divisible by 3 and 5

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

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

{ if(i%2==0&&i%3!=0&&i%5!=0)

printf("%d\n",i);}

}

Output

248

for statement example//12+22+32+…. n2

#include<stdio.h> //<math.h>void main(){ int n, i,sum=0; printf(“Enter the number:”); scanf(“%d”, &n); for(i=1;i <= n;i++) {

sum = sum + i*i; //pow(i,2)

} printf(“Sum of series=%d”,sum);}

Output

Enter the number:5Sum of series=55

break statement■ Sometimes while executing a loop it becomes desirable to skip a part of

the loop or quit the loop as soon as certain condition occurs.

■ For example consider searching a particular number in a set of 100 numbers. As soon as the search number is found it is desirable to terminate the loop.

■ C language permits a jump from one statement to another within a loop as well as to jump out of the loop.

■ The break statement allows us to accomplish this task. A break statement provides an early exit from for, while, do and switch constructs.

■ A break causes the innermost enclosing loop or switch to be exited immediately.

break statement#include<stdio.h>void main(){ int mark, i=0,sum=0; float avg; printf(“Enter the marks, -1 to end:”); while(1) { scanf(“%d”, &mark); if(mark == -1) break; sum+=mark; i++; } avg=(float)sum/i; printf(“\nThe average marks is: %f”, avg);}

Output

Enter the marks, -1 to end:55221166-1The average marks is:38.500000

continue statement■During loop operations it may be necessary to skip

a part of the body of the loop under certain conditions.

■Like the break statement C supports similar statement called continue statement.

■The continue statement causes the loop to be

continued with the next iteration after skipping any statement in between.

continue statement#include < stdio.h >void main() { int i, num, sum=0; printf(“Enter the integer:”); for (i = 0; i < 5; i++) { scanf(“%d”, &num); if(num < 0) { printf(“You have entered a negative number\n”); continue; } sum+=num; } printf(“Sum of positive numbers entered = %d”,sum); }

OutputEnter the integer:11 22 33 -1You have entered a negative number44Sum of positive numbers entered =110

break and continue comparisonBreak Continue

1) Syntax:break;

1) Syntax:continue;

2) Takes the control to outside of the loop

2) Takes the control to beginning of the loop

3) It is used in switch statement

3) It is not used in switch statement

4) Example:for(i=0;i<n;i++){

if(i==3) break;

}

4) Example:for(i=0;i<n;i++){

if(i==3) continue;

}

Input and Output Functions

Input and Output Functions

Unformatted Functions

Formatted Functions

scanf()printf()

getch()getche()getchar()gets()putch()putchar()puts()

Formatted FunctionsFormatted Input:

• Input data is arranged in a particular format

• I/P values are taken by using scanf function

• Syntax:

• scanf(“control string”,arg1,arg2…argn) ;

control string - includes format specifications and optional number

specifying field width and the conversion character %

arg1,arg2,… - address of locations where the data are stored

Example: scanf(“%3d%2d”,&a,&b);

An Example Program# include<stdio.h>#include<conio.h>void main() {

int num1, num2; clrscr();printf (“Enter two values:”) ;scanf(“%3d%4d”, &num1, &num2);printf (“\nThe Entered Values are:%d %d”, num1, num2) ;getch();

}

Output 1:

Enter two values: 1342 2422

The Entered Values are: 134 2

Output 2:

Enter two values: 134 2422

The Entered Values are: 134 2422

An Example Program# include<stdio.h>#include<conio.h>void main ( ) { float n1, n2, n3; clrscr(); printf (“Enter three values:”) ;scanf(“%f%f%f”, &n1,&n2,&n3);printf (“\nThe Entered Values are:%f\t%f\t%f”, n1, n2, n3) ;getch(); }

Output:Enter three values: 123.44 4.7 678

The Entered Values are:123.440000 4.700000 678.000000

An Example Program#include <stdio.h>#include <conio.h>void main(){float c, f;clrscr();printf("Enter temp in Centigrade: ");scanf("%f",&c);f = ( 1.8 * c ) + 32;printf("Temp in Fahrenheit: %0.2f",f);getch();}

Output:

Enter temp in Centigrade: 95.6

Temp in Fahrenheit: 204.08

An Example Program# include<stdio.h>#include<conio.h>void main ( ) { char s1[10],s2[10]; clrscr(); printf (“Enter two strings:”) ;scanf(“%3s%2s”,s1,s2);printf (“\nThe Entered Values are:%s\t%s”,s1,s2) ;getch(); }

Output:Enter two strings : hello world

The Entered Values are:hel lo

Formatted FunctionsFormatted Output:

• printf statement displays the information required to user

with specified format

• Syntax:

printf(“control string”,arg1,arg2…argn) ;

control string - field format which includes format

specifications and optional number specifying field width and

the conversion character %, blanks, tabs and newline.

arg1,arg2,… - name of the variables

Example: printf(“%d\t%f\n”,sum1,sum2);

Format for various outputFlag output justification

+ (right justification) - (left justification)Width Specifier minimum field width for an output value

TYPE FORMAT EXPLANATION

Integer %wd w-width

Float %w.cf w-widthc-no. of digits after decimal point

String %w.cs w-width of total charactersc-no. of characters to display

Example• INTEGERprintf(“%d”,12345); 12345printf(“%3d”,12345); 12345printf(“%7d”,12345); 12345 printf(“%-7d”,12345); 12345• FLOATprintf(“%f”,123.45); 123.450000printf(“%4.2f”,123.45); 123.45printf(“%9.3d”,12345); 123.450• STRINGprintf(“%s”,”Hello World”); Hello Worldprintf(“%6.2s”,”Hello World”); Heprintf(“%1.2s”,”Hello World”); He

Input / Output functions#include<stdio.h> void main() {

int i;float f;char c;double d;printf("Enter value for i,f,c,d:");scanf("%d %f %c %lf",&i,&f,&c,&d);printf(“i=%d\nf=%f\nc=%c\nd=%lf",i,f,c,d);

}

OutputEnter value for i,f,c,d: 10 2.3 A 5.6i=10f=2.300000c=AD=5.600000

Formatted & unformatted I/OFundamental

Data Type Data Type Conversion Symbol+Format Specifier

Integer short integer %d or %i

short unsigned %u

long signed %ld

long unsigned %lu

unsigned hexadecimal %X or %x

unsigned octal %o

Real float %f or %g

double %lf

Character character %c

string %s

Unformatted Functions

Unformatted Input

getch() & getche()

read a alphanumeric characters from the standard input

device such as the keyboard

The character entered is not displayed by getch() function

Example : getch() & getche()

# include<stdio.h>#include<conio.h>void main ( ) { clrscr(); printf (“Enter two alphabets:”) ; getche(); getch(); }Output:Enter two alphabets:A

Unformatted Functions

getchar()

• read a character type data from the standard input device

such as the keyboard

• Reads one character at a time till user press the enter key

Example : getchar()

# include<stdio.h>#include<conio.h>void main ( ) { char c; clrscr(); printf (“Enter a character:”) ; c=getchar(); printf(“c=%c”,c); getch(); }Output:Enter a character :A

c=A

Unformatted Functions

gets()

• read a string from the standard input device such as the

keyboard until user press the enter key

Example : gets()

# include<stdio.h>#include<conio.h>void main ( ) { char str[10]; clrscr(); printf (“Enter a string:”) ; gets(str); printf(“String=%s”,str); getch(); }Output:Enter a string :Hello

String=Hello

Unformatted Functions

putch() & putchar()

• Prints any alphanumeric character taken by the standard

input device such as the keyboard

Example:

char ch=‘X’;

putch(ch); or putchar(ch);

Output: X

Unformatted Functionsputs()

• prints the string or character array

Example : puts()

# include<stdio.h>#include<conio.h>void main ( ) { char str[10]; clrscr(); printf (“Enter a string:”) ; gets(str); printf (“Entered string:”) ; puts(str); getch(); }Output:Enter a string :Hello

Entered string:Hello

top related