Concept Notes

13
Short Notes “C” Concise Notes Facts about C C is a general-purpose high level and case sensitive programming language that was originally developed by Dennis Ritchie AT & T’s Bell Laboratories of USA in 1972. Algorithm An Algorithm is a step by step method for solving a problem by breaking a larger task down so that each step can be carried out easily. Flowchart Flowchart is pictorial representation of step by step solution of a problem by which flow of problem can be understood. Program A computer program is a set of instructions for a computer to perform a specific task. The C Character Set All the possible characters which we can use to built a c program constitute c character set. A character denotes any alphabet, digit or special symbol used to represent information. Keywords Keywords are the reserved words whose meaning has already been explained to the C compiler . They cannot be used as variable names. There are only 32 keywords available in C. For example do, while, for, int, char, float, etc are keywords. Statements A program is made of a number of statements. In C, all statements must end with a semicolon (;). For Example a=b+c; is a statement. Variables An entity that may vary during program execution is called a variable. Variable names are names given to locations in memory. Operator Operators are symbols which take one or more operands or expressions and perform arithmetic or logical computations. Broadly speaking the types of operators available in C are as follows: Arithmetic Assignment Logical relational Bitwise Arithmetic operators present in C are Web Address: https://sites.google.com/site/nitinpandey03/ Page 1

description

Concept Notes of C Programming language by Nitin Pandey, Lecturer, Faculty of Computer Science and Application, Amrapali Institute, Haldwani.

Transcript of Concept Notes

Page 1: Concept Notes

Short Notes “C”

Concise Notes

Facts about CC is a general-purpose high level and case sensitive programming language that was originally developed by Dennis Ritchie AT & T’s Bell Laboratories of USA in 1972.

AlgorithmAn Algorithm is a step by step method for solving a problem by breaking a larger task down so that each step can be carried out easily.

FlowchartFlowchart is pictorial representation of step by step solution of a problem by which flow of problem can be understood.

ProgramA computer program is a set of instructions for a computer to perform a specific task.

The C Character SetAll the possible characters which we can use to built a c program constitute c character set. A character denotes any alphabet, digit or special symbol used to represent information.

KeywordsKeywords are the reserved words whose meaning has already been explained to the C compiler . They cannot be used as variable names. There are only 32 keywords available in C. For example do, while, for, int, char, float, etc are keywords.

StatementsA program is made of a number of statements. In C, all statements must end with a semicolon (;). For Example a=b+c; is a statement.

VariablesAn entity that may vary during program execution is called a variable. Variable names are names given to locations in memory.

OperatorOperators are symbols which take one or more operands or expressions and perform arithmetic or logical computations. Broadly speaking the types of operators available in C are as follows:

Arithmetic Assignment Logical relational Bitwise

Arithmetic operators present in C are+ , -, /, *, %, - -  Decrement (post and pre) ++  Increment (post and pre)

Assignment operators present in C are as follows:*=   Multiply, /=   Divide, %=   Modulus, +=   Add, -=  Subtract.

Relational operators present in C are as follows:= =   Equal to, !=   Not Equal to, >   Greater than, <   Less than, >=   Greater than or equal to, <=   Less than or equal to

Logical operators present in C are as follows:

&&   Logical AND, ||   Logical OR, !   Logical NOT

Bitwise operators present in C are&   AND, |   Inclusive OR, ^   Exclusive OR, <<   Shift Left, >>   Shift Right, ~   One's compliment

Web Address: https://sites.google.com/site/nitinpandey03/ Page 1

Page 2: Concept Notes

Short Notes “C”

Operators Categories: Postfix operators, which follow a single operand. In post fix operators at first assignment is done, then operations is

performed. Unary prefix operators, which precede a single operand. In prefix operators at first operation is performed, then

assignment takes place. Binary operators, which take two operands and perform a variety of arithmetic and logical operations. The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third

