Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --------------------------- KEY ---------------------------
- #######'s = New section
- [[[[[[]]]]]] discriptor [[[[[[]]]]]] = sub-catagory
- ---------------------------
- code here; = code snippet
- ---------------------------
- --------------------------- END ---------------------------
- This document contains the following sections:
- - basic syntax (line 31)
- - data types (line 162)
- - variables (line 298)
- - constants (line 491)
- - operators (line 684)
- - decision making, (line 855)
- 'if, else if, else'
- statements
- - loops (line 1031)
- ###############################################################
- ###############################################################
- ###############################################################
- ### Basic Syntax ##############################################
- ###############################################################
- ###############################################################
- ###############################################################
- [[[[[[]]]]]] Tokens [[[[[[]]]]]]
- A C program consists of various tokens and a token is either
- a keyword, an identifier, a constant, a string literal
- (thse will all be explained later on), or a symbol.
- For example, the following C statement consists of five
- tokens −
- ----------
- printf("Hello, World! \n");
- ----------
- The individual tokens are −
- ---------------------------
- printf
- (
- "Hello, World! \n"
- )
- ;
- ---------------------------
- [[[[[[]]]]]] Semicolons [[[[[[]]]]]]
- In a C program, the semicolon is a statement terminator.
- That is, each individual statement must be ended with a semicolon.
- It indicates the end of one logical entity.
- Given below are two different statements −
- ---------------------------
- printf("Hello, World! \n");
- return 0;
- ---------------------------
- [[[[[[]]]]]] Comments [[[[[[]]]]]]
- Comments are like helping text in your C program and they are
- ignored by the compiler. They start with /* and terminate with
- the characters */ as shown below −
- ---------------------------
- // this is a single line comment
- /* This is a multi
- line comment */
- ---------------------------
- You cannot have comments within comments and they do not occur
- within a string or character literals.
- [[[[[[]]]]]] Identifiers [[[[[[]]]]]]
- A C identifier is a name used to identify a variable, function,
- or any other user-defined item. An identifier starts with a letter
- A to Z, a to z, or an underscore '_' followed by zero or more
- letters, underscores, and digits (0 to 9).
- C does not allow punctuation characters such as @, $, and % within
- identifiers. C is a case-sensitive programming language.
- Thus, Manpower and manpower are two different identifiers in C.
- Here are some examples of acceptable identifiers −
- mohd zara abc move_name a_123
- myname50 _temp j a23b9 retVal
- [[[[[[]]]]]] Keywords [[[[[[]]]]]]
- The following list shows the reserved words in C.
- These reserved words may not be used as constants or variables
- or any other identifier names.
- auto else long switch
- break enum register typedef
- case extern return union
- char float short unsigned
- const for signed void
- continue goto sizeof volatile
- default if static while
- do int struct _Packed
- double
- [[[[[[]]]]]] Whitespace in C [[[[[[]]]]]]
- A line containing only whitespace, possibly with a comment, is
- known as a blank line, and a C compiler totally ignores it.
- Whitespace is the term used in C to describe blanks, tabs, newline
- characters and comments. Whitespace separates one part of a statement
- from another and enables the compiler to identify where one element
- in a statement, such as int, ends and the next element begins.
- Therefore, in the following statement −
- ---------------------------
- int age;
- ---------------------------
- there must be at least one whitespace character (usually a space)
- between int and age for the compiler to be able to distinguish them.
- On the other hand, in the following statement −
- ---------------------------
- fruit=apples+oranges; // get the total fruit
- ---------------------------
- no whitespace characters are necessary between fruit and =, or
- between = and apples, although you are free to include some
- if you wish to increase readability.
- ###############################################################
- ###############################################################
- ###############################################################
- ### Data Types ################################################
- ###############################################################
- ###############################################################
- ###############################################################
- Data types in c refer to an extensive system used for declaring
- variables or functions of different types. The type of a variable
- determines how much space it occupies in storage and how the bit
- pattern stored is interpreted.
- The types in C can be classified as follows −
- 1 Basic Types:
- They are arithmetic types and are further classified into:
- (a) integer types and
- (b) floating-point types.
- 2 Enumerated types:
- They are again arithmetic types and they are used to define
- variables that can only assign certain discrete integer values
- throughout the program.
- 3 The type void:
- The type specifier void indicates that no value is available.
- 4 Derived types:
- They include
- (a) Pointer types,
- (b) Array types,
- (c) Structure types,
- (d) Union types and
- (e) Function types.
- The array types and structure types are referred collectively
- as the aggregate types. The type of a function specifies the
- type of the function's return value. We will see the basic
- types in the following section, where as other types will
- be covered in the upcoming chapters.
- [[[[[[]]]]]] Integer Types [[[[[[]]]]]]
- The following table provides the details of standard integer
- types with their storage sizes and value ranges −
- ______________________________________________________________
- Type Storage size Value range
- ______________________________________________________________
- char 1 byte -128 to 127 OR 0 to 255
- unsigned char 1 byte 0 to 255
- signed char 1 byte -128 to 127
- int 2 OR 4 bytes -32,768 to 32,767
- OR -2,147,483,648 to 2,147,483,647
- unsigned int 2 OR 4 bytes 0 to 65,535 OR 0 to 4,294,967,295
- short 2 bytes -32,768 to 32,767
- unsigned short 2 bytes 0 to 65,535
- long 4 bytes -2,147,483,648 to 2,147,483,647
- unsigned long 4 bytes 0 to 4,294,967,295
- _______________________________________________________________
- To get the exact size of a type or a variable on a particular
- platform, you can use the sizeof operator.
- The expressions sizeof(type) yields the storage size of the
- object or type in bytes. Given below is an example to get the
- size of int type on any machine −
- ---------------------------
- #include <stdio.h>
- #include <limits.h>
- int main() {
- printf("Storage size for int : %d \n", sizeof(int));
- return 0;
- }
- ---------------------------
- [[[[[[]]]]]] Floating-Point Types [[[[[[]]]]]]
- The following table provide the details of standard floating-point
- types with storage sizes and value ranges and their precision −
- _______________________________________________________________
- Type Storage Value range Precision
- ________________size___________________________________________
- float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
- double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
- long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places
- _______________________________________________________________
- The header file float.h defines macros that allow you to use
- these values and other details about the binary representation
- of real numbers in your programs. The following example prints
- the storage space taken by a float type and its range values −
- ---------------------------
- #include <stdio.h>
- #include <float.h>
- int main() {
- printf("Storage size for float : %d \n", sizeof(float));
- printf("Minimum float positive value: %E\n", FLT_MIN );
- printf("Maximum float positive value: %E\n", FLT_MAX );
- printf("Precision value: %d\n", FLT_DIG );
- return 0;
- }
- ---------------------------
- [[[[[[]]]]]] The void type [[[[[[]]]]]]
- Function returns as void:
- There are various functions in C which do not return any value
- or you can say they return void. A function with no return value
- has the return type as void. For example, void exit (int status);
- Function arguments as void:
- There are various functions in C which do not accept any parameter.
- A function with no parameter can accept a void. For example,
- int rand(void);
- Pointers to void:
- A pointer of type void * represents the address of an object,
- but not its type. For example, a memory allocation function
- void *malloc( size_t size ); returns a pointer to void which
- can be casted to any data type.
- ###############################################################
- ###############################################################
- ###############################################################
- ### Variables #################################################
- ###############################################################
- ###############################################################
- ###############################################################
- A variable is nothing but a name given to a storage area that our
- programs can manipulate. Each variable in C has a specific type,
- which determines the size and layout of the variable's memory;
- the range of values that can be stored within that memory; and
- the set of operations that can be applied to the variable.
- The name of a variable can be composed of letters, digits,
- and the underscore character. It must begin with either a
- letter or an underscore. Upper and lowercase letters are distinct
- because C is case-sensitive. Based on the basic types explained
- in the previous chapter, there will be the following basic
- variable types −
- 1 char:
- Typically a single octet(one byte). This is an integer type.
- 2 int:
- The most natural size of integer for the machine.
- 3 float:
- A single-precision floating point value.
- 4 double:
- A double-precision floating point value.
- 5 void:
- Represents the absence of type.
- C programming language also allows to define various other types
- of variables, which we will cover in subsequent chapters like
- Enumeration, Pointer, Array, Structure, Union, etc. For this
- chapter, let us study only basic variable types.
- [[[[[[]]]]]] Variable Definition in C [[[[[[]]]]]]
- A variable definition tells the compiler where and how much
- storage to create for the variable. A variable definition
- specifies a data type and contains a list of one or more
- variables of that type as follows −
- ---------------------------
- type variable_list;
- ---------------------------
- Here, type must be a valid C data type including
- char, w_char, int, float, double, bool, or any user-defined object;
- and variable_list may consist of one or more identifier names
- separated by commas. Some valid declarations are shown here −
- ---------------------------
- int i, j, k;
- char c, ch;
- float f, salary;
- double d;
- ---------------------------
- The line int i, j, k; declares and defines the variables i, j, and k;
- which instruct the compiler to create variables named i, j and k of
- type int.
- Variables can be initialized (assigned an initial value) in their
- declaration. The initializer consists of an equal sign followed by
- a constant expression as follows −
- ---------------------------
- type variable_name = value;
- ---------------------------
- Some examples are −
- ---------------------------
- extern int d = 3, f = 5; // declaration of d and f.
- int d = 3, f = 5; // definition and initializing d and f.
- byte z = 22; // definition and initializes z.
- char x = 'x'; // the variable x has the value 'x'.
- ---------------------------
- For definition without an initializer: variables with static storage
- duration are implicitly initialized
- with NULL (all bytes have the value 0); the initial
- value of all other variables are undefined.
- [[[[[[]]]]]] Variable Declaration in C [[[[[[]]]]]]
- A variable declaration provides assurance to the compiler that
- there exists a variable with the given type and name so that the
- compiler can proceed for further compilation without requiring
- the complete detail about the variable. A variable definition
- has its meaning at the time of compilation only, the compiler
- needs actual variable definition at the time of linking the
- program.
- A variable declaration is useful when you are using multiple
- files and you define your variable in one of the files which
- will be available at the time of linking of the program. You
- will use the keyword extern to declare a variable at any place.
- Though you can declare a variable multiple times in your C program,
- it can be defined only once in a file, a function, or a block of code.
- Example
- Try the following example, where variables have been declared
- at the top, but they have been defined and initialized inside
- the main function −
- ---------------------------
- #include <stdio.h>
- // Variable declaration:
- extern int a, b;
- extern int c;
- extern float f;
- int main () {
- /* variable definition: */
- int a, b;
- int c;
- float f;
- /* actual initialization */
- a = 10;
- b = 20;
- c = a + b;
- printf("value of c : %d \n", c);
- f = 70.0/3.0;
- printf("value of f : %f \n", f);
- return 0;
- }
- ---------------------------
- When the above code is compiled and executed, it produces the
- following result −
- ---------------------------
- value of c : 30
- value of f : 23.333334
- ---------------------------
- The same concept applies on function declaration where you
- provide a function name at the time of its declaration and
- its actual definition can be given anywhere else. For example −
- ---------------------------
- // function declaration
- int func();
- int main() {
- // function call
- int i = func();
- }
- // function definition
- int func() {
- return 0;
- }
- ---------------------------
- [[[[[[]]]]]] Lvalues and Rvalues in C [[[[[[]]]]]]
- There are two kinds of expressions in C −
- lvalue −- Expressions that refer to a memory location are called
- "lvalue" expressions. An lvalue may appear as either the left-hand
- or right-hand side of an assignment.
- rvalue −- The term rvalue refers to a data value that is stored
- at some address in memory. An rvalue is an expression that cannot
- have a value assigned to it which means an rvalue may appear on
- the right-hand side but not on the left-hand side of an assignment.
- Variables are lvalues and so they may appear on the left-hand side
- of an assignment. Numeric literals are rvalues and so they may not
- be assigned and cannot appear on the left-hand side. Take a look at
- the following valid and invalid statements −
- ---------------------------
- int g = 20; // valid statement
- 10 = 20; // invalid statement; would generate compile-time error
- ---------------------------
- ###############################################################
- ###############################################################
- ###############################################################
- ### Constants #################################################
- ###############################################################
- ###############################################################
- ###############################################################
- Constants refer to fixed values that the program may not alter
- during its execution. These fixed values are also called literals.
- Constants can be of any of the basic data types like an integer
- constant, a floating constant, a character constant, or a string
- literal. There are enumeration constants as well.
- Constants are treated just like regular variables except that
- their values cannot be modified after their definition.
- [[[[[[]]]]]] Integer Literals [[[[[[]]]]]]
- An integer literal can be a decimal, octal, or hexadecimal constant.
- A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0
- for octal, and nothing for decimal.
- An integer literal can also have a suffix that is a combination of
- U and L, for unsigned and long, respectively. The suffix can be
- uppercase or lowercase and can be in any order.
- Here are some examples of integer literals −
- ---------------------------
- 212 /* Legal */
- 215u /* Legal */
- 0xFeeL /* Legal */
- 078 /* Illegal: 8 is not an octal digit */
- 032UU /* Illegal: cannot repeat a suffix */
- ---------------------------
- Following are other examples of various types of integer literals −
- ---------------------------
- 85 /* decimal */
- 0213 /* octal */
- 0x4b /* hexadecimal */
- 30 /* int */
- 30u /* unsigned int */
- 30l /* long */
- 30ul /* unsigned long */
- ---------------------------
- [[[[[[]]]]]] Floating-point Literals [[[[[[]]]]]]
- A floating-point literal has an integer part, a decimal point,
- a fractional part, and an exponent part. You can represent floating
- point literals either in decimal form or exponential form.
- While representing decimal form, you must include the decimal
- point, the exponent, or both; and while representing exponential
- form, you must include the integer part, the fractional part,
- or both. The signed exponent is introduced by e or E.
- Here are some examples of floating-point literals −
- ---------------------------
- 3.14159 /* Legal */
- 314159E-5L /* Legal */
- 510E /* Illegal: incomplete exponent */
- 210f /* Illegal: no decimal or exponent */
- .e55 /* Illegal: missing integer or fraction */
- ---------------------------
- [[[[[[]]]]]] Character Constants [[[[[[]]]]]]
- Character literals are enclosed in single quotes, e.g., 'x' can be
- stored in a simple variable of char type.
- A character literal can be a plain character (e.g., 'x'), an escape
- sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').
- There are certain characters in C that represent special meaning
- when preceded by a backslash for example, newline (\n) or tab (\t).
- ________________________________________________________________
- Escape sequence Meaning
- ________________________________________________________________
- \\ \ character
- \' ' character
- \" " character
- \? ? character
- \a Alert or bell
- \b Backspace
- \f Form feed
- \n Newline
- \r Carriage return
- \t Horizontal tab
- \v Vertical tab
- \ooo Octal number of one to three digits
- \xhh . . . Hexadecimal number of one or more digits
- _________________________________________________________________
- Following is the example to show a few escape sequence characters −
- ---------------------------
- #include <stdio.h>
- int main() {
- printf("Hello\tWorld\n\n");
- return 0;
- }
- ---------------------------
- [[[[[[]]]]]] String Literals [[[[[[]]]]]]
- String literals or constants are enclosed in double quotes "".
- A string contains characters that are similar to character
- literals: plain characters, escape sequences, and universal characters.
- You can break a long line into multiple lines using string
- literals and separating them using white spaces.
- Here are some examples of string literals. All the three forms
- are identical strings.
- ---------------------------
- "hello, dear"
- "hello, \
- dear"
- "hello, " "d" "ear"
- ---------------------------
- [[[[[[]]]]]] Define Constants [[[[[[]]]]]]
- There are two simple ways in C to define constants −
- 1 Using #define preprocessor.
- 2 Using const keyword.
- ---------------------------
- #define identifier value
- ---------------------------
- The following example explains it in detail −
- ---------------------------
- #include <stdio.h>
- #define LENGTH 10
- #define WIDTH 5
- #define NEWLINE '\n'
- int main() {
- int area;
- area = LENGTH * WIDTH;
- printf("value of area : %d", area);
- printf("%c", NEWLINE);
- return 0;
- }
- ---------------------------
- [[[[[[]]]]]] The const Keyword [[[[[[]]]]]]
- You can use const prefix to declare constants with a
- specific type as follows −
- ---------------------------
- const type variable = value;
- ---------------------------
- The following example explains it in detail −
- ---------------------------
- #include <stdio.h>
- int main() {
- const int LENGTH = 10;
- const int WIDTH = 5;
- const char NEWLINE = '\n';
- int area;
- area = LENGTH * WIDTH;
- printf("value of area : %d", area);
- printf("%c", NEWLINE);
- return 0;
- }
- ---------------------------
- ###############################################################
- ###############################################################
- ###############################################################
- ### Operators #################################################
- ###############################################################
- ###############################################################
- ###############################################################
- An operator is a symbol that tells the compiler to perform
- specific mathematical or logical functions. C language is
- rich in built-in operators and provides the following types
- of operators −
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Misc Operators
- We will, in this chapter, look into the way each operator works.
- [[[[[[]]]]]] Arithmetic Operators [[[[[[]]]]]]
- The following table shows all the arithmetic operators supported
- by the C language. Assume variable A holds 10 and variable B
- holds 20 then −
- ___________________________________________________________________
- Operator Description Example
- ___________________________________________________________________
- + Adds two operands. A + B = 30
- − Subtracts second operand from the first. A − B = -10
- * Multiplies both operands. A * B = 200
- / Divides numerator by de-numerator. B / A = 2
- % Modulus Operator and remainder B % A = 0
- of after an integer division.
- ++ Increment operator increases A++ = 11
- the integer value by one.
- -- Decrement operator decreases the A-- =
- integer value by one.
- ___________________________________________________________________
- [[[[[[]]]]]] Relational Operators [[[[[[]]]]]]
- The following table shows all the relational operators supported
- by C. Assume variable A holds 10 and variable B holds 20 then −
- ________________________________________________________
- Operator Description Example
- ________________________________________________________
- == Checks if the values of two (A == B) is not true.
- operands are equal or not.
- If yes, then the condition
- becomes true.
- != Checks if the values of two (A != B) is true.
- operands are equal or not.
- If the values are not equal,
- then the condition becomes
- true.
- > Checks if the value of left (A > B) is not true.
- operand is greater than the
- value of right operand. If
- yes, then the condition
- becomes true.
- < Checks if the value of left (A < B) is true.
- operand is less than the
- value of right operand.
- If yes, then the condition
- becomes true.
- >= Checks if the value of left (A >= B) is not true.
- operand is greater than or
- equal to the value of right
- operand. If yes, then the
- condition becomes true.
- <= Checks if the value of left (A <= B) is true.
- operand is less than or
- equal to the value of right
- operand. If yes, then the
- condition becomes true.
- ________________________________________________________
- [[[[[[]]]]]] Logical Operators [[[[[[]]]]]]
- Following table shows all the logical operators supported
- by C language. Assume variable A holds 1 and variable B
- holds 0, then −
- ___________________________________________________________________
- Operator Description Example
- ___________________________________________________________________
- && Called Logical AND operator. If both (A && B) is false.
- the operands are non-zero, then the
- condition becomes true.
- || Called Logical OR Operator. If any (A || B) is true.
- of the two operands is non-zero, then
- the condition becomes true.
- ! Called Logical NOT Operator. It is !(A && B) is true.
- used to reverse the logical state of
- its operand. If a condition is true,
- then Logical NOT operator will make it false.
- ___________________________________________________________________
- [[[[[[]]]]]] Assignment Operators [[[[[[]]]]]]
- The following table lists the assignment operators
- supported by the C language −
- _________________________________________________________________
- Operator Description Example
- _________________________________________________________________
- = Simple assignment operator. Assigns C = A + B will
- values from right side operands to assign the value
- left side operand of A + B to C
- += Add AND assignment operator. It C += A is equivalent
- adds the right operand to the left to C = C + A
- operand and assign the result to the
- left operand.
- -= Subtract AND assignment operator. It C -= A is equivalent
- subtracts the right operand from the to C = C - A
- left operand and assigns the result to
- the left operand.
- *= Multiply AND assignment operator. It C *= A is equivalent
- multiplies the right operand with the to C = C * A
- left operand and assigns the result
- to the left operand.
- /= Divide AND assignment operator. It C /= A is equivalent
- divides the left operand with the to C = C / A
- right operand and assigns the result
- to the left operand.
- %= Modulus AND assignment operator. It C %= A is equivalent
- takes modulus using two operands and to C = C % A
- assigns the result to the left operand.
- <<= Left shift AND assignment operator. C <<= 2 is same as
- C = C << 2
- >>= Right shift AND assignment operator. C >>= 2 is same as
- C = C >> 2
- &= Bitwise AND assignment operator. C &= 2 is same as
- C = C & 2
- ^= Bitwise exclusive OR and assignment C ^= 2 is same as
- operator. C = C ^ 2
- |= Bitwise inclusive OR and assignment C |= 2 is same as
- operator. C = C | 2
- _________________________________________________________________
- ###############################################################
- ###############################################################
- ###############################################################
- ### Decision Making and IF statements #########################
- ###############################################################
- ###############################################################
- ###############################################################
- Decision making structures require that the programmer
- specifies one or more conditions to be evaluated or tested
- by the program, along with a statement or statements
- to be executed if the condition is determined to be true,
- and optionally, other statements to be executed if the
- condition is determined to be false.
- Show below is the general form of a typical decision
- making structure found in most of the programming languages −
- NOTE: This IS an 'if statement'
- START
- |
- V
- condition ---------
- | |
- V |
- if condition if condition
- is true is false
- | |
- V |
- code |
- | |
- V |
- END <-------------
- NOTE: This IS an 'if statement'
- C programming language assumes any non-zero and non-null
- values as true, and if it is either zero or null, then
- it is assumed as false value.
- C programming language provides the following types of
- decision making statements.
- if statement: An if statement consists of a boolean
- expression followed by one or more
- statements.
- if...else statement: An if statement can be followed
- by an optional else statement, which
- executes when the Boolean expression
- is false.
- nested if statements: You can use one if or else if
- statement inside another if or
- else if statement(s).
- switch statement: A switch statement allows a variable
- to be tested for equality against
- a list of values.
- nested switch statements: You can use one switch statement
- inside another switch
- statement(s).
- [[[[[[]]]]]] if-else statement [[[[[[]]]]]]
- An if statement can be followed by an optional else
- statement, which executes when the Boolean
- expression is false.
- ---------------------------
- if(boolean_expression) {
- /* statement(s) will execute if true */
- } else {
- /* statement(s) will execute if false */
- }
- ---------------------------
- If the Boolean expression evaluates to true, then the
- if block will be executed, otherwise, the else block
- will be executed.
- C programming language assumes any non-zero and non-null
- values as true, and if it is either zero or null, then
- it is assumed as false value.
- START
- |
- V
- condition ---------
- | |
- V |
- if condition if condition
- is true is false
- | |
- V V
- if code else code
- | |
- V |
- END <-------------
- [[[[[[]]]]]] 'if- else if - else' statement [[[[[[]]]]]]
- An if statement can be followed by an optional
- else if...else statement, which is very useful to
- test various conditions using single if...else if
- statement.
- When using if...else if..else statements, there are
- few points to keep in mind −
- -An if can have zero or one else's and it
- must come after any else if's.
- -An if can have zero to many else if's and they
- must come before the else.
- -Once an else if succeeds, none of the remaining else
- if's or else's will be tested.
- The syntax of an if...else if...else statement in
- C programming language is −
- ---------------------------
- if(boolean_expression 1) {
- /* Executes when the boolean expression 1 is true */
- } else if( boolean_expression 2) {
- /* Executes when the boolean expression 2 is true */
- } else if( boolean_expression 3) {
- /* Executes when the boolean expression 3 is true */
- } else {
- /* executes when the none of the above condition is true */
- }
- ---------------------------
- The flow is as follows
- START
- |
- V
- condition ---------
- | |
- V |
- if condition if condition
- is true is false
- | |
- V |
- if code |
- | |
- | V
- | else-if condition --------------
- | | |
- | V |
- | else-if condition else-if condition
- | is true is false
- | | |
- | V |
- | else-if code |
- | | |
- | | |
- | | |
- | | |
- | | |
- | | else code
- | | |
- V | |
- END <------------------------------------
- ###############################################################
- ###############################################################
- ###############################################################
- ### Loops #####################################################
- ###############################################################
- ###############################################################
- ###############################################################
- You may encounter situations, when a block of code needs
- to be executed several number of times. In general,
- statements are executed sequentially: The first
- statement in a function is executed first, followed
- by the second, and so on.
- Programming languages provide various control structures
- that allow for more complicated execution paths.
- A loop statement allows us to execute a statement or group
- of statements multiple times. Given below is the general
- form of a loop statement in most of the programming languages −
- break statement: Terminates the loop or switch
- statement and transfers execution
- to the statement immediately
- following the loop or switch.
- continue statement: Causes the loop to skip the
- remainder of its body and
- immediately retest its condition
- prior to reiterating.
- goto statement: Transfers control to the labeled
- statement.
- NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
- [[[[[[]]]]]] While loop [[[[[[]]]]]]
- A while loop in C programming repeatedly executes
- a target statement as long as a given condition is true.
- The syntax of a while loop in C programming language is −
- ---------------------------
- while(condition) {
- statement(s);
- }
- ---------------------------
- Here, statement(s) may be a single statement or
- a block of statements. The condition may be any
- expression, and true is any nonzero value. The
- loop iterates while the condition is true.
- When the condition becomes false, the program
- control passes to the line immediately following
- the loop.
- START
- |
- V
- ---> condition -----------
- | | |
- | V |
- | if condition if condition
- | is true is false
- | | |
- | V V
- ------- code END
- [[[[[[]]]]]] For loop [[[[[[]]]]]]
- A for loop is a repetition control structure that
- allows you to efficiently write a loop that needs
- to execute a specific number of times.
- The syntax of a for loop in C programming language is −
- ---------------------------
- for ( init; condition; increment ) {
- statement(s);
- }
- ---------------------------
- Here is the flow of control in a 'for' loop −
- init: The init step is executed first, and only once.
- This step allows you to declare and initialize any
- loop control variables. You are not required to put
- a statement here, as long as a semicolon appears.
- condition: Next, the condition is evaluated. If it is
- true, the body of the loop is executed. If it is
- false, the body of the loop does not execute and
- the flow of control jumps to the next statement
- just after the 'for' loop.
- increment: After the body of the 'for' loop executes, the
- flow of control jumps back up to the increment
- statement. This statement allows you to update
- any loop control variables. This statement can
- be left blank, as long as a semicolon appears
- after the condition.
- The condition is now evaluated again. If it is true, the loop
- executes and the process repeats itself (body of loop, then
- increment step, and then again condition). After the condition
- becomes false, the 'for' loop terminates.
- START
- |
- V
- init
- |
- V
- --> condition --------
- | | |
- | V |
- | if condition if condition
- | is true is false
- | | |
- | V |
- | code |
- | | |
- | V |
- --- increment |
- |
- V
- END
- [[[[[[]]]]]] infinite loop [[[[[[]]]]]]
- A loop becomes an infinite loop if a condition
- never becomes false. The for loop is traditionally
- used for this purpose. Since none of the three
- expressions that form the 'for' loop are required,
- you can make an endless loop by leaving the conditional
- expression empty.
- ---------------------------
- #include <stdio.h>
- int main () {
- for( ; ; ) {
- printf("This loop will run forever.\n");
- }
- return 0;
- }
- ---------------------------
- When the conditional expression is absent, it is assumed to
- be true. You may have an initialization and increment
- expression, but C programmers more commonly use the for(;;)
- construct to signify an infinite loop.
- [[[[[[]]]]]] Do while loop [[[[[[]]]]]]
- Unlike for and while loops, which test the loop condition
- at the top of the loop, the do...while loop in C programming
- checks its condition at the bottom of the loop.
- A do...while loop is similar to a while loop, except the fact
- that it is guaranteed to execute at least one time.
- The syntax of a do...while loop in C programming language is −
- ---------------------------
- do {
- statement(s);
- } while( condition );
- ---------------------------
- Notice that the conditional expression appears at the end
- of the loop, so the statement(s) in the loop executes once
- before the condition is tested.
- If the condition is true, the flow of control jumps back
- up to do, and the statement(s) in the loop executes again.
- This process repeats until the given condition becomes
- false.
- START
- |
- V
- ------> code
- | |
- | V
- | condition -----------
- | | |
- | V |
- | if condition if condition
- | is true is false
- | | |
- |_________| V
- END
- -- THIS LINE IS INTENTIONALLY LEFT BLANK --
- -- THIS LINE IS INTENTIONALLY LEFT BLANK --
- -- THIS LINE IS INTENTIONALLY LEFT BLANK --
- -- THIS LINE IS INTENTIONALLY LEFT BLANK --
- -- THIS LINE IS INTENTIONALLY LEFT BLANK --
- -- THIS LINE IS INTENTIONALLY LEFT BLANK --
- -- THIS LINE IS INTENTIONALLY LEFT BLANK --
- -- THIS LINE IS INTENTIONALLY LEFT BLANK --
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement