• Nenhum resultado encontrado

UNITII

N/A
N/A
Protected

Academic year: 2021

Share "UNITII"

Copied!
25
0
0

Texto

(1)

UNIT –II Data Input and Output: Preliminaries

 An input/output function can be accessed from anywhere within a program, simply by writing the function name, followed by a list of arguments enclosed in parenthesis.

 Some functions do not require arguments, though empty parentheses still appear. Some functions may return data item and some functions do not return any data item.

 Each file contains information in support of a group of related library functions. These are entered through #include statement at the beginning of the program.

 The header file required by the standard input/output library functions is called stdio.h, it supplies information to the library functions scanf and printf.

 The getchar( ) function causes a single character entered from the keyboard and assign to the character variable.

 The putchar( ) function causes the value of the character variable to be displayed.

Single character input-getchar function:

 Single characters can be entered into the computer using the C I/O library function getchar.  This function returns a single character from a standard input device, keyboard. This function

does not require any arguments.  The general form is,

Character_variable = getchar( ); Ex: char c;

c=getchar( );

 If an end-of-file condition is encountered when reading a character with the getchar function, the value of the symbolic constant EOF(Value is -1) will automatically be returned.

 The getchar function can also be used to read multi character strings, by reading one character at a time within a multi pass loop.

#include<stdio.h> #include<conio.h> main( ) { char c,line[80]; int i; clrscr( );

printf(“\n Enter characters at end press ctrl+z keys”); i=0; do { c=getchar( ); line[i]=c; i++; } while(c!=EOF); line[i]=’\0’; Test data

Enter characters at end press ctrl+z keys

Jagans college of engg and tech ^Z

The characters entered are: Jagans college of engg and tech

(2)

printf("\n The characters entered are: \n"); printf("%s",line);

getch( ); }

Single character output- putchar function:

 Single characters can be displayed using the C library function putchar.

 The putchar function, like getchar, is a part of the standard C I/O library. It transmits a single character to a standard output device-monitor.

 The general is as follows , putchar(character variable); Ex: char ch=’J’;

putchar (ch);

 The putchar function can be used with loops to output a string. #include<stdio.h>

#include<conio.h> main( )

{

char line[80]="jagans college"; int i; clrscr( ); i=0; do { putchar(line[i]); i++; }while(line[i]!='\0'); getch( ); } Test data jagans college

Enter input data- scanf function

 Input data can be entered into the computer from a standard input device with C library function scanf.

 This function is used to read data any combination of numeric values, single characters and strings.

 The general format is:

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

Here control string refers the format of data being received.

 The ampersand (&) operator before each variable specifies the address of the variable.  Control string contains the field specifications consisting of conversion character

percentage(%), and a data type character (such as d or f) and an optional number specifying the width.

char sname[20]; int snum;

(3)

scanf(“%s %d %f”,&sname,&snum,&age);

Within the scanf function, the control string is “%s %d %f”, three character groups.  The first character group %s indicates that the first argument &sname represents a string.  The second character %d indicates the second argument &snum represents a decimal integer

value.

 The third character %f indicates the third argument &sage represents a floating point value. The following data items could be entered from the standard input device when the program is executed.

 Mohan 222 19.6

The first 5 characters will be assigned the string sname, the integer value 222 would be assigned to snum, and the floating-point value 19.6 would be assigned to sage.

*Note that the individual data items are entered on one line, separated by blank spaces. The data items could also be entered on separated lines.

Field width

 It is also possible to limit the number of input characters by specifying the Field width for a data item.

Syntax: %w

 The number of characters in the actual data item cannot exceed the specified field width. Any characters that extend beyond the specified field width will not be read. Such leftover(extra) characters may be interpreted as the components of the next data item.

int a,b,c;

scanf(“%3d %3d %3d”, &a,&b,&c);

Suppose the input data items are entered as, 1 2 3 The assignments will result: a=1 b=2 c=3

If the data has been entered as, 123 456 789 The assignment would be a=123 b=456 c=789 If the data has been entered as, 123456789

Conversion character Meaning

c Data item is a single character d Data item is a Decimal integer f Data item is as a Floating-point value

e Data item is a floating point value as exponent ld Data item is a long integer value

lf Data item is a double value h Data item is a short integer

i Data item is a decimal/hexa/octal integer o Data item is an octal integer

s Data item is a string

u Data item is an unsigned decimal integer X Data item is a hexadecimal integer

(4)

The assignment would be a=123 b=456 c=789 Finally the data has been entered as, 1234 5678 9 The resulting assignment would be a=123 b=4 c=567 the remaining two digits 8 and 9 would be ignored.

Writing output – printf function

 Output data can be written from the computer onto a standard output using the library function printf. This function can be used to output any combination of numerical values, single

characters and strings.

 The general format is as follows,

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

where control string refers to a string that contains formatting information,