expression, depending on the evaluation of the first expression. Assignment operators, which assign a value to a variable. The comma operator, which guarantees left-to-right evaluation of comma-separated expressions.←Precedence of C Operators:

← Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:←

Category  Operator  Associativity 

Logical Not(Unary)  ! Right to left 

Arithmetic  * / %  Left to right 

Arithmetic + -  Left to right 

Relational   < <= > >=  Left to right 

Equality   = = !=  Left to right 

Logical AND  &&  Left to right 

Logical OR  ||  Left to right 

Assignment  = += -= *= /= %= >>= <<= &= ^= |=  Right to left 

ExpressionsExpressions combine variables and constants to create new values. or An expression can be a combination of operator and operands or constants. Statements are expressions, assignments, function calls, or control flow statements which make up C programs. For example a=b+c is an expression.

OperandsOperands are variables or expressions which are used in operators to evaluate the expression. Combination of operands and operators form an expression. For instance a = b + c; denote an expression in which there are 3 operands namely a, b, c and one operator namely +.

CommentsComments are used to give additional useful information inside a C Program. All the information which is written inside the comments are ignored by the compiler. There are two types of comments.

1. Single line comment: //2. Multiple line comment: /* */

Data typesData type determines a set of values that a variable can have, and the possible operations that can be performed on these values. For the declaration of each variable we have to attach some data type.

The data type defines:1. the amount of storage allocated to variables. 2. the values that they can accept.

Web Address: https://sites.google.com/site/nitinpandey03/ Page 2

Page 3: Concept Notes

Short Notes “C”

3. the operations that can be performed on variables. Data types can be divided into three types.

a. Basic or Primitive data types.b. User defined data types.c. Derived data types.

C has the following basic built-in datatypes.Data Type Range Size(bytes) Format Specifierchar -128 to 127 1 cint -32768 to 32767 2 dfloat 3.4e-38 to 3.4e+38 4 Fdouble 1.7e-308 to 1.7e+308 8 Lflong int -2147483648 to 2147483647 4 ld

User defined data types: The data types which are defined by the users are called user defined data types. The user defined data types are Structure, Union, Enumeration.

Derived data types: The data types which are derived form basic data types are called derived data types. Arrays, Pointers, Functions are the derived data types.

IdentifiersAn identifier refers to the name of an object. It can be a variable name, a function name, a structure name, a union name, etc.

ConstantsA constant is an entity whose value remains same throughout the execution of the program. It can not be placed on the left side of an assignment operator. It can only be placed on the right side of the assignment operator. In c Constant are classified as:

1. Literal constants2. Qualified constants3. Symbolic constants

Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'. Some characters can't be represented in this way, so we use a 2 character sequence this is called escape sequence.

Escape Sequence

Escape Sequence Meaning

\n Sends the cursor to the next line.

\t Horizontal Tab

\a Alert( Used to generate beep)

\c Carriage return(sends the cursor to the beginning of the current line)

\b back space(sends the cursor one character to the left)

\’ prints the single quotation mark

\’’ prints the double quotation mark

\\ prints the back slash character

\? prints the question mark

Flow in CC provides three sytles of flow.

Web Address: https://sites.google.com/site/nitinpandey03/ Page 3

Page 4: Concept Notes

Short Notes “C”

Default flow Branching Looping

Default flow: It is a line by line flow. It means the statement which comes first, will be executed first.

Decision Making (Branching) control Structure : Branching decides what actions to take. Branching is so called because the program chooses to follow one branch or another. Decision control structure is used for branching. It includes if, if-else, nested if-else, switch, conditional operator.

if statementIt takes an expression in parenthesis and an statement or block of statements. if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.if statements take the following form:

if (expression) statement;

or

if (expression) { Block of statements; }

if-else statement: In if-else statement either if block gets executed or else block gets executed depends which one is true. if-else statements take the following form:

if (expression) { Block of statements; }else { Block of statements; }

