• No results found

Programming in c. 1. Explain the basic structure of C Programs (Programming language).

N/A
N/A
Protected

Academic year: 2021

Share "Programming in c. 1. Explain the basic structure of C Programs (Programming language)."

Copied!
8
0
0

Loading.... (view fulltext now)

Full text

(1)

Programming in c

Gaurav k sardhara || 9067351366

Page 1

UNIT -2

1. Explain the basic structure of C Programs (Programming language).

A „C‟ program may contain one or more sections as shown below:

Documentation Section Link Section

Definition Section

Global Declaration Section main( ) Function Section { Declaration Part; Executable Part; } Subprogram Section Function 1 Function 2 : : Function n Documentation Section:

- The Documentation section consists of a set of comment lines giving the name of the program, the author and the other details. Which programmer would like to use later.

- „C‟ language supports two types of comments:

Single line comments ( // ) : What ever written after this will be treated as a comment (for that line only) and compiler will not read it.

e.g. int m1; // for storing mark of subject 1

Multi line comments (/* */) : What ever written after /* upto */ will be tread as comment and compiler will not read it.

e.g. /* This program is use develop to calculate simple interest. Amount, rate of interest and number of years must be inputted. Developed by : Radhe Shyam on 1/1/2010 */

- This section is optional.

Link Section:

- The link section provides instructions to the compiler to link functions from the system library. - This section is optional.

Definition Section:

- This section defines all the symbolic constants for the program. - This section is optional.

Global Declaration Section:

- There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. These section also declares all the user defined functions.

- This section is optional.

main( ) Function Section:

- Every C program must have one main() - This section contains two parts:

o Declaration Part: all the variables used in the function must be declared here. o Executable Part: all the executable statements must be written here.

- These two parts must appear between opening brace and closing brace.

- All the statements in the declaration and executable parts end with a semicolon (;).

Subprogram Section:

- The subprogram section contains all the user-defined functions that are called in the main function. User-defined functions are generally placed immediately after the main function, although they may appear in any order.

(2)

Programming in c

Gaurav k sardhara || 9067351366

Page 2

- This section is optional.

2. List out Decision making statements (Control STATEMENTS) available in C

language. Explain any one with an example.

As answer of Q.3 or Q.4

3. Explain if - Decision statement in different forms with an example.

The if else Statement

This is used to decide whether to do something at a special point, or to decide between two courses of action.

The following test decides whether a student has passed an exam with a pass mark of 45 if (result >= 45)

printf("Pass\n"); else

printf("Fail\n");

It is possible to use the if part without the else. if (temperature < 0)

print("Frozen\n");

Each version consists of a test, (this is the bracketed statement following the if). If the test is true then the next statement is obeyed. If is is false then the statement following the else is obeyed if present.

If we wish to have more than one statement following the if or the else, they should be grouped together between curly brackets. Such a grouping is called a compound statement or a block.

if (result >= 45) { printf("Passed\n"); printf("Congratulations\n") } else { printf("Failed\n");

printf("Good luck in the resits\n"); }

Sometimes we wish to make a multi-way decision based on several conditions. Nesting of if can be used, as follow.

if (result >= 75) {

printf("Passed: Grade A\n"); } else { if (result >= 60) { printf("Passed: Grade B\n"); } else { if (result >= 45) { printf("Passed: Grade C\n"); } else { printf("Failed\n"); } } }

(3)

Programming in c

Gaurav k sardhara || 9067351366

Page 3

The most general way of doing this is by using the else if variant on the if statement however This works by cascading several comparisons. As soon as one of these gives a true result, the following statement or block is executed, and no further comparisons are performed. In the following example we are awarding grades depending on the exam result.

if (result >= 75)

printf("Passed: Grade A\n"); else if (result >= 60) printf("Passed: Grade B\n"); else if (result >= 45) printf("Passed: Grade C\n"); else printf("Failed\n");

In this example, all comparisons test a single variable called result. In other cases, each test may involve a different variable or some combination of tests. The same pattern can be used with more or fewer else if's, and the final lone else may be left out. It is up to the programmer to devise the correct structure for each programming problem.

4. Explain Switch Case statement with an example.

The switch Statement

This is another form of the multi way decision. It is well structured, but can only be used in certain cases where;

- Only one variable is tested, all branches must depend on the value of that variable. - The variable must be an integral type. (int, long, short or char).

- Each possible value of the variable can control a single branch.

- A final, catch all, default branch may optionally be used to trap all unspecified cases. - Nesting of switch statements is allowed.

An example will so these. This is a function which converts an integer into a vague description (words). It is useful where we are only concerned in measuring a quantity when it is quite small.

int number;

/* Estimate a number as none, one, two, several, many */ { switch(number) { case 0 : printf("None\n"); break; case 1 : printf("One\n"); break; case 2 : printf("Two\n"); break; case 3 : case 4 : case 5 : printf("Several\n"); break; default : printf("Many\n"); } }

- Each interesting case is listed with a corresponding action. The break statement prevents any further statements from being executed by leaving the switch.

- Since case 3 and case 4 have no following break, they continue on allowing the same action for several values of number.

Both if and switch constructs allow the programmer to make a selection from a number of possible actions.

(4)

Programming in c

Gaurav k sardhara || 9067351366

Page 4

5. Explain Conditional Operator ( ? : )in C language with an example.

Conditional operator ('? :')

- The conditional operator '? :' is, in fact, a ternary operator. - It uses the following syntax:

expr1 ? expr2 : expr3

- In the expression expr1 ? expr2 : Expr3, the operand expr1 must be of scalar type.

- In all cases, expr1 is evaluated first. If its value is nonzero (true), then expr2 is evaluated and

expr3 is ignored (not evaluated at all). If expr1 evaluates to zero (false), then expr3 is

evaluated and expr2 is ignored. The result of expr1 ? expr2 : expr3 will be the value of whichever of expr2 and expr3 is evaluated.

- It is shortcut of if…else but can be used only when we want to execute a single statement when the condition is true or false.

- e.g. if (a==b) flag=0; else

flag=1;

can be written using conditional statements as: flag = (a==b ? 0 : 1) ;

- We can also use conditional operators as follow :

(c==2 ? printf(“No is prime”) : printf(“No is not prime”)); - Nesting of the conditional operators is also allowed

e.g. big = ( a>b ? (a>c ? 3 : 4) : (b>c ? 6 : 8) ) ;

- a>b ? c=a : c=b ; will give error „Lvalue required‟ the compiler believes that b is being assigned to the result of the expression to the left of second =. This can be overcome by using parenthesis, as a>b ? c=a : ( c=b );

6. List out Loop statements available in C language. Explain any one with

example.

Loops

- Loops allow a statement, or block of statements, to be repeated. - C gives a choice of three types of loop, while, do…while and for loop.

The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will be traversed.

 The do…while loops is similar, but the test occurs after the loop body is executed. This ensures that the loop body is run at least once.

The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it offers.

[Explain any one of the above loop as in Q.7,8 or 9]

7. Explain structure of for loop with example.

FOR loop:

- for loops are the most useful type. - The syntax of a for loop is

for ( variable initialization ; test condition ; variable update ) {

Code to execute while the condition is true }

- Initialization of the control variables is done first, using assignment statement such as x=0. Such variables are known as loop-control variables.

(5)

Programming in c

Gaurav k sardhara || 9067351366

Page 5

- The value of control variable is tested using the test condition. It is a relational expression, such as x<10 that determines when the loop will exit. If the condition is true, the body of the loop is executed, otherwise the loop is terminated.

- When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now the control variable is updated x++ or x-- and is again tested to see whether it satisfies the loop condition. If satisfied, the body of the loop is again executed, otherwise not.

- This process continues till the value of the control variable fails to satisfy the test conidion. Loops are used to repeat a block of code. Being able to have our program repeatedly execute a block of code is one of the most basic but useful tasks in programming executing a single task many times.

Now, about what this means: a loop lets us to write a very simple statement to produce a significantly greater result simply by repetition.

int x;

/* The loop goes while x < 10, and x increases by one every loop*/ for ( x = 0; x < 10; x++ )

{

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

/* The loop condition checks the conditional statement before it loops again. consequently, when x equals 10 the loop breaks. x is updated before the condition is checked. */

8. Explain While loop (ENTRY CONTROL LOOP) with example.

The while Loop

- The simples of all the looping structures in C is the while statement. - The basic format of the while statement is :

[ initialize loop variable; ] while (test condition) {

Body of the loop :

:

[ Update loop variable; ] }

- The while is entry controlled loop statement. The test condition is evaluated and if the condition is true, the body of the loop is executed.

- After execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again.

- The process of repeated execution of the body continues until the test condition finally becomes false and the control is transferred out of the loop.

- As an example, here is a function to return the length of a string.

- The string is represented as an array of characters terminated by a null character '\0'. int string_length(char string[])

{ int i = 0; while (string[i] != '\0') i++; return(i); }

- The string is passed to the function as an argument. The size of the array is not specified, the function will work for a string of any size.

-

The while loop is used to look at the characters in the string one at a time until the null character is found. Then the loop is exited and the index of the null is returned. While the character isn't null, the index is incremented and the test is repeated.

(6)

Programming in c

Gaurav k sardhara || 9067351366

Page 6

9. Explain DO…WHILE (Exit control) loop structure with example.

DO..WHILE Loop

- DO..WHILE loops are useful for things that want to loop at least once. The structure is do { … … Body of loop; … } while ( condition );

- The condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, control jump back to the beginning of the block and execute it again.

- A do...while loop is almost the same as a while loop except that the loop body is guaranteed to execute at least once.

- A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and then continue to loop while the condition is true". - Example: int x; x = 0; do { printf( "%d\n", x ); } while ( x != 0 );

/* "Hello, world!" is printed at least one time even though the condition is false*/ - Trailing semi-colon must be included after the while in the above example.

- A common error is to forget that a do..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion).

- This loop will execute once, because it automatically executes before checking the condition.

10.

Explain Nested loop in c language with suitable example.

C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept.

Syntax

The syntax for a nested for loop statement in C is as follows − for ( init; condition; increment ) {

for ( init; condition; increment ) { statement(s);

}

statement(s); }

The syntax for a nested while loop statement in C programming language is as follows − while(condition) { while(condition) { statement(s); } statement(s); }

The syntax for a nested do...while loop statement in C programming language is as follows − do {

(7)

Programming in c

Gaurav k sardhara || 9067351366

Page 7

do {

statement(s); }while( condition ); }while( condition );

A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a 'for' loop can be inside a 'while' loop or vice versa.

Example

The following program uses a nested for loop to find the prime numbers from 2 to 100 − #include <stdio.h>

int main () {

/* local variable definition */ int i, j;

for(i = 2; i<100; i++) { for(j = 2; j <= (i/j); j++)

if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) printf("%d is prime", i);

}

return 0; }