and arg1,arg2….,argn are arguments that represent the individual output data items

 The arguments in a printf function do not represent memory addresses and therefore are not preceded by ampersands.

 The control sting consists of individual groups of characters, an individual character group will consist of the % sign followed by a conversion character indicating the corresponding data item.  Control string indicates the type of the arguments or variables. The variables should match in

number, type and order with the format specification.

Example:

1. printf(“\n welcome the c programming”);

Will display the text enclosed in double quotes on to the screen. 2. printf(“%d”, x); Will display the value of the integer variable x. 3. printf(“\n sum of two variables =%d”,c);

Will display message and value of c. The gets and puts function:

 The function gets( ) is used to accept a string from keyboard.

 The major difference to scanf( ) and gets( ) is, the gets function may read blank spaces within the string.

 The Input is terminated when a new line character ‘\n’ (enter key) is entered. Syntax: gets(string_variable);

Example:

char sname[20]; gets(sname);

 The function puts( ) is used to output a string onto screen. Conversion character Meaning

c Data item is displayed as a single character d Data item is displayed as a Decimal integer

f Data item is displayed as a Floating-point value

e Data item is displayed as a floating-point value with an exponent lf Data item is displayed as a double value

ld Data item is displayed as a long integer value h Data item is displayed as a short integer

i Data item is displayed as a decimal/hexa/octal integer o Data item is displayed as an octal integer

s Data item is displayed as a string

u Data item is displayed as an unsigned decimal integer X Data item is displayed as a hexadecimal integer

(5)

Syntax: puts(string_variable);

Example: char college[30]=”jagans engineering”; puts(college);

Interactive programming:

 Many modern computer programs are designed to create an interactive dialog between the computer and the person using the program.

 These dialogs usually involve some form of question-answer interaction, where the computer asks the questions and the user provides the answer, or vice versa.

 In C, such dialogs can be created by alternate use of scanf and printf functions.

 The printf function is used both when entering data and displaying results. The scanf is used only for actual data entry.

 Consider the following program that reads students number and 3 subjects marks, and then calculate total and average marks.

#include<stdio.h> #include<conio.h> main( ) { int sno; flaot m1,m2,m3,tot,avg; clrscr();

printf(“\n Enter student number:”); scanf(“%d”,&sno);

printf(“\n Enter subject1 marks:”); scanf(“%f”,&m1);

printf(“\n Enter subject2 marks:”); scanf(“%f”,&m2);

printf(“\n Enter subject3 marks:”); scanf(“%f”,&m3);

tot=m1+m2+m3; avg=tot/3;

printf(“\n Student number=%7d”,sno); printf(“\n Subject1 marks=%7.1f”,m1); printf(“\n Subject2 marks=%7.1f”,m2); printf(“\n Subject3 marks=%7.1f”,m3); printf(“\n Total marks=%7.1f”,tot); printf(“\n Average marks=%7.1f”,avg); getch();

}

The interactive session is as follows. Enter student number: 121 Enter subject1 marks:55 Enter subject2 marks:66 Enter subject3 marks:77 Student number= 121 Subject1 marks= 55.0

(6)

Subject2 marks= 66.0 Subject3 marks= 77.0 Total marks= 198.0 Average marks= 66.0

Preparing and Running a Complete C Program

Planning a C Program:

 Once the overall program strategy such as program logic, has been clearly established, the details associated with the individual program statements can be considered. This approach is generally referred as “top-down” programming.

 In top-down approach the initial stages of program development in C are minimal, consisting only of major program components, such as function headings, function references, compound statements, and control statements.

 The compound Interest calculation program development in the form of pseudocode in top-down approach is as follows.

main() {

/*declare p,r,n,i and f to be float variables */ /* write a prompt for p and then read its value */ /* write a prompt for r and then read its value */ /* write a prompt for n and then read its value */ /* calculate i=r/100 */

/* calculate f=p(i+i)n as f=p * pow((i+i),n)

where pow is library function*/ /* display the value f, with a suitable text */ }

 Another method of planning is “bottom-up” approach. This method is useful for programs that make use of self-contained program modules. This approach involves the detailed development of these program modules early in the planning process. The overall program development is then based upon the known characteristics of these available program modules.

Writing a C Program:

 Writing a program means translating each step of the program outline into one or more equivalent program instructions.

 When writing a program an attention should be given to including certain additional features that will improve the readability of the program and its resulting output. The features include the logical sequence sequencing of statements, the use of indentation and white spaces, the inclusion of comments and clear labelled output.

(7)

 Comments should always be included within C program. It can provide a overview of the general program logic.

 Another important characteristic of a well-written program is its ability to generate clear, legible output.

 In an interactive environment the input data is displayed on the screen at the time of data entry, during program execution. A well-written interactive program should generate prompts at appropriate times during the program execution in order to provide information how to enter data.

 Consider an interactive C program for simple compound interest problem

/* simple compound interest problem */ #include<stdio.h>

#incldue<math.h> main()

