Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
ExamQuestions_1.doc
Скачиваний:
0
Добавлен:
01.03.2025
Размер:
265.73 Кб
Скачать

Input using scanf()

The scanf() function is the input method equivalent to the printf() output function - simple yet powerful. In its simplest invocation, the scanf format string holds a single placeholder representing the type of value that will be entered by the user. These placeholders are exactly the same as the printf() function - %d for ints, %f for floats, and %lf for doubles.

There is, however, one variation to scanf() as compared to printf(). The scanf() function requires the memory address of the variable to which you want to save the input value. While pointers are possible here, this is a concept that won't be approached until later in the text. Instead, the simple technique is to use the address-of operator, &. For now it may be best to consider this "magic" before we discuss pointers.

A typical application might be like this:

#include "stdio.h"

int main(void)

{

int a;

printf("Please input an integer value: ");

scanf("%d", &a);

printf("You entered: %d\n", a);

return 0;

}

11.Loops: while

In c programming language, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement.

The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because while loop checks the condition before the block is executed, the control structure is often also known as a pre-test loop. Compare with the do while loop, which tests the condition after the loop has executed.

while (condition)

{

statements;

}

Example:

#include<conio.h>

void main ()

{

clrscr ();

int i,j;

i=0;

while (i<8)

{

printf (" ");

j=7;

while(j>i)

{

printf ("* ");

j--;

}

printf ("\n");

i++;

}

getch();

}

12.Loops: do-while

In c programming language, a do while loop is a control flow statement that allows code to be executed once based on a given Boolean condition.

The do while construct consists of a process symbol and a condition. First, the code within the block is executed, and then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false. Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop. Contrast with the while loop, which tests the condition before the code within the block is executed.

It is possible, and in some cases desirable, for the condition to always evaluate to true, creating an infinite loop. When such a loop is created intentionally, there is usually another control structure (such as a break statement) that allows termination of the loop.

Some languages may use a different naming convention for this type of loop. For example, the Pascal language has a "repeat until" loop, which continues to rununtil the control expression is true (and then terminates) — whereas a "while" loop runs while the control expression is true (and terminates once the expression becomes false). Bash did not support this control flow statement.

do {

do_work();

} while (condition);

is equivalent to

do_work();

while (condition) {

do_work();

}

13.Loops: for

In computer science a for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement.

Unlike many other kinds of loops, such as the while loop, the for loop is often distinguished by an explicit loop counter or loop variable. This allows the body of the for loop (the code that is being repeatedly executed) to know about the sequencing of each iteration. For loops are also typically used when the number of iterations is known before entering the loop. For loops are the shorthand way to make loops when the number of iterations is known, as a for loop can be written as a while loop.

The name for loop comes from the English word for, which is used as the keyword in most programming languages to introduce a for loop. The loop body is executed "for" the given values of the loop variable, though this is more explicit in the ALGOL version of the statement, in which a list of possible values and/or increments can be specified.

for (initialization; condition; increment-decrement) {

// Statements.

}

14.Control statements: if else

If–then(–else)

The if–then construct (sometimes called if–then–else) is common across many programming languages. Although the syntax varies quite a bit from language to language, the basic structure (in pseudocodeform) looks like this: (The example is actually perfectly valid Visual Basic or QuickBASIC syntax.)

IF (boolean condition)

(consequent)

ELSE

(alternative)

END IF

When an interpreter finds an If, it expects a boolean condition – for example, x > 0, which means "the variable x contains a number that is greater than zero" – and evaluates that condition. If the condition istrue, the statements following the then are executed. Otherwise, the execution continues in the following branch – either in the else block (which is usually optional), or if there is no else branch, then after the end If.

After either branch has been executed, control returns to the point after the end If.

  1. Control statements: switch

In programming, a switch, case, select or inspect statement is a type of selection control mechanism that exists in most imperative programminglanguages as  C. It is also included in several other types of languages. Its purpose is to allow the value of a variable or expression to control the flow of program execution via a multiway branch (or "goto", one of several labels). The main reasons for using a switch include improving clarity, by reducing otherwise repetitive coding, and (if the heuristics permit) also offering the potential for faster execution through easier compiler optimization in many cases.

In C and similarly-constructed languages, the lack of break keywords to cause fall through of program execution from one block to the next is used extensively. For example, if n==2, the fifth case statement will produce a match to the control variable. The next line outputs "n is an even number.". Execution then continues through the next 3 case statements and to the next line, which outputs "n is a prime number." this is a classic example of omitting the break line to allow for fall through. The break line after a case block causes the switch statement to conclude. If the user types in more than one digit, the default block is executed, producing an error message by executing the default code.

switch (n) {

case 0:

printf("You typed zero.");

break;

case 4:

printf("n is an even number.");

case 1:

case 9:

printf("n is a perfect square.");

break;

case 2:

printf("n is an even number.");

case 3:

case 5:

case 7:

printf("n is a prime number.");

break;

case 6:

case 8:

printf("n is an even number.");

break;

default:

printf("Only single-digit numbers are allowed.");

}

  1. Control statements: break, Continue