11.

Explain break and continue statements in c language with suitable

example.

Break

- The break command will exit the most immediately surrounding loop regardless of what the conditions of the loop are.

- break is useful if we want to exit a loop under special circumstances. - break is also useful in switch…case to break a case.

Continue

- Continue is keyword that controls the flow of loops.

- If we are executing a loop and hit a continue statement, the loop will stop its current iteration, update itself (in the case of for loops) and begin to execute again from the top.

- Essentially, the continue statement is saying "this iteration of the loop is done, let's continue with the loop without executing whatever code comes after me."

void main( ) { int xx; for(xx = 5;xx < 15;xx = xx + 1) { if (xx == 8) break;

printf("in the break loop, xx is now %d\n",xx); }

for(xx = 5;xx < 15;xx = xx + 1) {

if (xx == 8) continue;

(8)

Programming in c

Gaurav k sardhara || 9067351366

Page 8

} }

- In the first "for" there is an if statement that calls a break if xx equals 8. The break will jump out of the loop you are in and begin executing the statements following the loop, effectively terminating the loop. This is a valuable statement when you need to jump out of a loop depending on the value of some results calculated in the loop. In this case, when xx reaches 8, the loop is terminated and the last value printed will be the previous value, namely 7.

-

The next "for" loop, contains a continue statement which does not cause termination of the loop but jumps out of the present iteration. When the value of xx reaches 8 in this case, the program will jump to the end of the loop and continue executing the loop, effectively eliminating the printf statement during the pass through the loop when xx is eight.