{

float p,r,n,i;

/* read input data */

printf(“Enter value for principal amount p:”); scanf(“%f”,&p);

printf(“Enter value for interest rate r:”); scanf(“%f”,&r);

printf(“Enter value of number of years n:”); scanf(“%f”,&p);

/* calculate i and f */ i=r/100;

f= p*pow((1+i),n); /* display the output*/

printf(“\n Final value f is:”%f”,f); }

Error Diagnostics

 Programming errors are not detected until we made compile or execute the program. There are three kinds of programming errors.

1. Syntactic errors 2. Run Time errors or execution errors 3. Semantic or logical errors

Syntactic errors:

 Syntactic errors are due to violation of structure and rules of programming language. Some common errors of this type are improperly declared variables, a reference to an undeclared variables, incorrect punctuation, etc.

 Most C compilers will generate diagnostic messages when syntactic errors have been detected during the compilation process. These messages are not always straightforward in their meaning and they may not correctly identify where the error occurred.

(8)

 If a program includes several different syntactic errors, they may not all be detected on the first pass through the compiler. Thus, it is necessary to correct some syntactic errors before others can be found. This process could repeat itself though several cycles before all of the syntactic errors have been identified and corrected.

/* simple compound interest problem */ #include<stdio.h>

incldue<math.h> main()

{

float p,r,n,i;

printf(“Enter value for p:”); scanf(“%f”,&p);

printf(“Enter value for r:); scanf(“%f”,&r);

printf(“Enter value for n:”); scanf(“%f”,&p)

i=r/100;

f= p*pow(1+i),n); /* display the output /*

printf(“\n Final value f is:”%f”,f); }

This program contains five different syntactic errors.

1. The second include statement does not begin with # sign.

2. The control string in the second printf does not have a closing quotation mark. 3. The last scanf statement does not end with a semicolon.

4.The assignment statement for f contains unbalanced.

5.The last comment closes improperly.

Run Time or Execution Errors

 Execution errors occur during program execution, after a successful compilation.

 Some common execution errors are a numerical overflow or underflow, division by zero, attempting to computer square root of a negative number, etc.

 Diagnostic messages will often be generated of this type, making it easy to identify and correct the errors. These diagnostics are sometimes called execution messages or run-time messages.  Consider to calculate the real roots of the quadratic equation ax2+bx+c=0

using the formula x=−b ±

b2−4 ac 2a

/* real roots of a quadratic equation */ #include<stdio.h>

#incldue<math.h> main()

{

float a,b,c,d,x1,x2;

printf(“Enter value for a:”); scanf(“%f”,&a);

printf(“Enter value for b:”); scanf(“%f”,&b);

printf(“Enter value for c:”); scanf(“%f”,&c)

(9)

d=sqrt(b*b - 4*a*c); x1= (-b+d)/(2*a); x2= (-b+d)/(2*a); /* display the output /*

printf(“\n Roots are x1=%f x2=%f”,x1,x2); }

Suppose for example the program is run with the following input values Enter value for a:1.0

Enter value for b:2.0 Enter value for c:3.0

The program compiles without any difficulty. When the program is executed, the following error message is generated.

sqrt: DOMAIN error Semantic or Logical Errors:

 A semantic error is one related to the meaning of something. For example, a syntactically perfect statement made in the wrong context is a semantic error which may be detected at compile-time.  A logic error is one that refers to incorrect program logic.

 For example, the following pseudo code snippet contains a logic error: if (a > b)

printf("a is greater than b"); else

printf("a is less than b");

The error is that the second branch is true if a is less than or equal to b. DEBUGGING TECHNIQUES

 Finding the location of execution errors and logical errors within a program is referred to as debugging techniques.

 Some of the more commonly used debugging techniques are,

1. Error Isolation

 Error Isolation is useful for locating an error resulting in a diagnostic message.

 If the location of the error is not known, it can frequently be found by temporarily deleting a portion of the program and then run the program to see if the error disappears.

 The temporary deletion is accomplished by surrounding the instructions with comment (/* and */). If the error message then disappears, the deleted portion of the program contains the source of the error.

(10)

printf(“Debugging – line1 \n”); printf(“Debugging – line2 \n”);

at various places with in the program. When the program is executed the debug messages will indicates the location of the error.

/* real roots of a quadratic equation */ #include<stdio.h>

#incldue<math.h> main()