Ternary Operator or Conditional Operator:? : Operator The ? : operator is just like an if ... else statement except that because it is an operator you can use it within expressions.? : is a ternary operator in that it takes three values, this is the only ternary operator C has.

switch statement:The switch statement is much like a nested if .. else statement. Its mostly a matter of preference which you use, switch statement can be slightly more efficient and easier to read. Syntax is given below:switch ( expression ) { case constant 1 : do this ; case constant 2 : do this ; case constant 3 : do this ; ..default : do this ; }

goto statement: Its also a control structure that transfers the control of a program from one part to another part. In a difficult programming situation it seems so easy to use a goto to take the control where you want.

Web Address: https://sites.google.com/site/nitinpandey03/ Page 4

Page 5: Concept Notes

Short Notes “C”

The big problem with gotos is that when we do use them we can never be sure how we got to a certain point in our code. They obscure the flow of control.

Loop control structure: Loops provide a way to repeat commands and control how many times they are repeated. Loop control structure includes while, for, do-while loops.

while loopIf the test condition of while loop is true then all the statements within loop get executed. This cycle repeats until the test condition evaluates to false. Basic syntax of while loop is as follows:

while ( expression or test condition ){ Single statement or Block of statements;}

for loopfor loop is similar to while, it's just written differently. for statements are often used to process lists such a range of numbers. Basic syntax of for loop is as follows:

for( expression1; expression2; expression3){ Single statement or Block of statements;}

In the above syntax:← expression1 - Initialisese variables. ← expression2 - Condtional expression, as long as this condition is true, loop will keep executing. ← expression3 - expression3 is the modifier which may be simple increment of a variable.

do...while loopdo ... while is just like a while loop except that the test condition is checked at the end of the loop rather than the start. This has the effect that the content of the loop are always executed at least once. Basic syntax of do...while loop is as follows:

do{ Single statement or Block of statements;}while(expression);

break and continue statementsC provides two commands to control how we loop:

← break -- exit form loop or switch. ← continue -- skip 1 iteration of loop.

PointerPointers are designed for storing memory address i.e. the address of another variable. It means pointer is a variable which is used to store the address of another variable. There are two new operators we need to know to work with pointers. The "address of" operator '&' and the "dereferencing" operator '*'. Both are prefix unary operators.For example: int *a; //Declaration of pointera=&b; // Assigning address of b to pointer a.

Function

Web Address: https://sites.google.com/site/nitinpandey03/ Page 5

Page 6: Concept Notes

Short Notes “C”

A function is a self-contained block of code that performs a specific task. It has a name and it is reusable . it can be executed from as many different parts in a Program as required, it can also return a value to calling program. All executable code resides within a function. We pass information to the function called arguments which  specified when the function is called. A function either can return a value or returns nothing.Function is a subprogram that helps to reduce coding.

Library Function In C: C  provides library functions for performing some operations. These functions are present in the c library and they  are predefined for example. Sqrt() is a mathematical library function  which is used for finding the square root of any number The function scanf and printf() are input and output library function,  similarly we have strcmp() and strlen() for string manipulations.To use a library function we need to include some header file using the preprocessor directive #include . for example : to use input and output function like printf() and scanf() we have to include stdio.h, for math library function we have to include math.h for string library string.h should be included .

User Defined Function In C User defined function are those function which are defined by the users. User can create their own functions for performing any specific task of program. To create and use these function we have to know these 3 things.

1. Function Declaration 2. Function Definition 3. Function Call

Function DefinitionThe function definition consists of the  whole description and code of a function. It tells that what the function is doing and what are the input output for that.   A function definition have two parts :

1. Function Header 2. Function Body

Function Declaration and Function PrototypesC always needs declaration before use. This is also true for functions. For functions the declaration needs to be before the first call of the function. A full declaration includes the return type and the number and type of the arguments. This is also called the function prototype.