12.

Explain goto statement with label in C language.

To use a "goto" statement, simply use the reserved word "goto", followed by the symbolic name to which you wish to jump.

The name is then placed anywhere in the program followed by a colon.

It is not allowed to jump into any loop, but allowed to jump out of a loop. Also, it is not allowed to jump out of any function into another. These attempts will be as an error.

The goto statement transfers control to a label. The given label must reside in the same function and can appear before only one statement in the same function.

Syntax statement: labeled-statement jump-statement jump-statement: goto identifier ; labeled-statement: identifier : statement

A statement label is meaningful only to a goto statement; in any other context, a labeled statement is executed without regard to the label.

A jump-statement must reside in the same function and can appear before only one statement in the same function. The set of identifier names following a goto has its own name space so the names do not interfere with other identifiers. Labels cannot be redeclared.

It is good programming style to use the break, continue, and return statement in preference to goto whenever possible. Since the break statement only exits from one level of the loop, a goto may be necessary for exiting a loop from within a deeply nested loop.

This example demonstrates the goto statement: #include <stdio.h> void main() { int i, j; for ( i = 0; i < 10; i++ ) {

printf_s( "Outer loop executing. i = %d\n", i ); for ( j = 0; j < 3; j++ )

{

printf_s( " Inner loop executing. j = %d\n", j ); if ( i == 5 )

goto stop; }

}

/* This message does not print: */ printf_s( "Loop exited. i = %d\n", i );

stop: printf_s( "Jumped to stop. i = %d\n", i ); }

References

Related documents

Field experiments were conducted at Ebonyi State University Research Farm during 2009 and 2010 farming seasons to evaluate the effect of intercropping maize with

Results suggest that the probability of under-educated employment is higher among low skilled recent migrants and that the over-education risk is higher among high skilled

○ If BP elevated, think primary aldosteronism, Cushing’s, renal artery stenosis, ○ If BP normal, think hypomagnesemia, severe hypoK, Bartter’s, NaHCO3,

The key segments in the mattress industry in India are; Natural latex foam, Memory foam, PU foam, Inner spring and Rubberized coir.. Natural Latex mattresses are

The results of this study showed that increasing salinity of re-circulating nutrient solutions of tomato grown in soil-less system in SE Spain caused a notable improvement in

The foremost motivation behind this study is to empirically find out the effect of demonetization on the Indian economy specifically on Money Supply (M1), Notes

National Conference on Technical Vocational Education, Training and Skills Development: A Roadmap for Empowerment (Dec. 2008): Ministry of Human Resource Development, Department

However, obtaining bacterial genomic information is not always trivial: the target bacteria may be difficult-to-culture or uncultured, and may be found within samples containing