{

float a,b,c,d,x1,x2;

printf(“Enter value for a:”); scanf(“%f”,&a);

printf(“Enter value for b:”); scanf(“%f”,&b);

printf(“Enter value for c:”); scanf(“%f”,&c); printf(“Debugging – line1 \n”); d=sqrt(b*b - 4*a*c); printf(“Debugging – line2 \n”); x1= (-b+d)/(2*a); printf(“Debugging – line3 \n”); x2= (-b+d)/(2*a);

/* display the output /*

printf(“\n Roots are x1=%f x2=%f”,x1,x2); }

2. Tracing:

 Tracing involves the use of printf statements to display the values that are calculated internally at various locations within the program. This information serves several purposes.

(11)

 In many situations, we will be able to identify a particular place where things begin to go wrong because the values generated will be obviously incorrect.

/* real roots of a quadratic equation */ #include<stdio.h>

#incldue<math.h> main()

{

float a,b,c,d,x1,x2;

printf(“Enter value for a:”); scanf(“%f”,&a);

printf(“Enter value for b:”); scanf(“%f”,&b);

printf(“Enter value for c:”); scanf(“%f”,&c);

d=sqrt(b*b - 4*a*c);

printf(“a=%f b=%f c=%f d=%f”,a,b,c,d); /* tracing statement*/ printf(“\n -b+d=%f”,(-b+d)); /* tracing statement*/

printf(“\n –b-d=%f”,(-b-d)); /* tracing statement*/ x1= (-b+d)/(2*a);

x2= (-b+d)/(2*a); /* display the output /*

printf(“\n Roots are x1=%f x2=%f”,x1,x2); }

 Most C compilers include an interactive debugger, which provides the ability to set watch values, breakpoints, and allows stepping through a program, one instruction at a time. 3. Watch values:

 A watch value is the value of a variable or an expression which is displayed continuously as the program executes. Thus, we can see the changes in a watch value as they occur, in response to the program logic.

 In turbo C, watch values can be defined by selecting Add Watch from the Break/Watch menu or press ctrl+f7 keys and then specify one or more variables or expressions in the

(12)

resulting dialog box. The watch values will then be displayed within a separate window as the program executes.

4. Breakpoints:

 A breakpoint is a temporary stopping point within a program. Each breakpoint is associated with a particular instruction within the program. When the program is executed, the program execution will temporarily stop at the breakpoint, before the instruction is executed. The execution may then be resumed, until the next breakpoint is encountered.

 Breakpoints are used in conjunction with watch values, by observing the current watch value at each breakpoint as the program executes.

5. Stepping:

 Stepping refers to the execution of one instruction at a time, by pressing a function key F7 or F8 to execute each instruction. By stepping through an entire program, we can determine which instruction produce erroneous results or generate error messages.

 Stepping is used with watch values, allow us to trace the entire history of a program as it executes. Thus, we can observe changes to watch values as they happen.

CONTROL STATEMENTS Branching : The if-else statement:

 The instructions are executed in sequence order in the program. There may be many situations where such execution sequence may not be sufficient.

 For example, we want to find the bigger among two numbers. It requires comparison of two numbers, and based on comparison result, the bigger number is found. This can be implemented using if instruction.

 The ‘if’ statement is a powerful decision making statement and is used to control the flow of execution of statements.

 The ‘if’ statement may be implemented in different forms depending on the complexity of condition to be tested.

a). Simple ‘ If ’ statement: This is one-way branching statement. The general form of a simple if is as follows;

Syntax: Flowchart: Ex: if(marks>=60) { if(Testexpression) { ………… Statements ………. } Statement-x;

(13)

marks=marks+10; }

printf(“%d”, marks);

The statement block may be a single statement or a group of statements.

If the test expression is true, the statement block will be executed, otherwise the statement-block will be skipped and the execution will jump to statement-x.

b). The ‘ if..else ’ statement:

 This is two-way branching statement.

 If the test expression is true, then the true-block statements will be executed, otherwise the false-block statements will be executed.

 In both the case the control is transferred subsequently to statement-x. Example: if(marks>=35) if(a>b) res=”pass”; big=a; else else res=”fail”; big=b; printf(“\n Result=%s”,res); printf(“\n biggest= %d”,big);

The general form is as follows;

Syntax:

c). ‘Nested if..else ’ statement:  When a series of decisions are

involved, we have to use more than one if..else statement in nested form.

 This is a multi-way branching statement. Syntax: Flowchart: if(Test expression) { True-block statements; } else { False-block statements; } statement-x;

(14)

If condition1 is false, then statement block3 will be executed, otherwise condition2 is evaluated. If condition2 is true, then statement block1 will be executed; otherwise statement block2 will be executed. Finally the control is transferred to statement-x;

/* a program to find biggest among two */ main( )

{

int a,b,big;

printf(“\n Enter two numbers”); scanf(“%d %d”,&a,&b);

if(a>b) big=a; else big=b;

printf(“\n the biggest =%d”,big); getch( );

}

/* a program to find biggest among three numbers */ main( )

{

int a,b,c,big;

printf(“\n Enter three numbers”); scanf(“%d %d %d”,&a,&b,&c); if(a>b) { if(a>c) big=a; else big=c; } else { if(c>b) big=c; else big=b; }

Printf(“\n biggest =%d”,big); getch( );

} d. The else..if Ladder’:

 When a multi-path decisions are involved, in which the statement associated with each else is an another if.

 The conditions are evaluated from the top downwards. As soon as a true condition is found, then the statement block associated with it is executed and the control is transferred to statement-x.  When all the n conditions become false, then the final else containing the default- statement will

be executed. if(test condition1) { if(test condition2) { Statement block1; } else { Statement block2; } } else { Statement block3; } Statement-x;

(15)

LOOPING The While statement:

 The while statement is used to carry out looping operations, in which a group of statements is executed repeatedly, until some condition has been satisfied.

 The general form of while statement is

while(expression/condition) {

Body of the loop; …….

}

The body of the loop will be executed as long as the expression/condition is true. Example: i=1; while(i<=10) { printf(“%d \t”,i); i++; }

The following output will be generated when the program is executed. 1 2 3 4 5 6 7 8 9 10

 This is an entry-controlled loop. The body of the loop is executed only when the test condition is true.

The do-while statement:

 This is an exit-controlled loop. The condition is tested at end of the body of the loop is executed.  The general form of do-while statement is,

do {

Body of the loop; ……. }while(expression/condition); if(condition1) { statement block-1; } else if(condition2) { Statement block2; } ….. ….. ……. else if(condition n) { Statement block n; } else default-Statement; statement-x; Example: if (avg>=80) grade=”distinction; else if(avg>=60) grade=”first class”; else if(avg>=50) grade=”second class”; else if(avg>=35) grade=”third class” else grade=”fail”;

(16)

 The body of the loop is executed repeatedly, as long as the value of expression is true.  The body of the loop will be executed at least once even if the condition fails.

i=1; do { printf(“\n %d”,i); i++; }while(i<=10);

The following output will be generated when the program is executed. 1 2 3 4 5 6 7 8 9 10

 For many applications it is more natural to test for continuation of loop at the beginning rather than at the end of loop. For this reason do-while statement is used less frequently than the while statement.

The for Statement :

 The ‘for’ first statement is third and the most commonly used looping statement in c.  This statement includes an expressions that specifics an initial value for an index, another

expression that determines whether or not the loop is continued, and a third expressions that allows the index to be modified at the end of each pass.

 The general form of the for statement

for ( expression1; expression2; expression3) {

Body of the loop; }

 Where expressions1 is used to initialize some parameter (called an index ) that controls the looping action, expression2 represents a condition that must be true to continue execution, and expression3 is used to alter the value of parameter initially assigned by expression 1. Typically, expression1 is an assignment.

 When the for statement is executed, expression 2 is evaluated and tested at the beginning of each pass through the loop, and expression 3 is evaluated at the end of each pass.

 The looping action will continue as long as the value of expression2 is true. for(i=1;i<=10;i++)

{

printf(“\n %d”,i); }

The following output will be generated when the program is executed. 1 2 3 4 5 6 7 8 9 10

 All three expressions need not be included in the for statement, though the semicolons must be present. The first and third expressions may be omitted such as initialization of index and increment/decrement of the index.

(17)

i=1; for(; i<=10; ) { printf(“%d \t”,i); i++; }

A program to find the average of a list of numbers #include<stdio.h> #include<conio.h> main() { int n,count; float x,avg,sum=0; clrscr();

printf(“\n how many numbers:”); scanf(“%d”,&n);

for(count=1;count<=n;count++) {

printf(“\n Enter element:”); scanf(“%d”,&x);

sum=sum+x; }

avg=sum/n;

printf(“\n Average is %f”,avg); getch();

}

Nested Control Structures:

 A control structure can be nested, one within another.

 The inner and outer loops need not be generated by the same type of control structure. Each loop must be controlled by a different index.

(18)

A program to display the product table using nested loops #include<stdio.h> #include<conio.h> main() { int i,j,n; clrscr();

printf(“\n how many numbers:”); scanf(“%d”,&n);

printf(“\n PRODUCT TABLE \t”); i=1; while(i<=n) { for(j=1;j<=n;j++) { printf(“%d \t”,i*j); } i++; } getch(); } Switch statement:

 It is a multi-way decision statement, it tests the value of a given variable or expression against a list of case values and when a match is found, a block of statements associated with that case is executed.

 The general form of the switch is as follows.

 The expression is an integer expression or characters.

 value1, value 2,… are constants and are known as case labels, and they end with a colon (:).