The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C.

The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.

Example:

#!/usr/bin/python

for letter in 'Python': # First Example

if letter == 'h':

break

print 'Current Letter :', letter

var = 10 # Second Example

while var > 0:

print 'Current variable value :', var

var = var -1

if var == 5:

break

print "Good bye!"

The continue statement in Python returns the control to the beginning of the while loop. The continuestatement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

The continue statement can be used in both while and for loops.

Example:

#!/usr/bin/python

for letter in 'Python': # First Example

if letter == 'h':

continue

print 'Current Letter :', letter

var = 10 # Second Example

while var > 0:

var = var -1

if var == 5:

continue

print 'Current variable value :', var

print "Good bye!"

  1. Goto and labels

C provides the infinitely-abusable goto statement, and labels to branch to. Formally, the goto statement is never necessary, and in practice it is almost always easy to write code without it.

Nevertheless, there are a few situations where gotos may find a place. The most common is to abandon processing in some deeply nested structure, such as breaking out of two or more loops at once. The break statement cannot be used directly since it only exits from the innermost loop. Thus:

for ( ... )

for ( ... ) {

...

if (disaster)

goto error;

}

...

error:

/* clean up the mess */

This organization is handy if the error-handling code is non-trivial, and if errors can occur in several places.

A label has the same form as a variable name, and is followed by a colon. It can be attached to any statement in the same function as the goto. The scope of a label is the entire function.

As another example, consider the problem of determining whether two arrays a and b have an element in common. One possibility is

for (i = 0; i < n; i++)

for (j = 0; j < m; j++)

if (a[i] == b[j])

goto found;

/* didn't find any common element */

...

found:

/* got one: a[i] == b[j] */

...

Code involving a goto can always be written without one, though perhaps at the price of some repeated tests or an extra variable. For example, the array search becomes

found = 0;

for (i = 0; i < n && !found; i++)

for (j = 0; j < m && !found; j++)

if (a[i] == b[j])

found = 1;

if (found)

/* got one: a[i-1] == b[j-1] */

...

else

/* didn't find any common element */

...

With a few exceptions like those cited here, code that relies on goto statements is generally harder to understand and to maintain than code without gotos. Although we are not dogmatic about the matter, it does seem that goto statements should be used rarely, if at all.

  1. Functions: Defining and accessing, passing arguments, Function prototypes

Functions break large computing tasks into smaller ones, and enable people to build on what others have done instead of starting over from scratch. Appropriate functions hide details of operation from parts of the program that don’t need to know about them, thus clarifying the whole, and easing the pain of making changes. C has been designed to make functions efficient and easy to use; C programs generally consist of many small functions rather than a few big ones. A program may reside in one or more source files. Source files may be compiled separately and loaded together, along with previously compiled functions from libraries. We will not go into that process here, however, since the details vary from system to system.

The standard clarifies the rules on the scope of names; in particular, it requires that there be only one definition of each external object. Initialization is more general: automatic arrays and structures may now be initialized. The C preprocessor has also been enhanced. New preprocessor facilities include a more complete set of conditional compilation directives, a way to create quoted strings from macro arguments, and better control over the macro expansion

process.

Each function definition has the form

return-type function-name(argument declarations)

]{

declarations and statements

}

The return statement is the mechanism for returning a value from the called function to its caller. Any expression can follow return:

return expression;

The expression will be converted to the return type of the function if necessary. Parentheses are often used around the expression, but they are optional.

Function prototypes

A function prototype is a function declaration or definition which includes information about the number and types of the arguments that the function takes.A declaration without any information about the arguments is not a prototype.

If a function is called with arguments of the wrong type, the presence of a prototype means that the actual argument is converted to the type of the formal argument ‘as if by assignment.

  1. External Variables and Scope

There are four different storage-class specification in ‘C’, automatic, external, static and register. They are identified as auto, extern, static and register respectively. Automatic variables are always declared within a function and are local to the function in which they are declared, that is their scope is confined to that function. Automatic variables defined in different functions will therefore be independent of one another. The location of the variable declarations within the program determine the automatic storage class, the keyword auto is not required at the

beginning of each variable declaration. These variables can be assigned initial value by including appropriate expressions within the variable declarations. An automatic variable does not retain its value once control is transferred out of its defining function. It means any value assigned to an automatic variable within a function will be lost once the function is exited. The scope of an automatic variable can be smaller than an entire function. Automatic variables can be declared within a single compound statement.

External variables are not confined to single functions. Their scopeextends from the point of definition through the remainder of the program. External variable are recognized globally, that means they are recognized throughout the program, they can be accessed from any function that falls within their scope. They retain their assigned values within their scope. Therefore, an external variable can be assigned a value within one function and this value can be used within another function. With the use of external variables one can transfer the information between functions.

External variable definitions and external variable declarations are not the same thing. An external variable definition is written in the same manner as an ordinary variable declaration. The storage-class specifier extern is not required in an external variable definition, because these variables will be identified by the location of their definition within the program. An external variable declaration must begin with the storage class specifier extern. The name of the external