Passing Parameters to a FunctionThere are two ways to pass parameters to a function:Pass(call) by Value: mechanism is used when you don't want to change the value of passed parameters. When parameters are passed by value then functions in C create copies of the passed in variables and do required processing on these copied variables.

← Pass(call) by Reference mechanism is used when you want a function to do the changes in passed parameters and reflect those changes back to the calling function. In this case only addresses of the variables are passed to a function so that function can work directly over the addresses.

Recursion: The process of calling a function itself again and again is called recursion. A function is called ‘recursive’ if a statement within the body of a function calls the same function. Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself.

Console I/O FunctionsConsole input/output functions are used to read input through the keyboard and to display output in monitor or VDU. The screen and keyboard together are called a console. Console I/O functions can be further classified into two categories—formatted and unformatted console I/O functions. The basic difference between them is that the formatted functions allow the input read from the keyboard or the output displayed on the VDU to be formatted as per our requirements.

Function Name

← Works

getch() ← Reads character through the keyboard(unformatted input function)getche() ← Reads character through the keyboard and echo it. (unformatted input function)getchar() ← Reads character through the keyboard(unformatted input function)putch() ← Display a single character on the VDU. (unformatted output function)putchar() ← Display a single character on the VDU. (unformatted output function)gets() ← Reads strings through the keyboard. (unformatted input function)puts() ← puts strings on the VDU. (unformatted output function)printf() ← Display output on the VDU.(formatted output function)

Web Address: https://sites.google.com/site/nitinpandey03/ Page 6

Page 7: Concept Notes

Short Notes “C”

scanf() ← Receive input through the keyboard(formatted input function)

←← Arrays

← Array by definition is a variable that hold multiple elements which has the same data type. Or an array is a collection of different types of data. An array is a multi element box, uses an indexing system. Array’s indexing always begins with 0 and ends with n-1. Where n is the size of array.

←Declaring the array:  We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name. data type array_name[size]; // for single dimensional array.

← data type array_name[row size][column size]; // for double dimensional array.

Array can be categorised into single dimensional or multi dimensional array.Example of Single Dimensional array:int a[10]; // declare an array which can store 10 integral values.Example of Double Dimensional array:int a[10][20]; // declare an array which has 10 rows and 20 columns.

StringsA group of characters can be stored in a character array. Character arrays are also called strings. A string is a group of characters, usually letters of the alphabet. String is always terminated by NULL ‘\0’ character.

Some library functions of strings: Library functions of strings are defined under string.h header file.

← Function Name ← Works← strcpy() ← copies one string into another← strcmp() ← compares two string and returns ascii value defference← strrev() ← Reverses a string← strlen() ← finds length of a strings← strcat() ← Appends on string at the end of another← strlwr() ← converts a string into lower case letters← strupr() ← converts a string into upper case letters

Preprocessor Directive or PreprocessorIt is a program that processes our source program before it is passed to the compiler. Preprocessor commands (often known as directives) form what can almost be considered a language within C language. It can take following form.

(a) Macro expansion : It replaces all the occurrences of defined word or character with its value. for example: #define UPPER 25 (b) File inclusion: This directive causes one file to be included in another. The preprocessor command for file inclusion looks like this: #include "filename"

Command Line ArgumentsC provides a fairly simple mechanism for retrieving command line parameters entered by the user. It passes an argv parameter to the main function in the program. The argc integer contains a count of the number of parameters.

StructuresA structure is collection of various data types. A structure is a group of one or more variables under a single name. or A structure contains a number of data types grouped together. These data types may or may not be of the same type.

Declaring a Structure: The general form or a syntax of a structure declaration statement is given below:struct <structure name> { structure element 1 ; structure element 2 ; ...... ......

Web Address: https://sites.google.com/site/nitinpandey03/ Page 7

Page 8: Concept Notes

Short Notes “C”

} ;Accessing Structure Elements: In arrays we can access individual elements of an array using a subscript. Structures use a different scheme. They use a dot (.) operator. Having declared the structure type and the structure variables, let us see how the elements of the structure can be accessed by: Structurename.structureelement

