Data Structures & C Programming
C Programming • What is C? • C is a computer programming language used to design computer software and applications. • Why do we use C? • We use the C programming language to design computer software and applications. • Who invented C? • C Programming Language was invented in the year 1972 by Dennis Ritchie (Dennis MacAlistair Ritchie). He was an American Computer Scientist worked at Bell Labs as a researcher along with Ken Thompson. He was born on 9th September 1941 and lived till 12th October 2011. He is said to be the Father of C.
Software used to create and execute a C Program • Following are the applications and software used to create and execute C programs. • Turbo C • Turbo C++ • GNU C • Code Blocks • Net Beans
Computer Language Computer languages are the languages through which the user can communicate with the computer by writing program instructions.
Creating and Running C Program • File -> New Type the program Save it as FileName.c (Use shortcut key F2 to save) • The compilation is the process of converting high-level language instructions into low-level language instructions. • The .exe file is submitted to the CPU, performs the task result generated in window screen • Alt + F5 to open the User Screen and check the result.
Execution Process of a C Program
Important Points • C program file (Source file) must save with .c extension. • The compiler converts complete program at a time from high-level language to low-level language. • Input to the compiler is .c file and output from the compiler is .exe file, but it also generates .obj file in this process. • The compiler converts the file only if there are no errors in the source code. • CPU places the result in User Screen window. Overall Process • Type the program in C editor and save with .c extension (Press F2 to save). • Press Alt + F9 to compile the program. • If there are errors, correct the errors and recompile the program. • If there are no errors, then press Ctrl + F9 to execute/run the program. • Press Alt + F5 to open User Screen and check the result.
C Programming Structure • C is a structured programming language. Every c program and its statements must be in a particular structure. Every c program has the following general structure...
#include <stdio.h> int main() { printf("Hello World!"); return 0; }
C Header Files
C Header Files
C Tokens • In a C program, a collection of all the keywords, identifiers, operators, special symbols, constants, strings, and data values are called tokens.
C Keywords • Keywords are the reserved words with predefined meaning which already known to the compiler. • 32 keywords • Properties of Keywords • All the keywords in C programming language are defined as lowercase letters so they must be used only in lowercase letters • Every keyword has a specific meaning, users can not change that meaning. • Keywords can not be used as user-defined names like variable, functions, arrays, pointers, etc... • Every keyword in C programming language represents something or specifies some kind of action to be performed by the compiler.
C Identifiers The identifier is a user-defined name of an entity to identify it uniquely during the program execution Example int marks; char studentName[30]; Here, marks and studentName are identifiers. • Rules for Creating Identifiers • A n i d e n t i f i e r c a n c o n t a i n l e t t e r s ( U P P E R C A S E a n d lowercase), numerics & underscore symbol only. • An identifier should not start with a numerical value. It can start with a letter or an underscore. • We should not use any special symbols in between the identifier even whitespace. However, the only underscore symbol is allowed. • Keywords should not be used as identifiers. • There is no limit for the length of an identifier. However, the compiler considers the first 31 characters only. • An identifier must be unique in its scope.
C data types
• void data type • The void data type means nothing or no value. Generally, the void is used to specify a function which does not return any value. We also use the void data type to specify empty parameters of a function. • Enumerated data type • An enumerated data type is a user-defined data type that consists of integer constants and each integer constant is given a name. The keyword "enum" is used to define the enumerated data type. • Derived data types • Derived data types are user-defined data types. The derived data types are also called as user-defined data types or secondary data types. In the c programming language, the derived data types are created using the following concepts... • Arrays • Structures • Unions • Enumeration
C Variables • Variable is a name given to a memory location where we can store different values of the same datatype during the program execution. • A variable name may contain letters, digits and underscore symbol. The following are the rules to specify a variable name... – Variable name should not start with a digit. – Keywords should not be used as variable names. – A variable name should not contain any special symbols except underscore(_). – A variable name can be of any length but compiler considers only the first 31 characters of the variable name.
Declaration of Variable
C Constants • A constant is a named memory location which holds only one value throughout the program execution. • The specific alphabetical or numerical value that never gets changed during the processing of the instructions is called as constant. • The constant can be alphabetical, numeric or special symbol. • The constants are given some names and are referred by the names. • Example: The most commonly used constant is PI. Once the value to this constant is assigned then it does not get changed. • The names to the constant help in accessing them easily. • Generally all the letters in the name of the constant are capital.
C Output Functions • C programming language provides built-in functions to perform output operation. The output operations are used to display data on user screen (output screen) or printer or any file. The c programming language provides the following built-in output functions... • printf() • putchar() • puts() • fprintf()
General rules for any C program • Every executable statement must end with a semicolon symbol (;). • Every C program must contain exactly one main method (Starting point of the program execution). • All the system-defined words (keywords) must be used in lowercase letters. • Keywords can not be used as user-defined names(identifiers). • For every open brace ({), there must be respective closing brace (}). • Every variable must be declared before it is used.
printf("message to be display!!!"); #include <stdio.h> //this is needed to run printf() function. int main() { printf("Hello World!"); // displays the contents inside “” return 0; }
printf("format string",variableName);
printf("String format string",variableName);
Formatted printf() function
C Input Functions • C programming language provides built-in functions to perform input operations. The input operations are used to read user values (input) from the keyboard. The c programming language provides the following built-in input functions. • scanf() • getchar() • getch() • gets() • fscanf()
scanf() function • The scanf() function is used to read multiple data values of different data types from the keyboard. The scanf() function is built-in function defined in a header file called "stdio.h". When we want to use scanf() function in our program, we need to include the respective header file (stdio.h) using #include statement. The scanf() function has the following syntax... • scanf("format strings",&variableNames);
getchar() function The getchar() function is used to read a character from the keyboard and return it to the program.This function is used to read a single character. To read multiple characters we need to write multiple times or use a looping statement.
getch() function • The getch() function is similar to getchar function. The getch() function is used to read a character from the keyboard and return it to the program. This function is used to read a single character. To read multiple characters we need to write multiple times or use a looping statement.
gets() function • The gets() function is used to read a line of string and stores it into a character array. The gets() function reads a line of string or sequence of characters till a newline symbol enters.
fscanf() function • The fscanf() function is used with the concept of files. The fscanf() function is used to read data values from a file. When you want to use fscanf() function the file must be opened in reading mode.
C Operators • An operator is a symbol used to perform arithmetic and logical operations in a program. That means an operator is a special symbol that tells the compiler to perform mathematical or logical operations. C programming language supports a rich set of operators that are classified as follows. • Arithmetic Operators • Relational Operators • Logical Operators • Increment & Decrement Operators • Assignment Operators • Bitwise Operators • Conditional Operator • Special Operators
Arithmetic Operators (+, -, *, /, %) • The arithmetic operators are the symbols that are used to perform basic mathematical operations like addition, subtraction, multiplication, division and percentage modulo. The following table provides information about arithmetic operators.
Relational Operators (<, >, <=, >=, ==, !=) • The relational operators are the symbols that are used to compare two values. That means the relational operators are used to check the relationship between two values. Every relational operator has two results TRUE or FALSE. In simple words, the relational operators are used to define conditions in a program. The following table provides information about relational operators.
Logical Operators (&&, ||, !) • The logical operators are the symbols that are used to combine multiple conditions into one condition. The following table provides information about logical operators.
Increment & Decrement Operators (++ & --) • The increment and decrement operators are called unary operators because both need only one operand. The increment operators adds one to the existing value of the operand and the decrement operator subtracts one from the existing value of the operand. The following table provides information about increment and decrement operators.
Assignment Operators (=, +=, -=, *=, /=, %=) • The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side variable (Lvalue). The assignment operator is used in different variants along with arithmetic operators. The following table describes all the assignment operators in the C programming language.
Bitwise Operators (&, |, ^, ~, >>, <<) • The bitwise operators are used to perform bit-level operations in the c programming language. When we use the bitwise operators, the operations are performed based on the binary values. The following table describes all the bitwise operators in the C programming language. Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Conditional Operator (?:) • The conditional operator is also called a ternary operator because it requires three operands. This operator is used for decision making. In this operator, first we verify a condition, then we perform one operation out of the two operations based on the condition result. If the condition is TRUE the first option is performed, if the condition is FALSE the second option is performed. The conditional operator is used with the following syntax. Condition ? TRUE Part : FALSE Part; Example • A = (10<15)?100:200; ⇒ A value is 100
Special Operators (sizeof, pointer, comma, dot, etc.) • The following are the special operators in c programming language. • sizeof operator • This operator is used to find the size of the memory (in bytes) allocated for a variable. This operator is used with the following syntax. • sizeof(variableName); Example • sizeof(A); ⇒ the result is 2 if A is an integer • Pointer operator (*) • This operator is used to define pointer variables in c programming language. • Comma operator (,) • This operator is used to separate variables while they are declaring, separate the expressions in function calls, etc. • Dot operator (.) • This operator is used to access members of structure or union.
C Expressions An expression is a collection of operators and operands that represents a specific value. ->An operator is a symbol that performs tasks like arithmetic operations, logical operations, and conditional operations, etc. ->Operands are the values on which the operators perform the task. Here operand can be a direct value or variable or address of memory location.
Expression Types in C • In the C programming language, expressions are divided into THREE types. They are as follows... • Infix Expression • Postfix Expression • Prefix Expression
Infix Expression • The expression in which the operator is used between operands is called infix expression. The infix expression has the following general structure. • Operand1 Operator Operand2
Postfix Expression • The expression in which the operator is used after operands is called postfix expression. The postfix expression has the following general structure. • Operand1 Operand2 Operator
Prefix Expression • The expression in which the operator is used before operands is called a prefix expression. The prefix expression has the following general structure. • Operator Operand1 Operand2
C Operator Precedence • Operator precedence is used to determine the order of operators evaluated in an expression. In c programming language every operator has precedence (priority). When there is more than one operator in an expression the operator with higher precedence is evaluated first and the operator with the least precedence is evaluated last.
Decision Making Statement • In the C programming language, the program execution flow is line by line from top to bottom. But this type of execution flow may not be suitable for all the program solutions.
if statement in c • In c, if statement is used to make decisions based on a condition. The if statement verifies the given condition and decides whether a block of statements are executed or not based on the condition result. In c, if statement is classified into four types as follows... • Simple if statement • if-else statement • Nested if statement • if-else-if statement (if-else ladder)
Simple if statement • Simple if statement is used to verify the given condition and executes the block of statements based on the condition result. The simple if statement evaluates specified condition. If it is TRUE, it executes the next statement or block of statements. If the condition is FALSE, it skips the execution of the next statement or block of statements. Simple if statement is used when we have only one option that is executed or skipped based on a condition.
Example Program | Test whether given number is divisible by 5.
if-else statement • The if-else statement is used to verify the given condition and executes only one out of the two blocks of statements based on the condition result. The if-else statement evaluates the specified condition. If it is TRUE, it executes a block of statements (True block). If the condition is FALSE, it executes another block of statements (False block). The if-else statement is used when we have two options and only one option has to be executed based on a condition result (TRUE or FALSE).
Example Program | Test whether given number is even or odd.
Nested if statement • Writing a if statement inside another if statement is called nested if statement. The nested if statement can be defined using any combination of simple if & if-else statements.
Example Program | Test whether given number is even or odd if it is below 100.
if-else-if statement (if-else ladder) • Writing a if statement inside else of an if statement is called if-else-if statement. The if-else-if statement can be defined using any combination of simple if & if-else statements.
Example Program | Find the largest of three numbers.
• When we use a conditional control statement like if statement, the condition might be an expression evaluated to a numerical value, a variable or a direct numerical value. • If the expression value or direct value is zero the condition becomes FALSE otherwise becomes TRUE.
'switch' statement in C • Consider a situation in which we have many options out of which we need to select only one option that is to be executed. Such kind of problems can be solved using nested if statement. But as the number of options increases, the complexity of the program also gets increased. This type of problem can be solved very easily using a switch statement. Using the switch statement, one can select only one option from more number of options very easily. In the switch statement, we provide a value that is to be compared with a value associated with each option. Whenever the given value matches the value associated with an option, the execution starts from that option. In the switch statement, every option is defined as a case.
• The switch statement contains one or more cases and each case has a value associated with it. • At first switch statement compares the first case value with the switchValue, if it gets matched the execution starts from the first case. • If it doesn't match the switch statement compares the second case value with the switchValue and if it is matched the execution starts from the second case. • This process continues until it finds a match. If no case value matches with the switchValue specified in the switch statement, then a special case called default is executed. • When a case value matches with the switchValue, the execution starts from that particular case. This execution flow continues with the next case statements also. • To avoid this, we use the "break" statement at the end of each case. That means the break statement is used to terminate the switch statement. However, it is optional.
Example Program | Display pressed digit in words.
When we use switch statement, we must follow the following... • Both switch and case are keywords so they must be used only in lower case letters. • The data type of case value and the value specified in the switch statement must be the same. • switch and case values must be either integer or character but not float or string. • A switch statement can contain any number of cases. • The keyword case and its value must be superated with a white space. • The case values need not be defined in sequence, they can be in any order. • The default case is optional and it can be defined anywhere inside the switch statement. • The switch value might be direct, a variable or an expression.
Looping statement in C The looping statements are used to execute a single statement or block of statements repeatedly until the given condition is FALSE. C language provides three looping statements... • while statement • do-while statement • for statement
while Statement The while statement is used to execute a single statement or block of statements repeatedly as long as the given condition is TRUE. The while statement is also known as Entry control looping statement.
When we use a while statement, we must follow the following... • while is a keyword so it must be used only in lower case letters. • If the condition contains a variable, it must be assigned a value before it is used. • The value of the variable used in condition must be modified according to the requirement inside the while block. • In a while statement, the condition may be a direct integer value, a variable or a condition. • A while statement can be an empty statement.
'do-while' statement in C • The do-while statement is used to execute a single statement or block of statements repeatedly as long as given the condition is TRUE. The do-while statement is also known as the Exit control looping statement.
When we use the do-while statement, we must follow the following... • Both do and while are keywords so they must be used only in lower case letters. • If the condition contains a variable, it must be assigned a value before it is used. • The value of the variable used in the condition must be modified according to the requirement inside the do block. • In a do-while statement, the condition may be a direct integer value, a variable or a condition. • A do-while statement can be an empty statement. • In do-while, the block of statements is executed at least once.
'for' statement in C • The for statement is used to execute a single statement or a block of statements repeatedly as long as the given condition is TRUE.
When we use for statement, we must follow the following... • for is a keyword so it must be used only in lower case letters. • Every for statement must be provided with initialization, condition, and modification (They can be empty but must b e s e p a r a t e d w i t h " ; " ) Ex: for ( ; ; ) or for ( ; condition ; modification ) or for ( ; condition ; ) • In for statement, the condition may be a direct integer value, a variable or a condition. • The for statement can be an empty statement.
break, continue and goto in C • In c, there are control statements that do not need any condition to control the program execution flow. These control statements are called as unconditional control statements. C programming language provides the following unconditional control statements... • break • continue • goto • The above three statements do not need any condition to control the program execution flow.
break statement • In C, the break statement is used to perform the following two things... • break statement is used to terminate the switch case statement • break statement is also used to terminate looping statements like while, do-while and for. • When a break statement is encountered inside the switch case statement, the execution control moves out of the switch statement directly.
• When the break statement is encountered inside the looping statement, the execution control moves out of the looping statements.
continue statement • The continue statement is used to move the program execution control to the beginning of the looping statement. When the continue statement is encountered in a looping statement, the execution control skips the rest of the statements in the looping block and directly jumps to the beginning of the loop. The continue statement can be used with looping statements like while, do-while and for. • When we use continue statement with while and do- while statements the execution control directly jumps to the condition. When we use continue statement with for statement the execution control directly jumps to the modification portion (increment/decrement/any modification) of the for loop.
goto statement The goto statement is used to jump from one line to another line in the program. Using goto statement we can jump from top to bottom or bottom to top. To jump from one line to another line, the goto statement requires a label. Label is a name given to the instruction or line in the program. When we use a goto statement in the program, the execution control directly jumps to the line with the specified label.
When we use break, continue and goto statements, we must follow the following... • The break is a keyword so it must be used only in lower case letters. • The break statement can not be used with if statement. • The break statement can be used only in switch case and looping statements. • The break statement can be used with if statement, only if that if statement is written inside the switch case or looping statements. • The continue is a keyword so it must be used only in lower case letters. • The continue statement is used only within looping statements. • The continue statement can be used with if statement, only if that if statement is written inside the looping statements. • The goto is a keyword so it must be used only in lower case letters. • The goto statement must require a label. • The goto statement can be used with any statement like if, switch, while, do- while, and for, etc.
Functions in C Function is a subpart of a program used to perform a specific task and is executed individually. Functions are used to divide a larger program into smaller subprograms such that the program becomes easy to understand and easy to implement.
Every function in C has the following... • Function Declaration (Function Prototype) • Function Definition • Function Call
Function Declaration The function declaration tells the compiler about function name, the data type of the return value and parameters. The function declaration is also called a function prototype. • Function declaration syntax - returnType functionName(parametersList); • In the above syntax, returnType specifies the data type of the value which is sent as a return value from the function definition. The functionName is a user- defined name used to identify the function uniquely in the program. The parametersList is the data values that are sent to the function definition.
Function Definition • The function definition provides the actual code of that function. The function definition is also known as the body of the function. The actual task of the function is implemented in the function definition. That means the actual instructions to be performed by a function are written in function definition. The actual instructions of a function are written inside the braces "{ }". The function definition is performed before the main function or after the main function. • Function definition syntax - returnType functionName(parametersList) { Actual code... }
Function Call • The function call tells the compiler when to execute the function definition. When a function call is executed, the execution control jumps to the function definition where the actual code gets executed and returns to the same functions call once the execution completes. The function call is performed inside the main function or any other function or inside the function itself. • Function call syntax - functionName(parameters);
ADVANTAGES OF FUNCTIONS • Using funcions we can implement modular programming. • Functions make the program more readable and understandable. • Using functions the program implementation becomes easy. • Once a function is created it can be used many times (code re-usability). • Using functions larger programs can be divided into smaller modules.
Types of Functions in C • In C Programming Language, based on providing the function definition, functions are divided into two types. Those are as follows... • System Defined Functions • User Defined Functions
System Defined Functions • The C Programming Language provides pre-defined functions to make programming easy. These pre-defined functions are known as system defined functions. The system defined function is defined as follows... • The function whose definition is defined by the system is called as system defined function. • The system defined functions are also called as Library Functions or Standard Functions or Pre-Defined Functions. The implementation of system defined functions is already defined by the system. • In C, all the system defined functions are defined inside the header files like stdio.h, conio.h, math.h, string.h etc., For example, the funtions printf() and scanf() are defined in the header file called stdio.h. • Whenever we use system defined functions in the program, we must include the respective header file using #include statement. For example, if we use a system defined function sqrt() in the program, we must include the header file called math.h because the function sqrt() is defined in math.h. • System defined functions are declared in header files • System defined functions are implemented in .dll files. (DLL stands for Dynamic Link Library). • To use system defined functions the respective header file must be included.
User Defined Functions • The function whose definition is defined by the user is called as user defined function. • Function without Parameters and without Return value • Function with Parameters and without Return value • Function without Parameters and with Return value • Function with Parameters and with Return value
Function without Parameters and without Return value • In this type of functions there is no data transfer between calling function and called function. Simply the execution control j u m p s f r o m c a l l i n g - function to called function a n d e xe c u t e s c a l l e d function, and finally comes back to the calling function.
Function with Parameters and without Return value • In this type of functions there is data transfer from calling-function to called function (parameters) but there is no data transfer from called function to calling-function (return value). The execution control jumps from calling- function to called function along with the parameters a n d exe c u t e s c a l l e d function, and finally comes b a c k t o t h e c a l l i n g function.
Function without Parameters and with Return value • In this type of functions there is no data transfer from calling-function to c a l l e d - f u n c t i o n (parameters) but there is data transfer from called function to calling- function (return value). The execution control jumps from calling- f u n c t i o n t o c a l l e d function and executes called function, and finally comes back to the calling function along with a return value.
Function with Parameters and with Return value • In this type of functions there is data transfer from calling-function to called- function (parameters) and also from called function to calling-function (return value). The execution control jumps from calling- function to called function along with parameters and executes called function, and finally comes back to the calling function along with a return value.
Points to be Remembered • The parameters specified in calling function are said to be Actual Parameters. • The parameters declared in called function are said to be Formal Parameters. • The value of actual parameters is always copied into formal parameters.
Parameter Passing in C • When the execution control is transferred from calling-function to called-function it may carry one or number of data values. These data values are called as parameters. • Parameters are the data values that are passed from calling function to called function. • In C, there are two types of parameters and they are as follows... • Actual Parameters • Formal Parameters • The actual parameters are the parameters that are speficified in calling function. The formal parameters are the parameters that are declared at called function. When a function gets executed, the copy of actual parameter values are copied into formal parameters. • In C Programming Language, there are two methods to pass parameters from calling function to called function and they are as follows... • Call by Value • Call by Reference
Call by Value • In call by value parameter passing method, the copy of actual parameter values are copied to formal parameters and these formal parameters are used in called function. The changes made on the formal parameters does not effect the values of actual parameters. That means, after the execution control comes back to the calling function, the actual parameter values remains same.
Call by Reference • In Call by Reference parameter passing method, the memory location address of the actual parameters is copied to formal parameters. This address is used to access the memory locations of the actual parameters in called function. In this method of parameter passing, t h e fo r m a l p a ra m ete rs m u st be pointer variables. • That means in call by reference parameter passing method, the address of the actual parameters is passed to the called function and is received by the formal parameters (pointers). Whenever we use these formal parameters in called function, they directly access the memory locations of actual parameters. So the changes made on the formal parameters effects the values of actual parameters.
Scope of Variable in C • Scope of a variable is the portion of the program where a defined variable can be accessed. • Before the function definition (Global Declaration) • Inside the function or block (Local Declaration) • In the function definition parameters (Formal Parameters)
Recursive Functions in C • In C programming language, function calls can be made from the main() function, other functions or from the same function itself. A function called by itself is called recursive function. • The recursive functions should be used very carefully because, when a function called by itself it enters into the infinite loop. And when a function enters into the infinite loop, the function execution never gets completed. We should define the condition to exit from the function call so that the recursive function gets terminated. • When a function is called by itself, the first call remains under execution till the last call gets invoked. Every time when a function call is invoked, the function returns the execution control to the previous function call.
Arrays in C • An array is a special type of variable used to store multiple values of same data type at a time. • An array is a collection of similar data items stored in continuous memory locations with single name.
Declaration of an Array • In C programming language, when we want to create an array we must know the datatype of values to be stored in that array and also the number of values to be stored in that array. We use the following general syntax to create an array... • datatype arrayName [ size ] ; • Syntax for creating an array with size and initial values • datatype arrayName [ size ] = {value1, value2, ...} ; • Syntax for creating an array without size and with initial values • datatype arrayName [ ] = {value1, value2, ...} ; • In the above syntax, the datatype specifies the type of values we store in that array and size specifies the maximum number of values that can be stored in that array.
• Example Code •int a [3] ; • Here, the compiler allocates 6 bytes of contiguous memory locations with a single name 'a' and tells the compiler to store three different integer values (each in 2 bytes of memory) into that 6 bytes of memory. • In the above memory allocation, all the three memory locations have a common name 'a'. So accessing individual memory location is not possible directly. Hence compiler not only allocates the memory but also assigns a numerical reference value to every individual memory location of an array. This reference number is called "Index" or "subscript" or "indices".
Accessing Individual Elements of an Array arrayName [ indexValue ] ;
Types of Arrays in C • Single Dimensional Array / One Dimensional Array • Multi Dimensional Array
Single Dimensional Array • single dimensional arrays are used to store list of values of same datatype. • In other words, single dimensional arrays are used to store a row of values. In single dimensional array, data is stored in linear form. • Single dimensional arrays are also called as one-dimensional arrays, Linear Arrays or simply 1-D Arrays. • Declaration of Single Dimensional Array • We use the following general syntax for declaring a single dimensional array... • datatype arrayName [ size ] ; • Example Code • int rollNumbers [60] ; • The above declaration of single dimensional array reserves 60 continuous memory locations of 2 bytes each with the name rollNumbers and tells the compiler to allow only integer values into those memory locations.
Initialization of Single Dimensional Array • We use the following general syntax for declaring and initializing a single dimensional array with size and initial values. • datatype arrayName [ size ] = {value1, value2, ...} ; • Example Code • int marks [6] = { 89, 90, 76, 78, 98, 86 } ; • The above declaration of single dimensional array reserves 6 contiguous memory locations of 2 bytes each with the name marks and initializes with value 89 in first memory location, 90 in second memory location, 76 in third memory location, 78 in fourth memory location, 98 in fifth memory location and 86 in sixth memory location. • We can also use the following general syntax to intialize a single dimensional array without specifying size and with initial values... • datatype arrayName [ ] = {value1, value2, ...} ; • The array must be initialized if it is created without specifying any size. In this case, the size of the array is decided based on the number of values initialized.
• Example Code int marks [] = { 89, 90, 76, 78, 98, 86 } ; char studentName [] = "btechsmartclass" ; • In the above example declaration, size of the array 'marks' is 6 and the size of the array 'studentName' is 16. This is because in case of character array, compiler stores one exttra character called 0 (NULL) at the end.
Accessing Elements of Single Dimensional Array • In c programming language, to access the elements of single dimensional array we use array name followed by index value of the element that to be accessed. Here the index value must be enclosed in square braces. Index value of an element in an array is the reference number given to each element at the time of memory allocation. The index value of single dimensional array starts with zero (0) for first element and incremented by one for each element. The index value in an array is also called as subscript or indices. We use the following general syntax to access individual elements of single dimensional array... • arrayName [ indexValue ] • Example Code • marks [2] = 99 ; • In the above statement, the third element of 'marks' array is assinged with value '99'.
Multi Dimensional Array • An array of arrays is called as multi dimensional array. In simple words, an array created with more than one dimension (size) is called as multi dimensional array. Multi dimensional array can be of two dimensional array or three dimensional array or four dimensional array or more... Most popular and commonly used multi dimensional array is two dimensional array. The 2-D arrays are used to store data in the form of table. We also use 2-D arrays to create mathematical matrices. • Declaration of Two Dimensional Array • We use the following general syntax for declaring a two dimensional array... – datatype arrayName [ rowSize ] [ columnSize ] ; • Example Code • int matrix_A [2][3] ; • The above declaration of two dimensional array reserves 6 continuous memory locations of 2 bytes each in the form of 2 rows and 3 columns.
Initialization of Two Dimensional Array • We use the following general syntax for declaring and initializing a two dimensional array with specific number of rows and coloumns with initial values. • datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ; • Example Code • int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ; • The above declaration of two-dimensional array reserves 6 contiguous memory locations of 2 bytes each in the form of 2 rows and 3 columns. And the first row is initialized with values 1, 2 & 3 and second row is initialized with values 4, 5 & 6.
Accessing Individual Elements of Two Dimensional Array • In a c programming language, to access elements of a two- dimensional array we use array name followed by row index value and column index value of the element that to be accessed. Here the row and column index values must be enclosed in separate square braces. In case of the two-dimensional array the compiler assigns separate index values for rows and columns. We use the following general syntax to access the individual elements of a two-dimensional array... • arrayName [ rowIndex ] [ columnIndex ] • Example Code • matrix_A [0][1] = 10 ; • In the above statement, the element with row index 0 and column index 1 of matrix_A array is assinged with value 10.
Applications of Arrays in C ● Arrays are used to Store List of values In c programming language, single dimensional arrays are used to store list of values of same datatype. In other words, single dimensional arrays are used to store a row of values. In single dimensional array data is stored in linear form. ● Arrays are used to Perform Matrix Operations We use two dimensional arrays to create matrix. We can perform various operations on matrices using two dimensional arrays. ● Arrays are used to implement Search Algorithms We use single dimensional arrays to implement search algorihtms like ... Linear Search,Binary Search ● Arrays are used to implement Sorting Algorithms We use single dimensional arrays to implement sorting algorihtms like ... Insertion Sort,Bubble Sort,Selection Sort,Quick Sort,Merge Sort, etc., ● Arrays are used to implement Datastructures We use single dimensional arrays to implement datastructures like... Stack Using Arrays,Queue Using Arrays ● Arrays are also used to implement CPU Scheduling Algorithms