variable and its data type must agree with the corresponding external variable definition that appears outside of the function.

Static variables are defined within individual functions and therefore have a same scope as automatic variables, i.e. they are local to the functions in which they are defined. Static variables retain their values throughout the program. Thus, if a function is exited and reentered

later, the static variables defined within that function will retain their former values. Static variables are defined within a function in the same manner as automatic variables, but its declaration must begin with the static storage class designation. They cannot be accessed outside of their defining function. Initial values can be included in static variable declarations.

  1. Functions:Recursion

Functions in C are recursive, which means that they can call themselves. Recursion tends to be less efficient than iterative code (i.e., code that uses loop-constructs), but in some cases may facilitate more elegant, easier to read code. The following code examples show two simple functions with both iterative and recursive implementations. The first calculates the greatest common divisor of two positive integers m and n, and the second computes the factorial of a non-negative integer n.

1 /* Iterative GCD: Returns the greatest common divisor of m and n. */

2 int gcd (int m, int n)

3 {

4 while (n) {

5 int tmp= n;

6 n= m%n;

7 m= tmp;

8 }

9 return m;

10 }

11

12 /* Recursive GCD */

13 int gcdr (int m, int n)

14 {

15 if (n==0) return m;

16 return gcdr(n, m%n);

17 }

Notice that the factorial functions below incorporate argument checking via the standard library

macro assert, which causes the program to terminate with an error message if the conditional

expression is FALSE.

1 /* Iterative factorial */

2 int factorial (int n)

3 {

4 int result= 1;

5 assert(n>=0);

6

7 while (n)

8 result *= n−−;

9 return result;

10 }

11

12 /* Recursive factorial */

13 int factorial r (int n)

14 {

15 assert(n>=0);

16 if (n==0) return 1;

17 return n * factorial r

  1. Arrays: Defining and processing

Arrays are declared in much the same manner as ordinary variables, except that each array name must be accompanied by a size specification (which specifies the number of elements). For a one-dimensional array, the size is specified by a positive integer constant, enclosed in square brackets. The generalization for multi-dimensional arrays is fairly obvious. Several valid array declarations are shown below:

int j[100];

double x[20];

double y[10][20];

Thus, j is a 100-element integer array, x is a 20-element floating point array, and y is a 10x20 floating-point array. Note that variable size array declarations, e.g.,

double a[n];

where n is an integer variable, are illegal in C.

It is sometimes convenient to define an array size in terms of a symbolic constant, rather than a fixed integer quantity. This makes it easier to modify a program that utilizes an array, since all references to the maximum array size can be altered by simply changing the value of the symbolic constant. This approach is used in many of the example programs employed in this course.

Like an ordinary variable, an array can be either local or global in extent, depending on whether the associated array declaration lies inside or outside, respectively, the scope of any of the functions which constitute the program. Both local and global arrays can be initialized via their declaration statements.10 For instance,

int j[5] = {1, 3, 5, 7, 9};

declares j to be a 5-element integer array whose elements have the initial values j[0]=1, j[1]=3, etc.

Single operations which involve entire arrays are not permitted in C. Thus, if x and y are similar arrays (i.e., the same data type, dimensionality, and size) then assignment operations, comparison operations, etc. involving these two arrays must be carried out on an element by element basis. This is usually accomplished within a loop (or within nested loops, for multi-dimensional arrays).

23.Strings: Defining and operations on strings

C has no string handling facilities built in; consequently, strings are defined as arrays of characters. C allows a character array to be represented by a character string rather than a list of characters, with the null terminating character automatically added to the end. For example, to store the string "Merkkijono", we would write

char string[] = "Merkkijono";

or

char string[] = {'M', 'e', 'r', 'k', 'k', 'i', 'j', 'o', 'n', 'o', '\0'};

In the first example, the string will have a null character automatically appended to the end by the compiler; by convention, library functions expect strings to be terminated by a null character. The latter declaration indicates individual elements, and as such the null terminator needs to be added manually.

Strings do not always have to be linked to an explicit variable. As you have seen already, a string of characters can be created directly as an unnamed string that is used directly (as with the printf functions.)

To create an extra long string, you will have to split the string into multiple sections, by closing the first section with a quote, and recommencing the string on the next line (also starting and ending in a quote):

char string[] = "This is a very, very long "

"string that requires two lines.";

While strings may also span multiple lines by putting the backslash character at the end of the line, this method is deprecated.

There is a useful library of string handling routines which you can use by including another header file.

#include <string.h> //new header file

This standard string library will allow various tasks to be performed on strings

24.Pointers: Declarations, Operations on pointers

Pointers are widely used in programming ; they are used to refer to memory location of another variable without using variable identifier itself. They are mainly used in linked lists and call by reference functions.

Declaring pointers can be very confusing and difficult at times (working with structures and pointer to pointers). To declare pointer variable we need to use * operator (indirection/dereferencing operator) before the variable identifier and after data type . Pointer can only point to variable of the same data type.

Syntax

Sample Code

  1. Datatype * identifier;

Copyright exforsys.com

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]