UnionUnion is a collection of different types of data. It means data may be a collection of different data types, ie its may be a combination of integers, characters and floats values. Declaration,and accessing union is same as structure.The general form or syntax for union is given below: Union union_name{

Type structure_element 1;Type structure_element 2;

------------------

Type structure_element n;};

Difference between structure and unionsa)All the members of the structure can be accessed at once, where as in an union only one member can be used at a time.b)Another important difference is in the size allocated to a structure and an union.

Storage Classes in CStorage classes tells: (a) Where the variable would be stored. (b) What will be the initial value of the variable, if initial value is not specifically assigned. (c) What is the scope of the variable; i.e. in which functions the value of the variable would be available. (d) What is the life of the variable; i.e. how long would the variable exist.

There are four storage classes in C given in following table:

Storage class Storage Default Value Scope LifeAutomatic Memory Garbage Local to the block in which variable

is defined.Till control remains within the block in which variable is defined.

Register CPU Garbage Local to the block in which variable is defined.

Till control remains within the block in which variable is defined.

Static Memory Zero Local to the block in which variable is defined.

Value of the variable persist between different function call.

External Memory Zero Global As long as program execution does not come to an end.

Memory Management in CMemory management in c is done using calloc( ), malloc( ), realloc( ) and free( ) functions. These functions can allocate, reallocate, deal locate and free memory during runtime. Allocation, deal location of memory during runtime is known as dynamic memory management. It means calloc( ), malloc( ), realloc( ) and free( ) are the functions which are used for dynamic memory management.Function Taskmalloc( ) Allocate request size of bytes & return a pointer to the first byte of the allocated space.

And contains garbage values.calloc( ) Allocate space for an array of elements, initialize them to zero and returns a pointer to

the first byte of allocated spacerealloc( ) Modify the size of previously allocated spacefree( ) Free the previously allocated space.

Web Address: https://sites.google.com/site/nitinpandey03/ Page 8

Page 9: Concept Notes

Short Notes “C”

File Input/ OutputA file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. Essentially there are two kinds of files that programmers deal with text files and binary files.ASCII Text file: A text file can be a stream of characters that a computer can process sequentially.Binary files: A binary is a collection of bytes. In C Programming Language a byte and a character are equivalent. Binary files can be either processed sequentially or randomly.File Operations: There are different operations that can be carried out on a file. These are:1 Creation of a new file 2 Opening an existing file 3 Reading from a file 4 Writing to a file 5 Moving to a specific location in a file (seeking) 6 Closing a file Some common functions of file handling:

← Function Name ← Works← fopen() ← for opening a file← fclose() ← for closing a file← fgetc() ← reads a character← fputc() ← puts a character← fgets() ← reads string

The enum data typeIt allows us to define a list of aliases which represent integer numbers. For example if you find yourself coding something like: #define MON 1 #define TUE 2 #define WED 3 You could use enum as below. enum week { Mon=1, Tue, Wed, Thu, Fri Sat, Sun} days;

CompilerA compiler is defined as a computer program that is used to convert high level instructions or language into a form that can be understood by the computer.

InterpreterHigh level instruction or language is converted into intermediate form by an interpreter.

Difference between compiler and interpreter• A complier converts the high level instruction into machine language while an interpreter converts the high level instruction into an intermediate form.• Before execution, entire program is executed by the compiler whereas after translating the first line, an interpreter then executes it and so on.• List of errors is created by the compiler after the compilation process while an interpreter stops translating after the first error.

Assembler An assembler is a program that takes basic computer instructions and converts them into a pattern of bits that the computer's processor can use to perform its basic operations.

Web Address: https://sites.google.com/site/nitinpandey03/ Page 9