switch(expression) { case value1: block1; break; case value2: block2; break; …. ….. ….. default: default block; break; } statement-x;

(19)

 The break statement at the end of each block signal the end of a particular case and causes exit from the switch statement and transfers the control to the statement-x.

 When the value of the expression does not match with any of the case values, then the default block will be executed.

 When the case labels are characters, then they must be enclosed in single quotes.

main( ) {

char choice; clrscr( );

printf(“\n enter a choice “);; switch(choice=toupper(getchar()) {

case ‘R’:

printf(“\n RED COLOR”); break;

case ‘W’:

printf(“\n WHITE COLOR”); break;

case ‘B’:

printf(“\n BLUE COLOR”); break;

default: printf(“\n Invalid color choice”); break; } getch( ); } main( ) { int x,y,choice; clrscr( );

printf(“\n enter two numbers”); scanf(“%d %d”,&x,&y);

printf(“\n AIRTMETIC OPERATIONS”); printf(“\n=================”); printf(“\n 1. ADDITION”);

printf(“\n 2. SUBTRACTION”); printf(“\n 3. MULTIPLICATION”); printf(“\n 4. DIVISION”);

printf(“\n Ener u r choice:”); scanf(“%d”, choice);

switch(choice) {

case 1: printf(“\n addition=%d”,(x+y)); break;

case 2: printf(“\n subtraction =%d”,(x-y)); break;

case 3: printf(“\n multiplication =%d”,(x*y)); break;

case 4: printf(“\n Division= %d”,(x/y)); break;

default: printf(“\n Invalid choice”); break;

} getch( ); }

The comma operator:

 The coma operator (,) is used in conjunction with the ‘for’ statement.

 This operator permits two different expressions to appear in situation where only one expression would ordinarily be used.

 For example,

for(expression1a,expressionib;expression2;expression3a,expression3b) {

(20)

Body of the loop; }

Expression1a and expression 1b are two expressions separated by comma operator. And also expression3a, expression3b are two expressions belongs to increment or decrement separated by comma operator. for(i=1,j=10;i<=10;i++,j--) { printf(“\n i= %d j=%d”,i,j); }

Goto Statement:

 This is an unconditional statement. It is used jump in program from one statement to another statement.  Its general form is : goto label;

 The control will be transferred directly to the label: statement in the program.

 There are two ways to jump in the program either it may be forward or backward jump. Forward jump …. …… statements; goto label; ….. …. Statements; label: Statements; Backward jump ….. ….. … label: statements; ….. goto label; …… statements;

The statement label: Is after the goto label; statement, then it is called forward jump, Is before the goto label; statement, it is called backward jump.

/* a program for forward jump */ main()

{ int x; clrscr();

printf(“\n Enter a number”); scanf(“%d”,&x);

if(x<0) goto end; else {

printf(“\n the root =%lf”,sqrt(x)); getch();

exit(1); }

end:

printf(“\n the root is not possible”); getch();

}

/* a program for backward jump */ main()

{ int x; clrscr(); start:

printf(“\n Enter a number”); scanf(“%d”,&x);

if(x<0) {

printf(“\n the root is not possible”); goto start;

} else

printf(“\n the root =%lf”,sqrt(x)); getch();

(21)

The break statement:

 The break statement is used to terminate a loop or to exit from a switch statement.  It can be used in a while, do-while and for statements.

 The general form is,

break;

 The break statement causes a transfer of control out of the loop, to the first statement following the loop. while(condition) { ………. if(condition) break; ………. Exit from } loop Statements; do { ………. if(condition) break; ………. Exit from } while(condition); loop Statements; for(initial;condition;incre/decre) { ………. if(condition) break; ………. Exit from } loop Statements;

The continue statement:

 The continue statement is used to bypass the remainder of the current pass through a loop.  The loop does not terminate, but the remaining loop statements are skipped and the computation

proceeds directly to the next pass through the loop.  It can be used in a while, do-while, and for statements.  The syntax is,

continue; while(condition) { ………. if(condition) continue; ………. Next iteration } Statements; do { ………. if(condition) continue; Next ………. iteration } while(condition); Statements; for(initial;condition;incre/decre) { ………. if(condition) continue; ………. Next iteration } Statements;

/* find average for a list of Non-Negative numbers */ #include<stdio.h> #include<conio.h> main( ) { int n,count,navg=0; float x,avg,sum=0; clrscr();

printf(“\n How many numbers:”); scanf(“%d”,&n);

Result

How many numbers: 6 Enter x value: 3 Enter x value:-3 Enter x value: 2 Enter x value:-2 Enter x value: 4 Enter x value:-4 Average is: 3.00000 Number of +ve

(22)

for(count=0;count<n;count++) {

printf(“\n Enter x value:”); scanf(“%f”,&x); if(x<0) continue; else sum=sum+x; ++navg; } avg=sum/navg;

printf(“\n Average is:%f”,avg);

printf(“\n Number of +ve elements:%d”,navg); getch();

}

elements: 3

FUNCTIONS

A Brief Overview:

 A function is a self-contained program segment that carries out some specific, well-defined task.  Functions are classified into two categories namely Library functions and user-defined functions.  The functions printf, scanf, sqrt, pow, strcat, etc are examples of library functions.

 The main( ) function is an example of user-defined function. Every C program consists of one or more functions. One of these functions must be called in main.

 The major difference between these two categories is that library functions are not require to be written by the programmer, whereas user-defined functions has to be developed by the

programmer.

 If a program contains multiple functions, their definitions may appear in any order, though they must be independent of one another.

 A function will carry out its intended action whenever it is accessed or called. A function can be accessed from anywhere within the program.

 A function will process information that is passed to it from the calling program and return a value. Information is passed to the function via special identifiers called arguments or parameters and returned via the return statement. Some functions accept information but does not return anything.

Function Definition

 When the program code become too large and complex as a result the task of debugging, testing and maintaining becomes difficult.

 If a program is divided into functional parts, then each sub-part may be coded independently and later combined into a single unit. In C, such sub-programs are referred to as Functions.

 A function definition has two principal components, function header and body.  The syntax for function definition is as follows

DataType FunctionName (Arguments List) {

Local variable Declaration; Executable statements;

……….

return expression; }

(23)

 The first line is known as function header and the statements between opening and closing braces are function body.

 The ‘DataType’ specifies the type of value that the function expected to return to the calling program. If the function is not return anything, then we need to specify the DataType as void. If the DataType is not specified, C will assume that it as an integer type.

 The ‘Argument List’ declares the variables that will receive the data sent by the calling program. These arguments are called as formal arguments. To indicate the argument/parameter List is empty, we use the keyword void.

 The function body contains the local declarations and necessary statements for performing the required task.

The return statement:

 Information is returned from the called function to the calling program through the ‘return’ statement. The value of expression is returned to the calling program.

 A function can return only one value to the calling program via return.

Syntax: return(expression); Example: return (big);

 The return statement can be omitted from a function definition when the called function does not return any value to the calling function.

Example function definitions:

/* function having return value */ int big2(int x, int y)

{

int big;

big=(x>y)?x:y; return big; }

/* Function No return value*/ void big2(int x, int y)

{

int big;

big=(x>y)?x:y;

printf(“Biggest=%d”,big); }

/* a function having more than one return statement*/ int big2(int x, int y)

{ if(x>y) return x; else return y; } Accessing a Function

 A function can be accessed or called by specifying its name, followed by a list of

arguments enclosed in parenthesis and separated by commas.

 The arguments appear in the function call are referred to as actual arguments or

parameters. Each actual argument must be of the same data type as its

(24)

 The value of each actual argument is transferred or copied into the function and

assigned to corresponding formal arguments.

 If a function returns a value, the function call is written as an assignment

statement.

max=big2(a,b);

The function call assigns a and b values to x and y. the function finds the biggest

between x and y and assign the result in big, and then returns to calling program

and assign into variable max.

 If the function does not return anything, the function call appears as,

big2(a,b);

/* function having return value */ #include<stdio.h>

#include<conio.h>

int big2(int x,int y); /*prototype*/ void main()

{

int a,b,max; clrscr();

printf(“\n Enter two numbers”); scanf(“%d %d”,&a,&b);

max=big2(a,b);

printf(“\n Biggest=%d”,max); getch();

}

int big2(int x, int y) {

int big;

big=(x>y)?x:y; return big; }

/*Function with No return value*/ #include<stdio.h>

#include<conio.h> int big2(int x,int y); void main()

{

int a,b,max; clrscr();

printf(“\n Enter two numbers”); scanf(“%d %d”,&a,&b);

big2(a,b); getch(); }

void big2(int x, int y) { int big; big=(x>y)?x:y; printf(“Biggest=%d”,big); } Function Prototype

 The programmer/user-defined functions will have been defined before the function access.  In top-down approach, main( ) appears ahead of the user-defined functions. In such situation the

function access will precede the function definition. So, we must specify to the compiler that the function being accessed will be defined later in the program. A function prototype is used for this purpose.

 The general form of a function prototype is as follows

DataType FunctionName (Arguments List);

 The function prototype ends with a semicolon.

 The data types of actual arguments must conform to the data types of the arguments within the prototypes.

(25)

 The names of the arguments within the function prototype need not be declared elsewhere in the program, since these are dummy argument names that are recognized only within the prototype. In fact, the argument names can be omitted, the argument data types are essential.

Example : int big2(int , int);

Passing Arguments to a Function

 When a single value is passed to a function via an actual argument, the value of the actual is copied into the function.

 The value of corresponding formal argument can be altered within the function, but the value of the actual argument within the calling function will not change. This procedure for passing the value of an argument to a function is known as ‘passing by value’.  The advantage of Passing an argument by value is, the value of actual argument is protected

from alterations within the called function.

 The disadvantage of passing an argument by value is, it does not allow information to be transferred back to the calling program via arguments.

/*swap two numbers using pass by value */ #include<stdio.h>

#include<conio.h> void swap(int x,int y); main()

{

int a,b; clrscr();

printf(“\n Enter a,b values:”); scanf(“%d %d”,&a,&b);

printf(“\n before swap a=%d b=%d”,a,b); swap(a,b);

printf(“\n after swap a=%d b=%d”,a,b); getch();

}

void swap(int x,int y) {

int t=x; x=y; y=t;

printf(“\n after swap x=%d y=%d”,x,y); }

Test data:

Enter a,b values: 3 5 before swap a=3 b=5 after swap x=5 y=3 after swap a=3 b=5

RECURSION:

 When a function calls itself, is called recursive functions.

 An example of recursion is the evaluation of factorials for a given number. The factorial for a number n is expressed as a series of repetitive multiplications.

n!=nx(n-1)x(n-2)x……1. For example, 4!=4x3x2x1=24 The sequence of operations are

(26)

fact(4) = 4*fact(3) = 4*3*fact(2) = 4*3*2*fact(1)

 A function to evaluate of factorial n is as follows. For example n=4,

Here the value of n is not 1, the statement return(n*fact(n-1)); will be executed. Then 4*fact(3) will be evaluated.

Again the function is called with n=3, this call will return the value 3*fact(2). Once again fact is called with n=2, this call will return the value 2*fact(1) Again fact is called with n=1, then the function returns 1.

 The recursive function definition for factorial is as follows. long int fact(int n)

{ if(n<=1) return 1; else return n*fact(n-1); }

/* a program to find factorial using recursion */ long int fact(int x);

main( ) { int x; clrscr();

printf(“\n Enter a number”); scanf(“%d”,&x);

printf(“\n factorial =%ld”,fact(x)); getch();

}

long int fact(int n) { if (n<=1) return 1; else return( n*fact(n-1) ); }

/* a program to find factorial using non-recursion */ long int fact(int x);

main( ) { int x; clrscr();

printf(“\n Enter a number”); scanf(“%d”,&x);

printf(“\n factorial =%ld”,fact(x)); getch();

}

long int fact(int n) { int i,f=1; for(i=1;i<=n;i++) f=f*i; return(f); } Towers of Hanoi

 The Towers of Hanoi is game played with three towers and a number of different sized disks.

 Disks are stacked on starting tower in the order of decreasing size. That is, largest on the bottom and smallest on the top.

(27)

 The object of the game is to move the disks from starting tower to ending tower using middle as intermediate tower.

 The rules to move are,

1. Only one disk may be moved at a time. 2. Do not place a bigger disk on smaller disk.

 The problem of moving all n disks to the ending tower can be stated in the following recursive manner.

1. Move the top n-1 disks from starting to intermediate tower 2. Move the nth disk to ending tower

3. Move the n-1 disk on the intermediate tower to ending tower  To move n disks, we need 2n-1 steps.

 The recursive function definition is as follows,

void tower(int n, char source, char dest, char temp) {

if(n>0) {

tower(n-1,source,temp,dest);

printf(“\n Move disk %d from %c to %c”,n,source,dest); tower(n-1,temp,dest,source);

} }

 We call the recursive function as

tower(n,’A’,’B’,’C’); The steps are,

1. Move disk1 from A to C 2. Move disk2 from A to B 3. Move disk1 from C to B 4. Move disk3 from A to C 5. Move disk1 from B to A 6. Move disk2 from B to C 7. Move disk1 from A to C /* a program on towers of hanoi */

(28)

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

void tower(int n, char source, char dest, char temp) main()

{

int n; clrscr();

printf(“\n Enter the number of disks:”); scanf(“%d”,&n);

printf(“\n The steps need are”); tower(n,’A’,’C’,’B’);

getch(); }

void tower(int n, char source, char dest, char temp) {

if(n>0) {

tower(n-1,source,temp,dest);

printf(“\n Move disk %d from %c to %c”,n,source,dest); tower(n-1,temp,dest,source);

} }

Referências

Documentos relacionados

Mas também além do mercado transatlântico e de sua etapa de redistribuição, o comércio de abastecimento dos grandes centros agroexportadores gerava um campo de atuação para

Assim, por meio de um comparativo, esta pesquisa tem como objetivo analisar os investimentos, nos anos de 2014 e 2015, do Governo do Estado de Santa Catarina

Para finalizar, nesta etapa de testes foi aprofundado um pouco mais a parte de processamento do sinal já que, pela Figura 3.26, facilmente se verifica que o sinal, embora

O resultado desse esforço foi a elaboração da Agenda de Pesquisa, Desenvolvimento e Inovação da Embrapa Cerrados, que definiu como foco de atuação da Unidade, três grandes

O projeto de pesquisa do Departamento de Odontologia Restauradora da Faculdade de Odontologia da Universidade Federal de Pelotas citado oferece reabilitação para

Por outras palavras, a investigação em psicoterapia psicanalítica ao nível do processo analítico passa por factores comuns e factores específicos, assumindo como factores

Fonte: elaboração própria. Esses dados oferecem um primeiro arranjo sobre a área temática corpo e cultura, no que tange a relação de orientações; grupos de pesquisa e

SciELO contempla uma coleção selecionada de periódicos científicos Ibero-Americanos. Segundo Ravelli et al. 508), “o objetivo da SciELO é o desenvolvimento de uma metodologia