Upload
others
View
4
Download
0
Embed Size (px)
Citation preview
Contents
28-09-2018
• Introduction: Basic block diagram and functions of various components of computer
• Flow charts and Algorithms
• Programming, Machines
• Knowledge about problem solving,
• What are programs, How to program, Steps followed in Program Development,
• Importance of Discipline in Programming, Good Programs and Bad Programs
Definition of Computer
28-09-2018
• A computer is an electronic device used to store and process information.
• It plays a major role in our lives.
• You use computers in education and research.
• You also use them for broadcasting news, receiving and sending messages to family and friends, making presentations, maintaining official and personal records, making weather forecasts, and for various other business and recreation activities.
• By using computers, you save a lot of time, effort, and money.
Internally
28-09-2018
1. Optical Drive 2. AirPort Extreme Card slot 3. System Blowers 4. Hard Drive 5. Right Speaker 6. I/O Ports 7. Power Supply 8. Diagnostic LEDs 9. Power PC G5 Processor 10.DIMM slots 11.Left Speaker
Fig1. Internal structure of Computer
Connections
28-09-2018
1. AirPort Antenna 2. Bluetooth Antenna 3. Optical Audio out 4. Optical Audio in 5. Analog Audio out 6. Analog Audio in 7. USB 2.0 8. FireWire 400 9. FireWire 800 10.10/10/1000BASE-T Ethernet 11.Modem
Fig2. Connections
Block Diagram of Computer
28-09-2018
Input Unit
Storage Unit
Output Unit
Control Unit
ALU
Program and Data
Results on the basis of decisions
Fig3. Block Diagram of Computer
• INPUT UNIT • Keyboard, mouse, joystick, scanner, touch screen
etc.
• STORAGE UNIT • Primary Devices : e.g. RAM,ROM • Secondary Devices: e.g. HDD, Floppy Disk, CD-
ROM, CD-R, DVD etc.
• OUTPUT UNIT • Printers, Monitors, LCD etc.
• PROCESSING UNIT • CPU (CU + ALU)
28-09-2018
Block Diagram of Computer
28-09-2018
Internal structure of Pentium microprocessor
The very first microprocessor had a 100KHz clock, whereas the Pentium Pro uses a 200MHz clock, which is to say it ticks 200 million times per second.
Fig4. Structure of microprocessor
• Problem - An obstacle which makes it difficult to achieve a desired goal, objective or purpose.
• Solving problem is the core of computer science
• Programmers must first understand
• how a human solves a problem,
• then understand how to translate this "algorithm" into something a computer can do,
• and finally how to "write" the specific syntax (required by a computer) to get the job done.
28-09-2018
Problem Solving
1. Define the problem
2. Analyze the problem
3. Generate possible solutions to the problem
4. Analyze the solutions
5. Select the best solution(s)
6. Implement the solution
28-09-2018
Problem Solving Process
• Tools a software developer uses when creating new programs.
• Algorithm - step-by-step recipe for processing data.
• Flowchart - graphically represents the steps a program or set of programs takes to process data.
• With algorithm and flowchart, we can easily understand a program.
28-09-2018
Algorithms & Flowcharts
28-09-2018
Symbols used in flowchart
Oval shaped symbol is used to denote the start/end of program
This symbol is used to show the I/O performed
This symbol is used to show the process
This symbol represents the point where decision is made
This symbol is used to show the I/O performed
Oval shaped symbol is used to denote the start/end of program
• A program is a set of instructions used to control the behavior of a machine, often a computer (in this case it is known as a computer program).
• Examples of programs include:
• A computer program list of instructions to be executed by a computer.
• Barrels, punched cards and music rolls encoding music to be played by player pianos, fairground organs, barrel organs and music boxes.
28-09-2018
Programming Machines
• Set of instructions executed directly by a computer's central processing unit (CPU).
• Each instruction performs a very specific task, such as a load, a jump, or an ALU operation on a unit of data in a CPU register or memory.
• Every program directly executed by a CPU is made up of a series of such instructions.
28-09-2018
Machine Language
Learning to program means
learning how to solve problems using code.
• Instructing a computer to do something with the help of a programming language.
• In programming we deal with three kind of things:
• Data
• Procedures
• Program
28-09-2018
What is Programming?
1. Define the problem
2. Outline the solution
3. Develop the outline into an algorithm
4. Test the algorithm for correctness
5. Code the algorithm into a programming language
6. Run the program on computer
7. Document and maintain the program
28-09-2018
Steps in Program Development
• An undisciplined developer will not be able to ship on time and will not write code that is easy to maintain.
• A disciplined developer will not only enable the success of a project, but will raise the level of productivity in others.
28-09-2018
Discipline in Programming
• If program produces what is required, and is correct in its output, then is this a ‘good’ program.
• Program executes successfully for n number of test cases.
• Characteristics of good program include: • Run-time efficient • User Friendly • Self Documenting code (uses meaningful names for identifiers) • Portable • Reusable • Robust (can handle unexpected conditions)
28-09-2018
Good Program v/s Bad Program
• Characteristics of bad program:
• Messy, unreadable code
• Bugs, bugs everywhere
• Not well tested
• No documentation / comments
• Not well organised
• No indentation
• No robustness
28-09-2018
Good Program v/s Bad Program
FAQs
• Explain the functioning of a keyboard with diagram.
• Explain the functioning of a mouse.
• How a computer performs decision making?
• What are the types of dynamic RAM?
• What is eMMC chip?
• What is the difference between DDR, DDR2, DDR3, DDDR4?
• Draw a flowchart to find average of two numbers.
28-09-2018
Contents
28-09-2018
• Features of C language
• Structure of C Program,
• comments, header files, data types, constants and variables, operators, expressions,
• evaluation of expressions,
• type conversion,
• precedence and associatively,
• I/O functions
• Structure of C program is defined by set of rules called protocol, to be followed by programmer while writing C program. All C programs are having sections/parts which are mentioned below.
28-09-2018
Structure of C Program
1. Documentation section 2. Link Section 3. Definition Section 4. Global declaration section 5. Function prototype declaration section 6. Main function 7. User defined function definition section
/* The following is a simple C program that prints a message on the screen. */
1. #include<stdio.h> // header file
2. #include<conio.h> // header file
3. void main()
4. {
5. clrscr();
6. printf(“Welcome to C”);
7. getch();
8. }
Structure of C Program
1. All C statements must end with semicolon.
2. C is case-sensitive. That is, upper case and lower case characters are different. Generally the statements are typed in lowercase.
3. C statement can be written in one line or it can split into multiple lines.
4. Braces must always match upon pairs, i.e., every opening brace { must have a matching closing brace }.
5. Every C program starts with void main() function.
6. Comments cannot be nested. For example,
/*Welcome to ‘C’,/*programming*/*/
A comment can be split into more than one line.
Rules to write C Program
• Preprocessor directives
• Header files
• Character set
• Keywords
• Identifiers
• Variables
• Constants
• Operators
• Data types and their storage
28-09-2018
Basic Constructs
• Before a C program is compiled in a compiler, source code is processed by a program called pre-processor.
• Commands used in pre-processor are called pre-processor directives and they begin with “#” symbol.
Pre-processor Directive
• A file with extension .h which contains C function declarations and macro definitions and to be shared between several source files.
• Types of header files:
• the files that the programmer writes and the files that come with your compiler.
• Request the use of a header file in program by including it, with the C pre-processing directive #include which comes along with your compiler.
28-09-2018
Header File
28-09-2018
C Variables
• An entity that may vary during program execution is called a variable.
• Variable names are names given to locations in memory.
• These locations can contain integer, real or character constants. In any language, the types of variables that it can support depend on the types of constants that it can handle.
• For example, an integer variable can hold only an integer constant, a real variable can hold only a real constant and a character variable can hold only a character constant.
28-09-2018
Data Types
Sr. No. Types Data Types
1 Basic/Primary data types int, char, float, double
2 User-defined/Enumeration data types
enum
3 Derived data type pointer, array, structure, union
4 Empty/Void data type void
• An operator is a symbol that tells the compiler to perform certain mathematical or logical manipulations.
• Operators are used in program to manipulate data and variables. The data items that operators act upon are called operands.
• Some operators require two operands, while others act upon only one operand. The operators are classified into unary, binary and ternary depending on whether they operate on one, two or three operands respectively.
28-09-2018
Operators
1. Arithmetic Operators
2. Increment & Decrement Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Assignment Operators
7. Conditional Operators
8. Some Special Operators
28-09-2018
Types of Operators
Precedence of Operators
• Precedence establishes the hierarchy of one set of operators over another when an arithmetic expression has to be evaluated.
• It refers to the order in which C evaluates operators.
• The evaluation of operators in an arithmetic expression takes place from left to right for operators having equal precedence .
E.g. k = 2 * 3/4 + 4/4 + 8–2 + 5/8 ;
O/P => 8
Precedence of Operators
• For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
• Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
• Associativity tells how an operator associates with its operands.
for eg:
1. The unary minus associates minus with the quantity to its right.
2. The assignment operator = associates from right to left.
• Hence the expression on the right is evaluated first and its value is assigned to the variable on the left.
• Associativity also refers to the order in which c evaluates operators in an expression having same precedence.
• Such type of operator can operate either left to right or vice versa.
28-09-2018
Associativity of Operators
• The operator () function call has highest precedence & the comma operator has lowest precedence
• All unary , conditional & assignment operators associate RIGHT TO LEFT .
• All other remaining operators associate LEFT TO RIGHT
28-09-2018
Associativity of Operators
• The operator () function call has highest precedence & the comma operator has lowest precedence
• All unary , conditional & assignment operators associate RIGHT TO LEFT .
• All other remaining operators associate LEFT TO RIGHT
28-09-2018
Associativity of Operators
28-09-2018
Associativity chart
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
28-09-2018
Associativity chart
Category Operator Associativity
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
• In programming, an expression is any legal combination of symbols that represents a value.
• C Programming Provides its own rules of Expression, whether it is legal expression or illegal expression. For example, in the C language x+5 is a legal expression.
• Every expression consists of at least one operand and can have one or more operators.
• Operands are values and Operators are symbols that represent particular actions.
28-09-2018
Expressions
• Expressions can be classified on the basis of Position of Operators in an expression –
28-09-2018
Types of Expressions
1. First parenthesized sub expression from left to right are evaluated.
2. If parentheses are nested, the evaluation begins with the innermost sub expression
3. The precedence rule is applied in determining the order of application of operators in evaluating sub expressions
4. The associatively rule is applied when 2 or more operators of the same precedence level appear in a sub expression.
5. Arithmetic expressions are evaluated from left to right using the rules of precedence
6. When parentheses are used, the expressions within parentheses assume highest priority
28-09-2018
Rules for evaluating expression
• L-Value stands for left value
• L-Value of Expressions refer to a memory locations
• In any assignment statement L-Value of Expression must be a container(i.e. must have ability to hold the data)
• Variable is the only container in C programming thus L Value must be any Variable.
• L Value cannot be Constant, Function or any of the available data type in C.
28-09-2018
L- value and R-value
• R Value stands for Right value of the expression.
• In any Assignment statement R-Value of Expression must be anything which is capable of returning Constant Expression or Constant Value.
• Example:
28-09-2018
L- value and R-value
• It may so happen that the type of the expression and the type of the variable on the left-hand side of the assignment operator may not be same.
• In such a case the value of the expression is promoted or demoted depending on the type of the variable on left-hand side of =.
• C allows for conversions between the basic types, implicitly or explicitly
28-09-2018
Type conversions
• Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly through the use of the cast operator.
• It is considered good programming practice to use the cast operator whenever type conversions are necessary
28-09-2018
Type conversions
#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}
28-09-2018
Type casting/ explicit conversion
When the above code is compiled and executed, it produces the following result: Value of mean : 3.400000
NOTE: It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value.
(a) An arithmetic operation between an integer and integer always yields an integer result.
(b) An operation between a real and real always yields a real result.
(c) An operation between an integer and real always yields a real result. In this operation the integer is first promoted to a real and then the operation is performed. Hence the result is real.
28-09-2018
Implicit conversion
• Conversion during assignments:
char c='a';
int i;
i=c; /* i is assigned the ASCII code of ‘a’ */
28-09-2018
Implicit conversion
(a) Console I/O functions - Functions to receive input from keyboard and write output to VDU.
(b) File I/O functions - Functions to perform I/O operations on a floppy disk or hard disk.
28-09-2018
Basic I/O Functions
• 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.
• For example, if values of average marks and percentage marks are to be displayed on the screen, then the details like where this output would appear on the screen, how many spaces would be present between the two values, the number of places after the decimal points, etc. can be controlled using formatted functions.
Console I/O Functions
FAQs
• What is the difference between formatted and unformatted functions? Give example.
• Evaluate the following expressions:
a. (a+(a*b/c)
b. (a%c/b)
where a= 5,b=10,c=15
• What is difference between basic, user-defined and derived data type?
• Explain the concept of variable with block diagram.
28-09-2018
Contents
28-09-2018
• Simple statements
• Decision making statements
• looping statements
• nesting of control structures,
• Jump statements
Simple statements
28-09-2018
• Smallest standalone element of an imperative programming language that expresses some action to be carried out.
• An instruction written in a high-level language that commands the computer to perform a specified action
• Example: • assertion: assert(ptr != NULL); • assignment: A:= A + 5 • goto: goto next; • return: return 5; • call: CLEARSCREEN()
• Determines the order in which the statements are executed.
• Must specify that a statement, or a group of statements, is to be carried out conditionally, only if some condition is true.
• Need to run the statement or a group of statements repeatedly based on certain conditions.
28-09-2018
Control Statements
• A conditional structure (or decision making) can be implemented in C using
• The if statement
• The if-else statement
• The nested if-else statement
• The switch statement
Decision/Conditional
IF statement
• The if statement is used to control the flow of execution of statements.
• The general form of if statement is
if(condition)
statement;
Decision/Conditional
IF ELSE statement
• If the condition is true, then statement1 is executed.
• Otherwise if the condition is false, then the statement2 is executed.
• Here statements statement1 and statement2 are either simple statements or compound statements.
• The general form of if statement is
if(condition)
statement 1;
else
statement 2;
Decision/Conditional
IF ELSE statement
if(condition)
{
statements /*if block*/
}
else
{
statements /*else*/
}
Decision/Conditional
IF ELSE IF statement / Nested IF ELSE
• When a series of conditions are involved, the programmer can use more than one if-else statement in nested form.
• This form is also known as if-else-if-else statements. The general form of if-else-if-else statement is
if(condition)
statements;
else if(condition)
statements;
else
statements;
Decision/Conditional
Contents
28-09-2018
• Simple statements
• Decision making statements
• looping statements
• nesting of control structures,
• Jump statements
Simple statements
28-09-2018
• Smallest standalone element of an imperative programming language that expresses some action to be carried out.
• An instruction written in a high-level language that commands the computer to perform a specified action
• Example: • assertion: assert(ptr != NULL); • assignment: A:= A + 5 • goto: goto next; • return: return 5; • call: CLEARSCREEN()
• Determines the order in which the statements are executed.
• Must specify that a statement, or a group of statements, is to be carried out conditionally, only if some condition is true.
• Need to run the statement or a group of statements repeatedly based on certain conditions.
28-09-2018
Control Statements
• A conditional structure (or decision making) can be implemented in C using
• The if statement
• The if-else statement
• The nested if-else statement
• The switch statement
Decision/Conditional
IF statement
• The if statement is used to control the flow of execution of statements.
• The general form of if statement is
if(condition)
statement;
Decision/Conditional
IF ELSE statement
• If the condition is true, then statement1 is executed.
• Otherwise if the condition is false, then the statement2 is executed.
• Here statements statement1 and statement2 are either simple statements or compound statements.
• The general form of if statement is
if(condition)
statement 1;
else
statement 2;
Decision/Conditional
IF ELSE statement
if(condition)
{
statements /*if block*/
}
else
{
statements /*else*/
}
Decision/Conditional
IF ELSE IF statement / Nested IF ELSE
• When a series of conditions are involved, the programmer can use more than one if-else statement in nested form.
• This form is also known as if-else-if-else statements. The general form of if-else-if-else statement is
if(condition)
statements;
else if(condition)
statements;
else
statements;
Decision/Conditional
SWITCH statement
• The Switch statement is an extension of the if-else if-else statement. The switch makes one selection when there are several choices to be made.
• IF statement is used to select among two alternatives whereas SWITCH statement is used to select among multiple alternatives.
• IF statement uses boolean expression to decide which alternative to be executed whereas SWITCH statement uses int expression to decide which alternative to be executed.
• IF statement increases the complexity of a program as alternatives increases.
Decision/Conditional
switch(variable)
{
case value1:
statements;
break;
case value2:
statements;
break;
case value3:
statements;
break;
default:
statements;
}
Decision/Conditional
General syntax of switch
NOTE: •Here, expression must be an integer value. • value1, value2 …. Value n are constants and are called as case labels. • Statements could be single statement or compound statement.
• A portion of program that is executed repeatedly is called a loop.
• The C programming language contains three different program statements for program looping. They are
• for loop
• while loop
• do-while loop
Looping/Repetition
FOR Loop
• The for loop is used to repeat the execution statement for some fixed number of times.
• The general form of for loop is
for(initialization; condition; increment/decrement)
{
statement;
}
where the statement is single or compound statement.
Looping/Repetition
Nested FOR Loop
• Nesting of loop means one loop defined within another loop (embedded) .
• The nesting may continue upto 15 levels or more i.e. compiler dependent.
Looping/Repetition
Nested FOR Loop Flowchart
Looping/Repetition
for(intialization; condition; updation) { for(intialization; condition; updation) { statement; } }
WHILE Loop
• The while loop is best suited to repeat a statement or a set of statements as long as some condition is satisfied.
• The general form of while loop is
initial expression;
while(conditional-expression)
{
statement;
increment/decrement;
}
Looping/Repetition
DO-WHILE Loop
• The structure of do-while loop is similar to while loop.
• The difference is that in case of do-while loop the expression is evaluated after the body of loop is executed.
• In case of while loop the expression is evaluated before executing body of loop.
• The general form of do-while statement is
do
{
statements;
} while(expression);
Looping/Repetition
DO-WHILE Loop
• The structure of do-while loop is similar to while loop.
• The difference is that in case of do-while loop the expression is evaluated after the body of loop is executed.
• In case of while loop the expression is evaluated before executing body of loop.
• The general form of do-while statement is
do
{
statements;
} while(expression);
Looping/Repetition
• C language provides us multiple statements through which we can transfer the control anywhere in the program.
• Jump statements cause an unconditional jump to another statement elsewhere in the code.
• They are used primarily to interrupt switch statements and loops.
• There are basically 3 Jumping statements: 1. break 2. continue 3. goto
Jumping
BREAK and CONTINUE statements
• Loops perform a set of repetitive task until text expression becomes false.
• Sometimes it is desirable to skip some statement/s inside loop
or
• terminate the loop immediately without checking the test expression.
Jumping
In such cases, break and continue statements are used
BREAK statement
• In C programming, break is used in terminating the loop immediately after it is encountered.
• The break statement is used with conditional if statement.
• This jumping statements always used with the control structure like
• switch case,
• while,
• do while,
• for loop
Jumping
CONTINUE statement
• It is sometimes desirable to skip some statements inside the loop. In such cases, continue command causes the next iteration of the loop to be started immediately.
• By using this jumping statement, we can terminate the further execution of the program and transfer the control to the beginning of any immediate loop.
• To do all this we have to specify a continue jumping statements whenever we want to terminate any particular condition and restart/continue our execution.
Jumping
GOTO statement
• In C programming, goto statement is used for altering the normal sequence of program execution by transferring control to some other part of the program.
• When, the control of program reaches to goto statement, the control of the program will jump to the label and executes the code below it.
Jumping
• WAP to print the pyramid pattern with 5 number of rows.
• You are given an array of integers an, , and a positive integer k. Find and print the number of (i, j) pairs where i<j and ai + aj is divisible by k .
Sample Input: Sample Output:
n=6, k=3 5
1 3 2 6 1 2
FAQs
Contents
28-09-2018
• Basics of pointers
• Pointer to pointer
• Pointer and array
• Pointer to array
• Array of pointers
• Functions returning a pointer
• Pointer to Function
Introduction
28-09-2018
• A Pointer is nothing but a variable that contains an address which is a location of another variable in memory.
• If one variable contains the address of another variable, the first variable is said to point to the second variable.
• A pointer provides an indirect method of accessing the value of data item.
• Since a pointer is a variable, its value is also used in the memory in another location.
for example:- int var=50;
int *ptr;
ptr=&var; Fig1. Pointer representation
Introduction
28-09-2018
• Pointers are used in situations when passing actual values is difficult or not desired.
• To return more than one value from a function.
• They increase the execution speed.
• The pointer are more efficient in handling the data types .
• Pointers reduce the length and complexity of a program.
• The use of a pointer array to character string results in saving of data.
• To allocate memory and access it( Dynamic memory Allocation).
• Implementing linked lists, trees graphs and many other data structure.
Declaring Pointers
28-09-2018
• Like any variable or constant, you must declare a pointer before using it to store any variable address.
• The general form of a pointer variable declaration is −
type *var-name;
• Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable.
• The asterisk * used to declare a pointer is the same asterisk used for multiplication.
Declaring Pointers
28-09-2018
• However, in this statement the asterisk is being used to designate a variable as a pointer.
• Take a look at some of the valid pointer declarations −
• int *ip; /* pointer to an integer */
• double *dp; /* pointer to a double */
• float *fp; /* pointer to a float */
• char *ch /*pointer to a character*/
Declaring Pointers
28-09-2018
• The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address.
• The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
NULL Pointer
28-09-2018
• It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned.
• This is done at the time of variable declaration.
• A pointer that is assigned NULL is called a null pointer.
• The NULL pointer is a constant with a value of zero defined in several standard libraries.
Pointer Concepts
28-09-2018
• Pointer Arithmetic
• Array of Pointers
• Pointer to array
• Pointer to pointer
• Passing pointers to function
• Return pointer from function
Pointer Arithmetic
• There are four arithmetic operators that can be used on pointers: ++, --, +, -
• To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000.
• Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer −
ptr ++
1000
ptr 1000 1004 1008 1012
Fig2. incrementing Pointer
Pointer Arithmetic
• After performing ptr++, ptr will now point to memory location 1004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location.
• This operation will move the pointer to the next memory location without impacting the actual value at the memory location.
1004
ptr 1000 1004 1008 1012
Fig3. incrementing Pointer
POINTER COMPARISON
• Pointers may be compared by using relational operators, such as ==, <, and >.
• If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared.
28-09-2018
Pointer Arithmetic
• When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array.
• Base address which gives location of the first element is also allocated by the compiler.
• Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
• Assuming that the base address of arr is 1000 and each integer requires two byte, the five element will be stored as follows:
28-09-2018
Pointer & Arrays
• Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0].
• Therefore arr is containing the address of arr[0] i.e 1000.
28-09-2018
Pointer & Arrays
Fig4. Array & Pointer
• As studied above, we can use a pointer to point to an Array, and then we can use that pointer to access the array. Lets have an example, • int i; • int a[5] = {1, 2, 3, 4, 5}; • int *p = a; // same as int*p = &a[0] • for (i=0; i<5; i++) • {
• printf("%d", *p); • p++;
• }
28-09-2018
Pointer to Array
• In the above program, the pointer *p will print all the values stored in the array one by one.
• We can also use the Base address (a in above case) to act as pointer and print all the values.
28-09-2018
Pointer to Array
We can also have array of pointers. Pointers are very helpful in handling character array with rows of varying length.
28-09-2018
Array of Pointers
• Till now we have used or learned pointer to a data type like character, integer etc.
• But in this section we will learn about pointers pointing to pointers.
• As the definition of pointer says that its a special variable that can store the address of an other variable.
• Then the other variable can very well be a pointer.
• This means that its perfectly legal for a pointer to be pointing to another pointer.
28-09-2018
Pointer to Pointer
•Double pointer allows user to initialize a pointer that points to another pointer.
•Example:
char array[4] = {'a','b','c',''}; //a char array
char *pr = array; //pointer that point to a memory cell with char type
char **ppr = pr; //pointer that points to the pointer 'pr'
28-09-2018
Pointer to Pointer
• C allows us to return a pointer from a function. To do so, you have to declare a function like this:
int * myfunction( )
{
------------;
------------;
}
28-09-2018
Function returning Pointer
Example:
•In this case you must be careful, because local variables of function doesn't live outside the function.
•Hence if you return a pointer connected to a local variable, that pointer be will pointing to nothing when function ends.
28-09-2018
Function returning Pointer
•It is not a good idea to return the address of a local variable outside the function, so you would have to define the local variable as static variable.
•Now, consider the following function which will generate 10 random numbers and return them using an array name which represents a pointer, i.e., address of first array element.
28-09-2018
Function returning Pointer
• Either use argument with functions.
• Because argument passed to the functions are declared inside the calling function, hence they will live outside the function called.
• Or, use static local variables inside the function and return it.
• As static variables have a lifetime until main() exits, they will be available through out the program.
28-09-2018
Safe Way to return Valid Pointer
• It is possible to declare a pointer pointing to a function which can then be used as an argument in another function.
• A pointer to a function is declared as follows,
• type (*pointer-name)(parameter);
• Example :
• int (*sum)(); //legal declaration of pointer to function
• int *sum(); //This is not a declaration of pointer to function
28-09-2018
Pointer to Function
int sum(int, int); int (*s)(int, int); s = sum;
1. You have to complete the function void update(int *a,int *b), which
reads two integers as argument, and sets a with the sum of them,
and b with the absolute difference of them.
• Input will contain two integers, a and b, separated by a newline.
• You have to print the updated value of a and b, on two different lines.
• Code is given on the next slide
28-09-2018
Questions for Practice
2. Write a C program to print string using pointers.
3. Write a C program to swap two numbers using pointers.
4. Write a program to find the sum of two numbers by creating a
pointer function.
28-09-2018
Questions for Practice
Contents
28-09-2018
• Concepts of user defined functions
• Prototypes
• Definition of function
• Parameters
• Parameter passing
• Calling a function
• Recursive function
• Macros
• Pre-processing
Introduction
28-09-2018
• In the earlier lessons we have already seen that C supports the use of library functions, which are used to carry out a number of commonly used operations or calculations.
• C also allows programmers to define their own functions for carrying out various individual tasks.
• In this lesson we will cover the creation and utilization of such user-defined functions.
Functions
28-09-2018
• Function is a self-contained block of program that performs a particular task.
• Every C program is collection of functions.
• Function is a complete and independent program which is used (or invoked or called) by the main program or subprograms.
• Thus, a C program can be modularized through the intelligent use of such functions.
Functions
28-09-2018
• For example many programs require a particular group of instructions to be accessed repeatedly from several different places within a program.
• The repeated instruction can be placed within a single function, which can then be accessed whenever it is needed.
Fig1. Use of functions
Types of Functions
28-09-2018
• C functions can be classified into two categories, namely library functions and user-defined functions.
• main() is an example of user-defined functions.
• printf() and scanf() belong to the category of library functions.
• The main distinction between these two categories is that library functions are not required to be written by the programmers whereas a user-defined function has to be developed by the user at the time of writing a program.
Need of User-Defined Functions
28-09-2018
• Sometimes certain type of operations or calculations are repeated at many
points throughout a program.
• For e.g. calculating factorial of a number several times in the same
program.
• In such situations, we may repeat the program statements wherever they
are needed.
• Another approach is to design a function that can be called and used
whenever required.
• This saves both time and space.
General form of Function
28-09-2018
• Before defining your own user-defined function, it is necessary to declare the function globally.
• By declaring the function, we are informing the compiler about the return type, name and parameter of the function that we are going to use in our program.
Function Declaration
return_type function_name(argument1,argument2,…);
Function Definition
28-09-2018
• When the function will be called, compiler will look for the definition of function inside the source code in order to give you the desirable output.
• Compiler will compare the return type, number of arguments and types of argument with those present in function call.
Function Definition
28-09-2018
• If the compiler is unable to find the function definition, then the compile time error will be generated.
Function Call
28-09-2018
• While creating a C function, the programmer give a definition of what the function has to do.
• To use a function, programmer will have to call that function to perform the defined task.
• When a program calls a function, program control is transferred to the called function.
Function Call
28-09-2018
• A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.
Fig2. Function call
Structure of Function
28-09-2018
• So, lets wind up the structure of a function.
• C function involves the following components:
• Function Declaration/ Function Signature/ Function Prototype
• Function Call
• Function Definition
Types of User-Defined Functions
28-09-2018
Function can be divided into 4 categories:
• A function with no arguments and no return value
• A function with no arguments and a return value
• A function with an argument or arguments and returning no value
• A function with arguments and returning a values
Arguments/Parameters
28-09-2018
• Actual parameter – This is the argument which is used in function call.
• Formal parameter – This is the argument which is used in function definition
Passing Arguments to a Function
28-09-2018
• If a function is to use arguments, it must declare variables that accept the values of the arguments.
• These variables are called the formal parameters of the function.
• The formal parameters behave like other local variables inside the function
• They are created upon entry into the function and destroyed upon exit.
Passing Arguments to a Function
28-09-2018
• While calling a function, there are two ways that arguments can be passed to a function:
1. Call by value (passing value of variable during function call)
2. Call by reference (passing address of variable during function call)
Call by Value
28-09-2018
• It copies the actual value of an argument into the formal parameter of the function.
• Changes made to the parameter inside the function have no effect on the argument.
• By default, C programming language uses call by value method to pass arguments.
• In general, this means that code within a function cannot alter the arguments used to call the function.
• Consider the function swap() definition as follows.
Call by Reference
28-09-2018
• Copies the address of an argument into the formal parameter.
• Inside the function, the address is used to access the actual argument used in the call.
• This means that changes made to the parameter affect the passed argument.
• To pass the value by reference, argument pointers are passed to the functions just like any other value.
Call by Reference
28-09-2018
• You need to declare the function parameters as pointer types in function swap(), which exchanges the values of the two integer variables pointed to by its arguments.
Recursive Function
28-09-2018
• The process of calling a function by itself is called recursion.
• The function which calls itself is called recursive function.
• Recursion is used to solve various mathematical problems by dividing it into smaller problems.
• This method of solving a problem is called Divide and Conquer.
• In programming, it is used to divide complex problem into simpler ones and solving them individually.
Recursive Function
28-09-2018
• C Program to show infinite recursive function
#include<stdio.h>
int main()
{
printf("Hello world");
main();
return 0;
}
Cons/Pros
28-09-2018
• Recursion is more elegant and requires few variables which make program clean.
• Recursion can be used to replace complex nesting code by dividing the problem into same problem of its sub-type.
• In other hand, it is hard to think the logic of a recursive function.
• It is also difficult to debug the code containing recursion.
Macros
28-09-2018
• Macro is a symbol recognized by pre-processor and replaced by the macro body.
• Structure of simple macro is:
#define identifier replacement_list
• Example:
#define WORDLEN 64
#define MAX 60
#define BUFFERSIZE 1024
Macros v/s Functions
28-09-2018
• Macros may be slightly faster than functions.
• Don’t incur the overhead of function call.
• However, resulting code size could be larger.
• Macros are generic.
• Parameters don’t have associated type.
• Arguments are not type checked.
Macros v/s Functions
28-09-2018
• The macro arguments are not evaluated before macro expansion.
• For example consider the following program
#include <stdio.h>
#define MULTIPLY(a, b) a*b
int main()
{
// The macro is expended as 2 + 3 * 3 + 5, not as 5*8
printf("%d", MULTIPLY(2+3, 3+5));
return 0;
}
Macros v/s Functions
28-09-2018
• The macros can take function like arguments, the arguments are not checked for data type.
#include <stdio.h> #define INCREMENT(x) ++x int main() { char *ptr = "GeeksQuiz"; int x = 10; printf("%s ", INCREMENT(ptr)); printf("%d", INCREMENT(x)); return 0; }
1. Write a C program to find factorial of a given number using recursion.
2. Explain the process of pre-processing.
3. How header files are pre-processed?
4. Explain the following terms in brief- i. Directives ii. Pre-processing iii. Stack iv. Heap v. Local and global variables
28-09-2018
Questions for Practice
Contents
28-09-2018
• Concept of array
• one and two dimensional array
• declaration and initialization of array
• string
• string storage
• Built-in-string functions
Arrays
28-09-2018
• Many tasks require storing and processing a list of data items.
• For example, we may need to store a list of exam scores and to process it in numerous ways,
• find the maximum and minimum average the scores,
• sort the scores in descending order search for a specific score, etc.
• Data items in simple lists are usually of the same scalar type.
• For example, a list of exam scores consists of all integer type items.
Arrays
28-09-2018
• C provides a derived data type that stores such a list of objects where each object is of the same data type - the array.
• An array is defined as finite ordered collection of homogenous data, stored in contiguous memory locations.
• finite means data range must be defined.
• ordered means data must be stored in continuous memory addresses.
• homogenous means data must be of similar data type.
Types of Arrays
28-09-2018
1. One dimensional array
2. Multi dimensional array
• Two dimensional array
• Three dimensional array, four dimensional array etc…
Declaring 1-D Array
28-09-2018
• Like any other variable, arrays must be declared before they are used.
• General form of array declaration is:
datatype variable_name [ size ];
• For example:
int a[5]; // array declaration
int a[5]= { 1,3,8,23, 99 };
where a[0] =1, a[1] =3, a[2] =8,
a[3] = 23, a[4] =99.
Initializing an array
Key Points
28-09-2018
• Key points about arrays: • Values inside the array can be accessed by specifying the index
number where value is located. • It is mandatory to provide the maximum size of an array. • Size of array must be a constant. • Declaring a variable sized array will give compile time error. • Each element of an array has its own memory address. • The name of an array stores the base address i.e. memory
address of first element. • After an array is declared it must be initialized. Otherwise, it will
contain garbage value(any random value).
• It is not necessary to define the size of arrays during initialization.
• In this case, the compiler determines the size of array by calculating the number of elements of an array.
28-09-2018
Key Points
• All the array elements are stored in continuous memory locations.
• Always base address is used to access the rest of the elements in an array.
• For example, if base address of some array of integers is 1001, then the address of 2nd element will be 1001 + 1*2 = 1003 where 1 is the index number and 2 is size of datatype.
• The program on next page demonstrates that arrays elements are stored in contiguous memory locations.
28-09-2018
Contiguous Memory Allocation
Memory representation of 1-D array
28-09-2018
• Computer memory will be represented as a linear array with low addresses on the left and high addresses on the right.
Memory address
Element
index
Base address
2-D Array
28-09-2018
• 1-D array is organised linearly and only one in direction.
• But at times, we need to store data in form of matrices or tables.
• So, 1-D array is extended to 2-D array.
• Specified using two subscripts i.e. one is for row and other is for column.
• Also called as a array of 1-D arrays.
Declaring 2-D Array
28-09-2018
• Must be declared before used.
• Syntax: data_type array_name[row_size][col_size];
• Example: int arr[5][4];
• Each dimension of 2-D array is indexed from zero to its maximum size minus one.
• The first index selects the row and second selects the column.
• Every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.
Initializing 2-D Array
28-09-2018
• Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.
• The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example:
Strings
28-09-2018
• The string in C programming language is actually a one-dimensional array of characters which is terminated by a null character '\0'.
• The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."
• The string library (string.h or strings.h) has some useful functions for working with strings, like
28-09-2018
String Functions
Table 1. String functions
1. An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. Given an array of N integers and you have to print the integers in the reverse order.
The first line of the input contains N ,where N is the number of integers. The next line contains integers separated by a space.
Sample Input Sample Output
4 2 3 4 1
1 4 3 2
28-09-2018
Questions for Practice
2. Write a C program to remove all characters in a string except alphabet.
Sample Input Sample Output
##Ch@ndig@rh Univer$ity## Chandigrh Univerity
3. What is the difference between strlen( ) and sizeof?
28-09-2018
Questions for Practice
Contents
28-09-2018
• Basics of structure
• Structure members,
• Accessing structure members
• Nested structures
• Array of structures
• Structure and functions
• Structures and pointers
Introduction
28-09-2018
Sr. No. Types Data Types
1 Basic/Primary data types int, char, float, double
2 User-defined/Enumeration data types
enum
3 Derived data type pointer, array, structure, union
4 Empty/Void data type void
Table 1. Datatypes in C
Introduction
28-09-2018
• Structure is a user-defined data type in C
• Allows you to combine different data types to store a particular type of record.
• Structure helps to construct a complex data type in more meaningful way.
• It is somewhat similar to an Array.
• The only difference is that array is used to store collection of similar data-types while structure can store collection of any type of data.
Introduction
28-09-2018
• Structs are generally useful whenever a lot of data needs to be grouped together—
• for instance, they can be used to hold records from a database or to store information about contacts in an address book.
• In the contacts example, a struct could be used that would hold all of the information about a single contact--name, address, phone number, and so forth
Declaring Structure
28-09-2018
• Structure is used to represent a record.
• Suppose you want to store record of Student which consists of student name, address, roll number and age.
• You can define a structure to hold this information.
struct student
{
char name[20];
char UID[10];
int marks;
}
Declaring Structure
28-09-2018
• Syntax for declaring structure:
struct structure_name
{
data_type member1;
data_type member2;
. .
data_type memberN;
};
Don't forget the semicolon }; in the ending line.
Declaring Structure Variable
28-09-2018
• It is possible to declare variables of a structure, after the structure is defined.
• Structure variable declaration is similar to the declaration of variables of any other data types.
• Structure variables can be declared in following two ways.
• Declaring Structure variables separately
• Declaring Structure Variables with Structure definition
Initializing Structure
28-09-2018
• Like any other data type, structure variable can also be initialized at compile time.
Accessing Structure Members
28-09-2018
• Structure members can be accessed and assigned values in number of ways.
• Structure member has no meaning independently.
• In order to assign a value to a structure member, the member name must be linked with the structure variable using dot (.) operator also called period or member access operator.
Accessing Structure Members
28-09-2018
#include<stdio.h>
#include<conio.h>
struct Student
{
char Name[20],Class[10];
int RollNo;
} ;
void main() { struct Student s1[5]; int i; clrscr(); for(i=1;i<=5;i++) { printf("\n Enter the Name of %d Student",i); scanf("%s",&s1[i].Name); printf("\n Enter the Class %d Student",i); scanf("%s",&s1[i].Class); printf("\n Enter the Roll No of %d Student",i); scanf("%d",&s1[i].RollNo); }
Accessing Structure Members
28-09-2018
printf("\n Entered Data is"); printf("\nName\t\tClass\tRollNo"); for(i=1;i<=5;i++) { printf("\n%s\t\t%s\t%d",s1[i].Name,s1[i].Class,s1[i].RollNo); } getch(); }
Nested Structure
28-09-2018
• When a structure contains another structure, it is called nested structure.
• For example, we have two structures named Address and Employee.
• To make Address nested to Employee, we have to define Address structure before and outside Employee structure and create an object of Address structure inside Employee structure.
Nested Structure
28-09-2018
SYNTAX:
struct structure1
{
- - - - - - - - - - - - - - - - - - - -
};
struct structure2
{
- - - - - - - - - - - - - - - - - - - -
struct structure1 obj;
};
Array of Structures
28-09-2018
• C allows us to create an array of variables of structure.
• Used to store large number of similar records.
• For example, to store the record of 100 students, array of structure is used.
• Syntax :
struct struct_name var_name[size];
• Example:
struct student s[100];
PASSING STRUCTURE TO A FUNCTION
• A structure variable can be passed to the function as an argument as a normal variable.
• If structure is passed by value, changes made to the structure variable inside the function definition does not reflect in the originally passed structure variable.
28-09-2018
Structure and Functions
•Like we have array of integers, array of pointer etc, we can also have array of structure variables.
•To make the use of array of structure variables efficient, we use pointers of structure type.
•We can also have pointer to a single structure variable, but it is mostly used with array of structure variables.
28-09-2018
Pointer to Structure
Fig3. Pointer to structure
• Structures can be created and accessed using pointers.
• A pointer variable of a structure can be created as below:
struct name {
member1;
member2;
. .
};
int main()
{ struct name *ptr; } 28-09-2018
Pointer to Structure
• A structure's member can be accesssed through pointer in two ways:
• Referencing pointer to another address to access memory
• Using dynamic memory allocation
28-09-2018
Pointer to Structure
1. Differentiate between Array and Structure. Give minimum 5 points.
2. Write a program to input marks of 50 students using pointers
concept.
3. Define Array within Structure.
28-09-2018
Questions for Practice
Computer Programming & Utilization UCT-144
UNIT-III Dynamic Memory Allocation
University Institute of Applied Science
Introduction
28-09-2018
• In C, the exact size of array is unknown until compile time, i.e., the time when a compiler compiles your code into a computer understandable language.
• So, sometimes the size of the array can be insufficient or more than required.
• Dynamic memory allocation allows your program to obtain more memory space while running, or to release it if it's not required.
• In simple terms, Dynamic memory allocation allows you to manually handle memory space for your program.
Introduction
28-09-2018
• There are four library functions under "stdlib.h" for dynamic memory allocation.
Function Use of Function
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
calloc() Allocates space for an array elements, initializes to zero and then returns a pointer to memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space Table 1: DMA functions
malloc()
28-09-2018
• The name malloc stands for "memory allocation".
• The function malloc() reserves a block of memory of specified size.
• It return a pointer of type void which can be casted into pointer of any form.
• Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
• Here, ptr is pointer of cast-type.
malloc()
28-09-2018
• The malloc() function returns a pointer to an area of memory with size of byte size.
• If the space is insufficient, allocation fails and returns NULL pointer.
• Example:
ptr = (int*) malloc(100 * sizeof(int));
• This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.
calloc()
28-09-2018
• The name calloc stands for "contiguous allocation".
• The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.
• Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
• This statement will allocate contiguous space in memory for an array of n elements.
calloc()
28-09-2018
• For example:
ptr = (float*) calloc(25, sizeof(float));
• This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.
free()
28-09-2018
• Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own.
• You must explicitly use free() to release the space.
• Syntax of free()
free(ptr);
• This statement frees the space allocated in the memory pointed by ptr.
realloc()
28-09-2018
• If the previously allocated memory is insufficient or more than required, you can change the previously allocated memory size using realloc().
• Syntax of realloc()
ptr = realloc(ptr, newsize);
• Here, ptr is reallocated with size of newsize.
Program 1
28-09-2018
• Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using malloc() function.
1. Write a C program to find sum of n elements entered by user. To
perform this program, allocate memory dynamically using calloc()
function.
2. Write a C Program to Find Largest Number Using Dynamic Memory
Allocation.
3. Write a C Program to Store Information Using Structures with
Dynamically Memory Allocation.
28-09-2018
Questions for Practice