EC2311-Data Structures and C Programming

  • 1.
    Data Structures &C Programming
  • 2.
    C Programming • Whatis C? • C is a computer programming language used to design computer software and applications. • Why do we use C? • We use the C programming language to design computer software and applications. • Who invented C? • C Programming Language was invented in the year 1972 by Dennis Ritchie (Dennis MacAlistair Ritchie). He was an American Computer Scientist worked at Bell Labs as a researcher along with Ken Thompson. He was born on 9th September 1941 and lived till 12th October 2011. He is said to be the Father of C.
  • 3.
    Software used tocreate and execute a C Program • Following are the applications and software used to create and execute C programs. • Turbo C • Turbo C++ • GNU C • Code Blocks • Net Beans
  • 4.
    Computer Language Computer languagesare the languages through which the user can communicate with the computer by writing program instructions.
  • 6.
    Creating and RunningC Program • File -> New Type the program Save it as FileName.c (Use shortcut key F2 to save) • The compilation is the process of converting high-level language instructions into low-level language instructions. • The .exe file is submitted to the CPU, performs the task result generated in window screen • Alt + F5 to open the User Screen and check the result.
  • 7.
  • 8.
    Important Points • Cprogram file (Source file) must save with .c extension. • The compiler converts complete program at a time from high-level language to low-level language. • Input to the compiler is .c file and output from the compiler is .exe file, but it also generates .obj file in this process. • The compiler converts the file only if there are no errors in the source code. • CPU places the result in User Screen window. Overall Process • Type the program in C editor and save with .c extension (Press F2 to save). • Press Alt + F9 to compile the program. • If there are errors, correct the errors and recompile the program. • If there are no errors, then press Ctrl + F9 to execute/run the program. • Press Alt + F5 to open User Screen and check the result.
  • 9.
    C Programming Structure •C is a structured programming language. Every c program and its statements must be in a particular structure. Every c program has the following general structure...
  • 10.
  • 11.
  • 12.
  • 13.
    C Tokens • Ina C program, a collection of all the keywords, identifiers, operators, special symbols, constants, strings, and data values are called tokens.
  • 14.
    C Keywords • Keywordsare the reserved words with predefined meaning which already known to the compiler. • 32 keywords • Properties of Keywords • All the keywords in C programming language are defined as lowercase letters so they must be used only in lowercase letters • Every keyword has a specific meaning, users can not change that meaning. • Keywords can not be used as user-defined names like variable, functions, arrays, pointers, etc... • Every keyword in C programming language represents something or specifies some kind of action to be performed by the compiler.
  • 15.
    C Identifiers The identifieris a user-defined name of an entity to identify it uniquely during the program execution Example int marks; char studentName[30]; Here, marks and studentName are identifiers. • Rules for Creating Identifiers • A n i d e n t i f i e r c a n c o n t a i n l e t t e r s ( U P P E R C A S E a n d lowercase), numerics & underscore symbol only. • An identifier should not start with a numerical value. It can start with a letter or an underscore. • We should not use any special symbols in between the identifier even whitespace. However, the only underscore symbol is allowed. • Keywords should not be used as identifiers. • There is no limit for the length of an identifier. However, the compiler considers the first 31 characters only. • An identifier must be unique in its scope.
  • 16.
  • 18.
    • void datatype • The void data type means nothing or no value. Generally, the void is used to specify a function which does not return any value. We also use the void data type to specify empty parameters of a function. • Enumerated data type • An enumerated data type is a user-defined data type that consists of integer constants and each integer constant is given a name. The keyword "enum" is used to define the enumerated data type. • Derived data types • Derived data types are user-defined data types. The derived data types are also called as user-defined data types or secondary data types. In the c programming language, the derived data types are created using the following concepts... • Arrays • Structures • Unions • Enumeration
  • 19.
    C Variables • Variableis a name given to a memory location where we can store different values of the same datatype during the program execution. • A variable name may contain letters, digits and underscore symbol. The following are the rules to specify a variable name... – Variable name should not start with a digit. – Keywords should not be used as variable names. – A variable name should not contain any special symbols except underscore(_). – A variable name can be of any length but compiler considers only the first 31 characters of the variable name.
  • 20.
  • 21.
    C Constants • Aconstant is a named memory location which holds only one value throughout the program execution. • The specific alphabetical or numerical value that never gets changed during the processing of the instructions is called as constant. • The constant can be alphabetical, numeric or special symbol. • The constants are given some names and are referred by the names. • Example: The most commonly used constant is PI. Once the value to this constant is assigned then it does not get changed. • The names to the constant help in accessing them easily. • Generally all the letters in the name of the constant are capital.
  • 22.
    C Output Functions •C programming language provides built-in functions to perform output operation. The output operations are used to display data on user screen (output screen) or printer or any file. The c programming language provides the following built-in output functions... • printf() • putchar() • puts() • fprintf()
  • 23.
    General rules forany C program • Every executable statement must end with a semicolon symbol (;). • Every C program must contain exactly one main method (Starting point of the program execution). • All the system-defined words (keywords) must be used in lowercase letters. • Keywords can not be used as user-defined names(identifiers). • For every open brace ({), there must be respective closing brace (}). • Every variable must be declared before it is used.
  • 24.
    printf("message to bedisplay!!!"); #include <stdio.h> //this is needed to run printf() function. int main() { printf("Hello World!"); // displays the contents inside “” return 0; }
  • 25.
  • 26.
  • 27.
  • 31.
    C Input Functions •C programming language provides built-in functions to perform input operations. The input operations are used to read user values (input) from the keyboard. The c programming language provides the following built-in input functions. • scanf() • getchar() • getch() • gets() • fscanf()
  • 32.
    scanf() function • Thescanf() function is used to read multiple data values of different data types from the keyboard. The scanf() function is built-in function defined in a header file called "stdio.h". When we want to use scanf() function in our program, we need to include the respective header file (stdio.h) using #include statement. The scanf() function has the following syntax... • scanf("format strings",&variableNames);
  • 35.
    getchar() function The getchar()function is used to read a character from the keyboard and return it to the program.This function is used to read a single character. To read multiple characters we need to write multiple times or use a looping statement.
  • 36.
    getch() function • Thegetch() function is similar to getchar function. The getch() function is used to read a character from the keyboard and return it to the program. This function is used to read a single character. To read multiple characters we need to write multiple times or use a looping statement.
  • 37.
    gets() function • Thegets() function is used to read a line of string and stores it into a character array. The gets() function reads a line of string or sequence of characters till a newline symbol enters.
  • 38.
    fscanf() function • Thefscanf() function is used with the concept of files. The fscanf() function is used to read data values from a file. When you want to use fscanf() function the file must be opened in reading mode.
  • 39.
    C Operators • Anoperator is a symbol used to perform arithmetic and logical operations in a program. That means an operator is a special symbol that tells the compiler to perform mathematical or logical operations. C programming language supports a rich set of operators that are classified as follows. • Arithmetic Operators • Relational Operators • Logical Operators • Increment & Decrement Operators • Assignment Operators • Bitwise Operators • Conditional Operator • Special Operators
  • 40.
    Arithmetic Operators (+,-, *, /, %) • The arithmetic operators are the symbols that are used to perform basic mathematical operations like addition, subtraction, multiplication, division and percentage modulo. The following table provides information about arithmetic operators.
  • 41.
    Relational Operators (<,>, <=, >=, ==, !=) • The relational operators are the symbols that are used to compare two values. That means the relational operators are used to check the relationship between two values. Every relational operator has two results TRUE or FALSE. In simple words, the relational operators are used to define conditions in a program. The following table provides information about relational operators.
  • 42.
    Logical Operators (&&,||, !) • The logical operators are the symbols that are used to combine multiple conditions into one condition. The following table provides information about logical operators.
  • 43.
    Increment & Decrement Operators(++ & --) • The increment and decrement operators are called unary operators because both need only one operand. The increment operators adds one to the existing value of the operand and the decrement operator subtracts one from the existing value of the operand. The following table provides information about increment and decrement operators.
  • 44.
    Assignment Operators (=,+=, -=, *=, /=, %=) • The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side variable (Lvalue). The assignment operator is used in different variants along with arithmetic operators. The following table describes all the assignment operators in the C programming language.
  • 45.
    Bitwise Operators (&,|, ^, ~, >>, <<) • The bitwise operators are used to perform bit-level operations in the c programming language. When we use the bitwise operators, the operations are performed based on the binary values. The following table describes all the bitwise operators in the C programming language. Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
  • 46.
    Conditional Operator (?:) •The conditional operator is also called a ternary operator because it requires three operands. This operator is used for decision making. In this operator, first we verify a condition, then we perform one operation out of the two operations based on the condition result. If the condition is TRUE the first option is performed, if the condition is FALSE the second option is performed. The conditional operator is used with the following syntax. Condition ? TRUE Part : FALSE Part; Example • A = (10<15)?100:200; ⇒ A value is 100
  • 47.
    Special Operators (sizeof,pointer, comma, dot, etc.) • The following are the special operators in c programming language. • sizeof operator • This operator is used to find the size of the memory (in bytes) allocated for a variable. This operator is used with the following syntax. • sizeof(variableName); Example • sizeof(A); ⇒ the result is 2 if A is an integer • Pointer operator (*) • This operator is used to define pointer variables in c programming language. • Comma operator (,) • This operator is used to separate variables while they are declaring, separate the expressions in function calls, etc. • Dot operator (.) • This operator is used to access members of structure or union.
  • 48.
    C Expressions An expressionis a collection of operators and operands that represents a specific value. ->An operator is a symbol that performs tasks like arithmetic operations, logical operations, and conditional operations, etc. ->Operands are the values on which the operators perform the task. Here operand can be a direct value or variable or address of memory location.
  • 49.
    Expression Types inC • In the C programming language, expressions are divided into THREE types. They are as follows... • Infix Expression • Postfix Expression • Prefix Expression
  • 50.
    Infix Expression • Theexpression in which the operator is used between operands is called infix expression. The infix expression has the following general structure. • Operand1 Operator Operand2
  • 51.
    Postfix Expression • Theexpression in which the operator is used after operands is called postfix expression. The postfix expression has the following general structure. • Operand1 Operand2 Operator
  • 52.
    Prefix Expression • Theexpression in which the operator is used before operands is called a prefix expression. The prefix expression has the following general structure. • Operator Operand1 Operand2
  • 53.
    C Operator Precedence •Operator precedence is used to determine the order of operators evaluated in an expression. In c programming language every operator has precedence (priority). When there is more than one operator in an expression the operator with higher precedence is evaluated first and the operator with the least precedence is evaluated last.
  • 55.
    Decision Making Statement •In the C programming language, the program execution flow is line by line from top to bottom. But this type of execution flow may not be suitable for all the program solutions.
  • 56.
    if statement inc • In c, if statement is used to make decisions based on a condition. The if statement verifies the given condition and decides whether a block of statements are executed or not based on the condition result. In c, if statement is classified into four types as follows... • Simple if statement • if-else statement • Nested if statement • if-else-if statement (if-else ladder)
  • 57.
    Simple if statement •Simple if statement is used to verify the given condition and executes the block of statements based on the condition result. The simple if statement evaluates specified condition. If it is TRUE, it executes the next statement or block of statements. If the condition is FALSE, it skips the execution of the next statement or block of statements. Simple if statement is used when we have only one option that is executed or skipped based on a condition.
  • 58.
    Example Program |Test whether given number is divisible by 5.
  • 59.
    if-else statement • Theif-else statement is used to verify the given condition and executes only one out of the two blocks of statements based on the condition result. The if-else statement evaluates the specified condition. If it is TRUE, it executes a block of statements (True block). If the condition is FALSE, it executes another block of statements (False block). The if-else statement is used when we have two options and only one option has to be executed based on a condition result (TRUE or FALSE).
  • 60.
    Example Program |Test whether given number is even or odd.
  • 61.
    Nested if statement •Writing a if statement inside another if statement is called nested if statement. The nested if statement can be defined using any combination of simple if & if-else statements.
  • 62.
    Example Program |Test whether given number is even or odd if it is below 100.
  • 63.
    if-else-if statement (if-elseladder) • Writing a if statement inside else of an if statement is called if-else-if statement. The if-else-if statement can be defined using any combination of simple if & if-else statements.
  • 64.
    Example Program |Find the largest of three numbers.
  • 65.
    • When weuse a conditional control statement like if statement, the condition might be an expression evaluated to a numerical value, a variable or a direct numerical value. • If the expression value or direct value is zero the condition becomes FALSE otherwise becomes TRUE.
  • 66.
    'switch' statement inC • Consider a situation in which we have many options out of which we need to select only one option that is to be executed. Such kind of problems can be solved using nested if statement. But as the number of options increases, the complexity of the program also gets increased. This type of problem can be solved very easily using a switch statement. Using the switch statement, one can select only one option from more number of options very easily. In the switch statement, we provide a value that is to be compared with a value associated with each option. Whenever the given value matches the value associated with an option, the execution starts from that option. In the switch statement, every option is defined as a case.
  • 68.
    • The switchstatement contains one or more cases and each case has a value associated with it. • At first switch statement compares the first case value with the switchValue, if it gets matched the execution starts from the first case. • If it doesn't match the switch statement compares the second case value with the switchValue and if it is matched the execution starts from the second case. • This process continues until it finds a match. If no case value matches with the switchValue specified in the switch statement, then a special case called default is executed. • When a case value matches with the switchValue, the execution starts from that particular case. This execution flow continues with the next case statements also. • To avoid this, we use the "break" statement at the end of each case. That means the break statement is used to terminate the switch statement. However, it is optional.
  • 69.
    Example Program |Display pressed digit in words.
  • 70.
    When we useswitch statement, we must follow the following... • Both switch and case are keywords so they must be used only in lower case letters. • The data type of case value and the value specified in the switch statement must be the same. • switch and case values must be either integer or character but not float or string. • A switch statement can contain any number of cases. • The keyword case and its value must be superated with a white space. • The case values need not be defined in sequence, they can be in any order. • The default case is optional and it can be defined anywhere inside the switch statement. • The switch value might be direct, a variable or an expression.
  • 71.
    Looping statement inC The looping statements are used to execute a single statement or block of statements repeatedly until the given condition is FALSE. C language provides three looping statements... • while statement • do-while statement • for statement
  • 72.
    while Statement The whilestatement is used to execute a single statement or block of statements repeatedly as long as the given condition is TRUE. The while statement is also known as Entry control looping statement.
  • 74.
    When we usea while statement, we must follow the following... • while is a keyword so it must be used only in lower case letters. • If the condition contains a variable, it must be assigned a value before it is used. • The value of the variable used in condition must be modified according to the requirement inside the while block. • In a while statement, the condition may be a direct integer value, a variable or a condition. • A while statement can be an empty statement.
  • 75.
    'do-while' statement inC • The do-while statement is used to execute a single statement or block of statements repeatedly as long as given the condition is TRUE. The do-while statement is also known as the Exit control looping statement.
  • 77.
    When we usethe do-while statement, we must follow the following... • Both do and while are keywords so they must be used only in lower case letters. • If the condition contains a variable, it must be assigned a value before it is used. • The value of the variable used in the condition must be modified according to the requirement inside the do block. • In a do-while statement, the condition may be a direct integer value, a variable or a condition. • A do-while statement can be an empty statement. • In do-while, the block of statements is executed at least once.
  • 78.
    'for' statement inC • The for statement is used to execute a single statement or a block of statements repeatedly as long as the given condition is TRUE.
  • 80.
    When we usefor statement, we must follow the following... • for is a keyword so it must be used only in lower case letters. • Every for statement must be provided with initialization, condition, and modification (They can be empty but must b e s e p a r a t e d w i t h " ; " ) Ex: for ( ; ; ) or for ( ; condition ; modification ) or for ( ; condition ; ) • In for statement, the condition may be a direct integer value, a variable or a condition. • The for statement can be an empty statement.
  • 81.
    break, continue andgoto in C • In c, there are control statements that do not need any condition to control the program execution flow. These control statements are called as unconditional control statements. C programming language provides the following unconditional control statements... • break • continue • goto • The above three statements do not need any condition to control the program execution flow.
  • 82.
    break statement • InC, the break statement is used to perform the following two things... • break statement is used to terminate the switch case statement • break statement is also used to terminate looping statements like while, do-while and for. • When a break statement is encountered inside the switch case statement, the execution control moves out of the switch statement directly.
  • 84.
    • When thebreak statement is encountered inside the looping statement, the execution control moves out of the looping statements.
  • 86.
    continue statement • Thecontinue statement is used to move the program execution control to the beginning of the looping statement. When the continue statement is encountered in a looping statement, the execution control skips the rest of the statements in the looping block and directly jumps to the beginning of the loop. The continue statement can be used with looping statements like while, do-while and for. • When we use continue statement with while and do- while statements the execution control directly jumps to the condition. When we use continue statement with for statement the execution control directly jumps to the modification portion (increment/decrement/any modification) of the for loop.
  • 89.
    goto statement The gotostatement is used to jump from one line to another line in the program. Using goto statement we can jump from top to bottom or bottom to top. To jump from one line to another line, the goto statement requires a label. Label is a name given to the instruction or line in the program. When we use a goto statement in the program, the execution control directly jumps to the line with the specified label.
  • 90.
    When we usebreak, continue and goto statements, we must follow the following... • The break is a keyword so it must be used only in lower case letters. • The break statement can not be used with if statement. • The break statement can be used only in switch case and looping statements. • The break statement can be used with if statement, only if that if statement is written inside the switch case or looping statements. • The continue is a keyword so it must be used only in lower case letters. • The continue statement is used only within looping statements. • The continue statement can be used with if statement, only if that if statement is written inside the looping statements. • The goto is a keyword so it must be used only in lower case letters. • The goto statement must require a label. • The goto statement can be used with any statement like if, switch, while, do- while, and for, etc.
  • 91.
    Functions in C Functionis a subpart of a program used to perform a specific task and is executed individually. Functions are used to divide a larger program into smaller subprograms such that the program becomes easy to understand and easy to implement.
  • 92.
    Every function inC has the following... • Function Declaration (Function Prototype) • Function Definition • Function Call
  • 93.
    Function Declaration The functiondeclaration tells the compiler about function name, the data type of the return value and parameters. The function declaration is also called a function prototype. • Function declaration syntax - returnType functionName(parametersList); • In the above syntax, returnType specifies the data type of the value which is sent as a return value from the function definition. The functionName is a user- defined name used to identify the function uniquely in the program. The parametersList is the data values that are sent to the function definition.
  • 94.
    Function Definition • Thefunction definition provides the actual code of that function. The function definition is also known as the body of the function. The actual task of the function is implemented in the function definition. That means the actual instructions to be performed by a function are written in function definition. The actual instructions of a function are written inside the braces "{ }". The function definition is performed before the main function or after the main function. • Function definition syntax - returnType functionName(parametersList) { Actual code... }
  • 95.
    Function Call • Thefunction call tells the compiler when to execute the function definition. When a function call is executed, the execution control jumps to the function definition where the actual code gets executed and returns to the same functions call once the execution completes. The function call is performed inside the main function or any other function or inside the function itself. • Function call syntax - functionName(parameters);
  • 96.
    ADVANTAGES OF FUNCTIONS •Using funcions we can implement modular programming. • Functions make the program more readable and understandable. • Using functions the program implementation becomes easy. • Once a function is created it can be used many times (code re-usability). • Using functions larger programs can be divided into smaller modules.
  • 97.
    Types of Functionsin C • In C Programming Language, based on providing the function definition, functions are divided into two types. Those are as follows... • System Defined Functions • User Defined Functions
  • 98.
    System Defined Functions •The C Programming Language provides pre-defined functions to make programming easy. These pre-defined functions are known as system defined functions. The system defined function is defined as follows... • The function whose definition is defined by the system is called as system defined function. • The system defined functions are also called as Library Functions or Standard Functions or Pre-Defined Functions. The implementation of system defined functions is already defined by the system. • In C, all the system defined functions are defined inside the header files like stdio.h, conio.h, math.h, string.h etc., For example, the funtions printf() and scanf() are defined in the header file called stdio.h. • Whenever we use system defined functions in the program, we must include the respective header file using #include statement. For example, if we use a system defined function sqrt() in the program, we must include the header file called math.h because the function sqrt() is defined in math.h. • System defined functions are declared in header files • System defined functions are implemented in .dll files. (DLL stands for Dynamic Link Library). • To use system defined functions the respective header file must be included.
  • 99.
    User Defined Functions •The function whose definition is defined by the user is called as user defined function. • Function without Parameters and without Return value • Function with Parameters and without Return value • Function without Parameters and with Return value • Function with Parameters and with Return value
  • 101.
    Function without Parametersand without Return value • In this type of functions there is no data transfer between calling function and called function. Simply the execution control j u m p s f r o m c a l l i n g - function to called function a n d e xe c u t e s c a l l e d function, and finally comes back to the calling function.
  • 102.
    Function with Parametersand without Return value • In this type of functions there is data transfer from calling-function to called function (parameters) but there is no data transfer from called function to calling-function (return value). The execution control jumps from calling- function to called function along with the parameters a n d exe c u t e s c a l l e d function, and finally comes b a c k t o t h e c a l l i n g function.
  • 103.
    Function without Parametersand with Return value • In this type of functions there is no data transfer from calling-function to c a l l e d - f u n c t i o n (parameters) but there is data transfer from called function to calling- function (return value). The execution control jumps from calling- f u n c t i o n t o c a l l e d function and executes called function, and finally comes back to the calling function along with a return value.
  • 104.
    Function with Parametersand with Return value • In this type of functions there is data transfer from calling-function to called- function (parameters) and also from called function to calling-function (return value). The execution control jumps from calling- function to called function along with parameters and executes called function, and finally comes back to the calling function along with a return value.
  • 105.
    Points to beRemembered • The parameters specified in calling function are said to be Actual Parameters. • The parameters declared in called function are said to be Formal Parameters. • The value of actual parameters is always copied into formal parameters.
  • 106.
    Parameter Passing inC • When the execution control is transferred from calling-function to called-function it may carry one or number of data values. These data values are called as parameters. • Parameters are the data values that are passed from calling function to called function. • In C, there are two types of parameters and they are as follows... • Actual Parameters • Formal Parameters • The actual parameters are the parameters that are speficified in calling function. The formal parameters are the parameters that are declared at called function. When a function gets executed, the copy of actual parameter values are copied into formal parameters. • In C Programming Language, there are two methods to pass parameters from calling function to called function and they are as follows... • Call by Value • Call by Reference
  • 107.
    Call by Value •In call by value parameter passing method, the copy of actual parameter values are copied to formal parameters and these formal parameters are used in called function. The changes made on the formal parameters does not effect the values of actual parameters. That means, after the execution control comes back to the calling function, the actual parameter values remains same.
  • 108.
    Call by Reference •In Call by Reference parameter passing method, the memory location address of the actual parameters is copied to formal parameters. This address is used to access the memory locations of the actual parameters in called function. In this method of parameter passing, t h e fo r m a l p a ra m ete rs m u st be pointer variables. • That means in call by reference parameter passing method, the address of the actual parameters is passed to the called function and is received by the formal parameters (pointers). Whenever we use these formal parameters in called function, they directly access the memory locations of actual parameters. So the changes made on the formal parameters effects the values of actual parameters.
  • 109.
    Scope of Variablein C • Scope of a variable is the portion of the program where a defined variable can be accessed. • Before the function definition (Global Declaration) • Inside the function or block (Local Declaration) • In the function definition parameters (Formal Parameters)
  • 110.
    Recursive Functions inC • In C programming language, function calls can be made from the main() function, other functions or from the same function itself. A function called by itself is called recursive function. • The recursive functions should be used very carefully because, when a function called by itself it enters into the infinite loop. And when a function enters into the infinite loop, the function execution never gets completed. We should define the condition to exit from the function call so that the recursive function gets terminated. • When a function is called by itself, the first call remains under execution till the last call gets invoked. Every time when a function call is invoked, the function returns the execution control to the previous function call.
  • 113.
    Arrays in C •An array is a special type of variable used to store multiple values of same data type at a time. • An array is a collection of similar data items stored in continuous memory locations with single name.
  • 114.
    Declaration of anArray • In C programming language, when we want to create an array we must know the datatype of values to be stored in that array and also the number of values to be stored in that array. We use the following general syntax to create an array... • datatype arrayName [ size ] ; • Syntax for creating an array with size and initial values • datatype arrayName [ size ] = {value1, value2, ...} ; • Syntax for creating an array without size and with initial values • datatype arrayName [ ] = {value1, value2, ...} ; • In the above syntax, the datatype specifies the type of values we store in that array and size specifies the maximum number of values that can be stored in that array.
  • 115.
    • Example Code •inta [3] ; • Here, the compiler allocates 6 bytes of contiguous memory locations with a single name 'a' and tells the compiler to store three different integer values (each in 2 bytes of memory) into that 6 bytes of memory. • In the above memory allocation, all the three memory locations have a common name 'a'. So accessing individual memory location is not possible directly. Hence compiler not only allocates the memory but also assigns a numerical reference value to every individual memory location of an array. This reference number is called "Index" or "subscript" or "indices".
  • 116.
    Accessing Individual Elementsof an Array arrayName [ indexValue ] ;
  • 118.
    Types of Arraysin C • Single Dimensional Array / One Dimensional Array • Multi Dimensional Array
  • 119.
    Single Dimensional Array •single dimensional arrays are used to store list of values of same datatype. • In other words, single dimensional arrays are used to store a row of values. In single dimensional array, data is stored in linear form. • Single dimensional arrays are also called as one-dimensional arrays, Linear Arrays or simply 1-D Arrays. • Declaration of Single Dimensional Array • We use the following general syntax for declaring a single dimensional array... • datatype arrayName [ size ] ; • Example Code • int rollNumbers [60] ; • The above declaration of single dimensional array reserves 60 continuous memory locations of 2 bytes each with the name rollNumbers and tells the compiler to allow only integer values into those memory locations.
  • 120.
    Initialization of SingleDimensional Array • We use the following general syntax for declaring and initializing a single dimensional array with size and initial values. • datatype arrayName [ size ] = {value1, value2, ...} ; • Example Code • int marks [6] = { 89, 90, 76, 78, 98, 86 } ; • The above declaration of single dimensional array reserves 6 contiguous memory locations of 2 bytes each with the name marks and initializes with value 89 in first memory location, 90 in second memory location, 76 in third memory location, 78 in fourth memory location, 98 in fifth memory location and 86 in sixth memory location. • We can also use the following general syntax to intialize a single dimensional array without specifying size and with initial values... • datatype arrayName [ ] = {value1, value2, ...} ; • The array must be initialized if it is created without specifying any size. In this case, the size of the array is decided based on the number of values initialized.
  • 121.
    • Example Code intmarks [] = { 89, 90, 76, 78, 98, 86 } ; char studentName [] = "btechsmartclass" ; • In the above example declaration, size of the array 'marks' is 6 and the size of the array 'studentName' is 16. This is because in case of character array, compiler stores one exttra character called 0 (NULL) at the end.
  • 122.
    Accessing Elements ofSingle Dimensional Array • In c programming language, to access the elements of single dimensional array we use array name followed by index value of the element that to be accessed. Here the index value must be enclosed in square braces. Index value of an element in an array is the reference number given to each element at the time of memory allocation. The index value of single dimensional array starts with zero (0) for first element and incremented by one for each element. The index value in an array is also called as subscript or indices. We use the following general syntax to access individual elements of single dimensional array... • arrayName [ indexValue ] • Example Code • marks [2] = 99 ; • In the above statement, the third element of 'marks' array is assinged with value '99'.
  • 123.
    Multi Dimensional Array •An array of arrays is called as multi dimensional array. In simple words, an array created with more than one dimension (size) is called as multi dimensional array. Multi dimensional array can be of two dimensional array or three dimensional array or four dimensional array or more... Most popular and commonly used multi dimensional array is two dimensional array. The 2-D arrays are used to store data in the form of table. We also use 2-D arrays to create mathematical matrices. • Declaration of Two Dimensional Array • We use the following general syntax for declaring a two dimensional array... – datatype arrayName [ rowSize ] [ columnSize ] ; • Example Code • int matrix_A [2][3] ; • The above declaration of two dimensional array reserves 6 continuous memory locations of 2 bytes each in the form of 2 rows and 3 columns.
  • 124.
    Initialization of TwoDimensional Array • We use the following general syntax for declaring and initializing a two dimensional array with specific number of rows and coloumns with initial values. • datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ; • Example Code • int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ; • The above declaration of two-dimensional array reserves 6 contiguous memory locations of 2 bytes each in the form of 2 rows and 3 columns. And the first row is initialized with values 1, 2 & 3 and second row is initialized with values 4, 5 & 6.
  • 125.
    Accessing Individual Elementsof Two Dimensional Array • In a c programming language, to access elements of a two- dimensional array we use array name followed by row index value and column index value of the element that to be accessed. Here the row and column index values must be enclosed in separate square braces. In case of the two-dimensional array the compiler assigns separate index values for rows and columns. We use the following general syntax to access the individual elements of a two-dimensional array... • arrayName [ rowIndex ] [ columnIndex ] • Example Code • matrix_A [0][1] = 10 ; • In the above statement, the element with row index 0 and column index 1 of matrix_A array is assinged with value 10.
  • 126.
    Applications of Arraysin C ● Arrays are used to Store List of values In c programming language, single dimensional arrays are used to store list of values of same datatype. In other words, single dimensional arrays are used to store a row of values. In single dimensional array data is stored in linear form. ● Arrays are used to Perform Matrix Operations We use two dimensional arrays to create matrix. We can perform various operations on matrices using two dimensional arrays. ● Arrays are used to implement Search Algorithms We use single dimensional arrays to implement search algorihtms like ... Linear Search,Binary Search ● Arrays are used to implement Sorting Algorithms We use single dimensional arrays to implement sorting algorihtms like ... Insertion Sort,Bubble Sort,Selection Sort,Quick Sort,Merge Sort, etc., ● Arrays are used to implement Datastructures We use single dimensional arrays to implement datastructures like... Stack Using Arrays,Queue Using Arrays ● Arrays are also used to implement CPU Scheduling Algorithms