Escolar Documentos
Profissional Documentos
Cultura Documentos
Lecture 1-2
Character set, Variables and Identifiers, Built-in Data Types, Variable Definition ,Expressions,Constants and Literals ,Simple assignment statement, Basic input/output statement, Simple C Programs
C Programming Language
What is C?
C is a structured, relatively low-level, portable programming language.
Why study C?
Many popular software tools are written in C. Has strongly influenced many other languages. C-shell, java, C++, Perl, etc. Forces the user to understand fundamental aspects of programming. Very concise language.
History of C
C
Evolved by Ritchie from two previous programming languages, BCPL and B Used to develop UNIX Used to write modern operating systems
C, cont.
Is C object-oriented?
No. C++ (its successor) is.
Result is : Hello,world!
Terms
Source code
Text of a program. The input to the C compiler.
Object code
Translation of the source code of a program into machine code. The input to the linker.
Linker
A program that links separately compiled modules into one program. The output is an executable program.
Terms (cont.)
Library
The file containing the standard functions that a program can use.
Complier time
The time during which a program is being compiled.
Run time
The time during which a program is executing.
Language Types
Three types of programming languages
1. Machine languages Strings of numbers giving machine specific instructions Example:
+1300042774 +1400593419 +1200274027
2. Assembly languages English-like abbreviations representing elementary computer operations (translated via assemblers) Example:
Load Add Store BASEPAY overpay GROSSPAY
High-level Languages
high-level is a relative term C is a relatively low-level high-level language Pascal, Fortran, COBOL are typical high-level languages Java, Python, Perl, VB are examples of high-level high-level languages Application specific languages (Matlab, Javascript, VBScript) are even higher-level.
Declaring types
Declaration allocates a block of memory
Type dictates the size of this block char 1 byte (8 bits) ASCII character code int 4 bytes long int 4 bytes float 4 bytes double 8 bytes
int
int is short for integer Integers are whole numbers
(no fractional part, no decimal point)
Can be positive and negative Short and long Signed and unsigned C has no specific standard on the size of an int, it varies from one C system to another Normally, an int is stored in 2 bytes or 4 bytes
Integer variables are declared int variable_name; e.g. int a; declares that you want to create an int variable called a int is considered the natural type for working with integers Sometimes extra digits are needed to store large numbers not allowed in int long int variable_name; /* 32 bits, not 16 */ Whereas less storage is indicated short int variable_name;
int contd..
int contd.
Unsigned integers contain only positive values, e.g. unsigned int variable_name; Signed integers allow both positive and negative numbers All int declarations default to signed, i.e.
signed int variable_name;
Is equivalent to
int variable_name;
Example
main() { int a, b, c, ;//declaration unsigned u=10;// declaration a =12; b =-24; //assignment c =a+u;d=b+u;// assignment printf(a+u=%d,b+u=%d\n,c, d); } a+u=22, b+u=-14
Integer overflow
At run-time a variable may be assigned an incorrect value. If a value is greater than the maximum value which can be stored in a variable of type int, we get integer overflow
Floating points
A real or floating point number has an integral part and a fractional part, separated by a decimal point, e.g. 0.02, 170.234, 3e+5 Floating point numbers can be either positive or negative always signed in C 3 floating types in ANSI C:
float, double, long double
Keywords
Reserved words. Cannot be redefined or used in other contexts. Case sensitive. Have a special predefined meaning.
Constants
They refer to fixed values that the program may not alter. They can be of any of the basic data types.
Integer: 1. Decimal 0, 77 2. Octal (Base 8) Digits 3. Hexadecimal (Base 16) Digits 09, AF 0. .7
Floating Point:
A character, or more likely a sequence of characters, enclosed in double quotes. A string is an array of characters. A and A are not the same. A is a string containing only one letter.
String Constant
H e l l o ! \0
A is actually A followed by the null character \0.
a = b + c;
// nothing is executed
Punctuators
They are located by the compiler as tokens and are used to separate language elements. Parentheses ( ) Braces {} Commas , Semicolons ; int main(void) { int a, b=3, c=6; a = 17 * (b + c); }
Comments
Multi-Line comments:
/* this is a multiline comment */
May be placed anywhere in a program, as long as they do not appear in the middle of a keyword or identifier. x = 10+ /* add the numbers */5; //correct
Single-Line Comments:
// this is a single-line comment
All but the most obvious functions should have a comment at the top that states what the function does, how it is called, and what it returns.
Variables in C
Topics Naming Variables Declaring Variables Using Variables The Assignment Statement
x=a+b z + 2 = 3(y - 5) Remember that variables in algebra are represented by a single alphabetic character.
Naming Variables
Variables in C may be given representations containing multiple characters. But there are rules for these representations. Variable names in C
May only consist of letters, digits, and underscores May be as long as you like, but only the first 31 characters are significant May not begin with a number May not be a C reserved word (keyword)
Naming Conventions
C programmers generally agree on the following conventions for naming variables.
Begin variable names with lowercase letters Use meaningful identifiers Separate words within identifiers with underscores or mixed upper and lower case. Examples: surfaceArea surface_Area surface_area
Case Sensitivity
C is case sensitive
It matters whether an identifier, such as a variable name, is uppercase or lowercase. Example: area Area AREA ArEa are all seen as different variables by the compiler.
Declaring Variables
Before using a variable, you must give the compiler some information about the variable; i.e., you must declare it. The declaration statement includes the data type of the variable. Examples of variable declarations: int balls ; float area ;
Characters
char
int length = 7 ;
7
diameter
5.9
initial
garbage
#include <stdio.h> int main( ) { int inches, feet, fathoms ; fathoms = 7 ; feet = 6 * fathoms ; inches = 12 * feet ;
feet
garbage
fathoms
garbage
fathoms 7 feet 42 inches 504
Escape characters
Escape Description Sequenc e \n \t Newline, position cursor at the start of a new line Horizontal tab, move cursor to the next tab stop
\r
\a \\ \
Carriage return. Position cursor to the beginning of the current line; do not advance to the next line. Alert, sound system warning beep
Backslash, print a backslash character in a printf statement Double quote print a double quote character in a printf statement.
Data Type
long double double float unsigned long int long int unsigned int int short char
Printf specifier
%Lf %f %f %lu %ld %u %d %hd %c
Scanf specifier
%Lf %lf %f %lu %ld %u %d %hd %c
A simple C Program that reads in two numbers,stores them and prints out the sum
main() { int x,y; /* places to store numbers */ printf("Enter x "); scanf("%d",&x); printf("Enter y "); scanf("%d",&y); printf("The sum of x and y was %d\n",x+y); }
C Program Read string and show output. #include <stdio.h> int main(void) { char str[80]; printf("Enter a string: "); scanf(''%s", str); printf("Here's your string: %s", str); return 0;}
getchar()
Function contained in stdio.h getchar() returns an int code for a character typed on the standard input (the keyboard)
char c; c = getchar() ;
putchar()
Prints a character to the standard output (screen) Is a function also referenced in stdio.h
#include
<stdio.h> int main() {char c; /* declare character variable */ /* read a character and store it in c */ c = getchar() ; /* print it twice, two different ways */ printf("%c\n", c ); putchar( c ) ;/* one character at a time so heres the newline */ c = '\n' ; putchar( c );} /* end program */
Field width.
# of columns output. including dec. pt.
Precision
# of decimal digits to right of decimal pt.
Review questions
1. C's output function printf() is part of the 'C' language a library function a function users must write as part of every 'C' program another name for the function print 2. An escape character can be included in a 'C' string by including the following characters in the string \e ESC \033 \0x1B
Contd..
3.Conventionally 'C' source files have names ending in .c .cpp .bas .html 4.The effect of writing print() rather than printf() is that The program will not compile The program will work as expected The program will display "hello world" in inverse video The program will not link correctly
Contd..
5. All 'C' programs must include The keyword 'program' A function called 'main' The name of the author A lest one use of the printf() function
Contd..
True/False ___, ___, ____, _____, _______ are the different data types in C. . String variables are terminated automatically with _______ . . _____ is the escape sequence for bell. . Floating-point constant contains either a _______ or an _______ or both. . Signed integers can range ______ and unsigned integers can range ______
Part A Q a) 1: Fill in the blanks : Basic data types in C are ________, _______, _______ and __________.
b) __________ terminates a statement in C. c) The symbols _____ and ______ mark the beginning and end of a comment. d) Every C program must have a function called _________. e) In a variable name the first character must be _______.
Q 2: State True/False: a) All variables must be declared before their usage in a program. b) An integer variable will be initialized to zero automatically if not done explicitly.
c) Comments must be restricted to one line only. d) Comments must begin at the start of a line only. e) getchar(c) accepts the value of c from the terminal. f) putchar() function prints a string on the terminal. Part B Q 1: Write a program which inputs 2 characters using getchar() and swaps them.
Operators
Arithmetic Operators
Relational and Logical Operators Special Operators
Arithmetic Operators
Operator + * / % -++ Action Subtraction, also unary minus Addition Multiplication Division Modulus Decrement Increment
Low
Prefix
++x;
or Postfix x = x + 1;
x++;
++ & -- both cause a value of a variable to change in memory. ( Have a side effect).
Increment Postfix: i++; Expression value is the current value (Before you increment) then it increments. use - then increment Increment Prefix: ++i; Expression value is the value After you increment. increment - then use Decrement Postfix: i--; use - then decrement Decrement Prefix: --i; decrement - then use
Examples
x =10; x =10; y = ++x; y = x++; y 11 y 10
i 5 i 6 j 4
l = 4; n = 3; m = 2;
x = l * n + m++; x
14
c= ?
7-((?
Relational Operators: Operator Action > Greater than >= Greater than or equal < Less than <= Less than or equal == Equal != Not equal
Logical Operators: Operator Action && AND || OR ! NOT
<=
Low
!0&&0||0
((!0)&&0)||0
FALSE
__?
Both are lower in precedence than the arithmetic operators. 10 > 1 + 12 10 > (1 + 12) FALSE 0
Associativity
left to right.
Examples
!A is false (0) if As value is: __. is true (1) if As value is: __. ! (!5) ! (0) 1 0
!!5
int
i, j = 1;
( ) needed
3) =
i 2 j = j && (i = = 3);
1
( ) not needed
1) (i = = 3)
false
2) && 3) =
j j
&& 0
j 0 i j = j || (i/2)
1) (i/2)
2
( ) not needed
(2/2)
2) || 3) = j
1
|| 1
true
4)
5)
&&
=
0 && 3
j 0
Lowest precedence of all the operators. Causes a sequence of operations, do this and this and this. Is a binary operator. expression_1, expression_2 Associates left to right.
The Comma Expression as a whole has the value and type of expression_2. int i = 2; j = 4;
j = i++, i - j; *i *j
3 -1
(3-4)
It allows multiple initializations and multiple processing of indices. for (sum=0, i=1; i<=n; ++i) sum += i;
Comma Operators can be useful in control statements though many C advocates discourage their use.
?
Ternary operator.
A powerful and convenient operator that replaces certain statements of the if-thenelse form. Exp1 ? Exp2: Exp3
Examples
x = 10; x = 10; y = x>9 ? 100 : 200;
( ) not needed
This statement does what? c = (c > =a && c < = z) ? c - (z - Z):c; IF True - have a Lower case letter in the variable C. Exper2: c - (z - Z) will give Capital Letter of whatever is in C. e.g. a - (z - Z) 97 - (122 90) = 65 which is A.
Expressions
An expression in C is any valid combination of operators, constants, functions and variables. An statement is a valid expression followed by a semicolon.
func(); /* a function call */
a = b+c; /* an assignment statement */ b+f(); ; /* a valid, but strange statement */ /* an NULL statement */
Null Statement:
Can be useful in loops & conditional statements. The body of a loop could be empty . Scanf(%d, &x); While(printf(%d,x) ,scanf(%d,&x)) ;
Expressions (cont.)
Spacing and Parentheses x=10/y-(127/x); x = 10 / y - (127/x);
Redundant or additional parentheses do not cause errors or slow down the execution of an expression. x = y/3-34*temp+127; x = (y/3) - (34*temp) + 127;
Exercises
Given a as 4. If b=a++, then b will be ___ and if b=++a, b will be ____ . The order of the evaluation of the expression depends on ______ and ______ In assignment operator, assignment is done from _____ to ______ . The logical operators in C are ___________ ?: is similar to __________ construct of C.
The type of a variable decides the operators that can at on them. Unary * has a greater precedence over ++. The ! Operator converts a zero to one and a nonzero value to zero. = = is a logical operator to check the equality of two operands. Type conversions involve converting a narrow type to wider type += is one of the ternary operator in C. & and * are also kinds of unary bit wise operators. ++p and p++ means the same in an assignment expression
Exercise Contd.
Exercise contd.
Write a program to read in 3 integers and print their sum. Write a program to read in two integers and display both the quotient and the remainder when they are divided. How does your computer treat the results of division by a negative number? What happens when you try and divide by zero? What error message does your compiler give when you write x+1=x in a program?
Exercise contd..
Write a program to test the behaviour of your computer system when it processes printf("%d %d\n",x++,++x); How do you think the computer will evaluate x+=x++
QUESTION What will be displayed in each of the following : a) a = 7; b = a++; printf ("%d", b); b) a = 7 b = ++a; printf ("%d", b); c) a = 5; while(a) { printf("Hello"); a--; }
d) a = 5;
while(--a) printf("hello");
e) a = 5; while(a--) printf("hello");
Write a program to calculate the area of a circle after accepting the radius of the circle from the standard input.
Selection
if switch
if statement
Conditional execution: if (Boolean expression) statement; else statement; Where a statement may consist of a single statement, a code block, or empty statement. The else clause is optional.
if logic:
YesFor a
Semi-colon
If-else-logic:
Conditional execution allows you write code that reacts to tested conditions.
Example #include <stdio.h> int main ( ) { double salary, payrate; int hours, union; printf (Please enter hours worked, payrate, and union status); printf (Enter 1 if a union member, 0 if not);
Example contd
scanf (%d%lf%d, &hours, &payrate, &union); if (hours > 40 && union = = 1) salary = (40 * payrate) + ((1.5 * payrate) * (hours - 40)); else salary = payrate * hours; printf (Salary is: $ % 6.2 f, salary); }
Nested ifs
Nested: One statement coded within another statement. An nested if is an if that is the target of another if or else.
Nested ifs:
Why Nested ifs? A simple - if and if - else statement are used to handle 2-choice tasks. Nested ifs: Needed to handle tasks where we have 3 or More options that are mutually exclusive.
#include <stdio.h> Nested IF statements main() { int score; printf(Please type in your score:); scanf(%d, &score); printf(Your grade is a ); if (score >= 90) printf{A); else if (score >= 80) printf(B); else if (score >=70) printf(C); else if (score >=50) printf(D); else if (score >= 40) printf(D); else printf(F);}
General form:
if (expression) statement; else if (expression) statement; else if (expression) statement; . . . else statement;
The conditions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed and the rest of the ladder is bypassed.
If none of the conditions are true, the final else is executed. That is, if all other conditional tests fail, the last else statement is performed. If the final else is not present, no action takes place if all other conditions are false.
Example
E.g. You are a salesperson for the Widget Manufacturing Co. You will earn a salary bonus according to the following rules:
Sales > = $50,000 Sales > = $100,000 Sales > = $150,000 earn $5,000 earn $15,000 earn $30,000
double sales, bonus; printf (please enter total sales); scanf (%lf, &sales);
if (sales < 50000) bonus = 0; else if (sales < 100000) bonus = 5000; else if (sales < 150000) bonus = 15000; else bonus = 30000;
Conditional Expression
The expressions must simply evaluate to either a true or false (zero or nonzero) value.
The expressions are not restricted to involving the relational and logical operators.
The ?: Alternative
Exp1 ? Exp2: Exp3
x = 10;
x = 10; y = x>9 ? 100 : 200; if(x>9) y = 100; else y = 200;
int main(void) { int a, b; printf("Enter two numbers: "); scanf(''%d%d", &a, &b); if(b) printf("%d\n", a/b); if(b != 0) printf("%d\n", a/b); else printf("Cannot divide by zero.\n");
return 0; }
switch statement
switch is a multiple-branch selection statement, which successively tests the value of an expression against a list of integer or character constants (floating point expression, for example, are not allowed). When a match is found, the statements associated with that constant are executed.
General Form
switch (expression) { case constant1: statement sequence break; case constant2: statement sequence break; . . default statement sequence } //ANSI C allowed at least 257 case statements.
Execution
The value of the expression is tested against the constants specified in the case statements in a top-down order.. When a match is found, the statement sequence associated with that case is executed until the break statement or the end of the switch statement is reached. When break is encountered in a switch, program execution "jumps" to the line of code following the switch statement. The default statement is executed if no matches are found. The default is optional.
The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of relational or logical expression.
No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch may have case constants that are in common. If character constants are used in the switch statement, they are automatically converted to integers (as is specified by C's type conversion rules).
The switch statement is often used to process keyboard commands, such as menu selection. The following function will when called: display the options, allow the user to make a selection, and then evoke the appropriate function to perform the task selected. void menu(void) { char ch; printf("1. Check Spelling\n"); printf(''2. Correct Spelling Errors\n"); printf("3. Display Spelling Errors\n"); printf("Strike Any Other Key to Skip\n"); printf(" Enter your choice: "); ch = getchar(); /* read the selection from the keyboard */
switch(ch) { case '1': check_spelling (); break; case '2': correct_errors (); break; case '3': display_errors (); break; default : printf("No option selected"); }
/* Assume k is initialized */
switch(k) { case 1: /* These cases have common */ case 2: /* statement sequences. */ If the break is case 3: flag = 0; omitted, break; execution will case 4: continue on into flag = 1; the next case until case 5: either a break or error(flag); the end of the break; switch is reached. default: process(k); }
Nested Switch
You can have a switch as a part of the statement sequence of an outer switch.
Even if the case constants of the inner and the outer switch contain common values, no conflict arise.
switch(x) { case 1: switch(y) { case 0: printf(''Divide by zero error.\n"); break; case 1: process(x, y); break; } break; case 2: .
Exercise
control constructs in C are ___________ and ___________. If- else statement is used for ____________. The case statement values are necessarily_____________. If values do not match any of the cases in switch-case then the control is transferred to ___________, if present.
Exercise
: Differentiate between "break" and "continue" giving examples.
Q 2: Find the sum of all odd no's between 1 and 100. Try to use different looping techniques. Q 3: Write a program to count the number of blanks, tabs and newlines in the input. (switch-case can be used) Q 4: Find the greatest of three numbers using the conditional operator. Q 5: Write a program to calculate the average of the non-negative numbers in a list of n numbers.
Iteration
Iteration statements (also called loops) allow a set of instructions to be repeatedly executed until a certain condition is reached. This condition may be predetermined (as in the for and while loop) or open ended (as do-while loops).
for loop
General form for (initialization; testing; increment) Loop Body; The initialization is an assignment statement that is used to set the loop control variable. The testing is a relational expression that determines when the loop exits. The increment defines how the loop control variable changes each time the loop is repeated.
Execution
The for loop continues to execute as long as the condition is true.
Once the condition becomes false, program execution resumes on the statement following the body of the for loop.
#include <stdio.h>
int main(void) { int x; for(x=1; x <= 100; x++) printf("%d ", x);
return 0; }
for(x=100; x != 65; x -= 5) { z = x*x; printf(''The square of %d, %d", x, z); }
The incrementation of the loop control variable can occur outside the for statement.
for( x=1 ; x < 10; ) { printf("%d", x); ++x; }
While Loop
Check the test condition at the top of the loop. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line of code immediately following the loop.
Example
char wait_for_char(void) { char ch; ch = '\0'; /* initialize ch */ while(ch != 'A') ch = getchar(); return ch; }
while((ch=getchar()) != 'A') ;
/* i.e., true */
while (working) { working = process1(); if (working) working = process2(); if (working) working = process3(); }
NESTED LOOPS
Nested Loop 1 loop syntax coded inside another syntax.
Why?-
Single -Loop?
Have a statement or statements that you want to repeat. A repetitive task that you must solve.
You have a single repetitive task - THAT YOU MUST REPEAT i.e., a repetition of an already repetitive task.
You may have any combination of the 3 loop syntax inside each other. The problem dictates what combination should be used.
/* Find triples of integers that add up to n. */ #include <stdio.h> main() { int cnt = 0, j , k , m,n; n=7; for(j = 0; j <= N; ++j) for( k = 0; k <= N; ++k) for( m = 0: m <= N; ++m) if ( j + k + m == N) { ++cnt; printf(%d%d%d, j , k , m); } printf(\n Count: %d\n, cnt); }
512 times
7 7 7
8 * 8 * 8 = 512
do-while Loop
The most common use of the do-while loop is in a menu selection function.
void menu(void) { char ch; printf("1. Check Spelling\n"); printf("2. Correct Spelling Errors\n"); printf("3. Display Spelling Errors\n"); printf(" Enter your choice: ");
do { ch = getchar(); /* read the selection from the keyboard */ switch(ch) { case '1': check_spelling(); break; case '2': correct_errors(); break; case '3': display_errors(); break; } } while(ch=='1' || ch=='2' || ch=='3'); }
Jump
break continue return (will be introduced in Ch. 4, Functions).
break Statement
#include <stdio.h>
Two uses: You can use it to terminate a case in the switch statement.
int main (void) { int t; for(t=0; t < 100; t++) { printf(''%d ", t); if(t == 10) break; }
You can also use it to force immediate termination of a return 0; loop, bypassing the normal } loop conditional test.
0 1 2 3 4 5 6 7 8 9 10
continue Statement
General form continue; break forces termination of the loop.
continue forces the next iteration of the loop to take place, skipping any code in between.
continue can expedite the exit from a loop by forcing the conditional test to be performed sooner.
For the for loop, continue causes the increment and then the conditional test portions of the loop to execute. For the while and do-while loops, program control passes to the conditional tests.
This function codes a void code(void) message by shifting all { characters you type char done, ch; one letter higher. For done = 0; example, an A while(!done) { becomes a B. The ch = getchar(); function will terminate if(ch == S') { when you type a S. done = 1; continue;} /* test the condition now */
putchar(ch+1); }}
Exercise
What will be displayed in each of the following : a) a = 7; b = a++; printf ("%d", b); b) a = 7 b = ++a; printf ("%d", b); c) a = 5; while(a) { printf("Hello"); a--; }
Exercise Contd.. d) a = 5; while(--a) printf("hello"); e) a = 5; while(a--) printf("hello"); 2.Write a program that converts each lower-case character in the standard input to uppercase and each uppercase character to lower case. Pass all other characters unchanged. 3. Write a program that reads nos. from the standard input and prints the largest value entered, the smallest value, the sum of all values read and the mean of all values inputted.
Question
Write a program that prints the number of occurrences of the character ! in the standard input. Q 8: Write a program that tests whether there are the same number of left brackets, [, as right brackets, ], in the standard input. Q 9: Write a program that takes an integer keyed in from the terminal and extracts and displays each digit of the integer in English. Q10: Write a program that converts each lower-case character in the standard input to uppercase and each uppercase character to lower case. Pass all other characters
Arrays
What is an "array"? A way to collect together data of a single type in a single object A linear sequence of data objects e.g.
array of ints
array of chars (string)
arr[0] = 1;
arr[1] = 22;
arr[2] = -35;
sum = arr[0] + arr[1] + arr[2];
partially initialized
not initialized
# include <stdio.h> int main (void) { int u,j,k, temp,no_elements,array [20]; printf (Enter the number of elements: ); scanf (%d,&no_elements); printf(Enter the list of elements:\n ); for (i=0;I<no_elements;i++) scanf (%d,&array[i]); for( i=0; i<no_elements; i++) for( j=0; j<no_elements; j++) if(array[i] > array [j]) { temp = array[i] array [i] = array [j] array[j] = temp; }
# include <stdio.h> int main (void) {int a [MAX], n, i, k, temp; printf (Size of the array : ); scanf (%d, &n); printf (Elements of the array:\n); for (k = 0 ; k < n ; k++) scanf (%d, &a[k]); for(k = 1 ; k < n ; k++) { temp = a[k]; for(I = k-1 ; i >= 0&&temp < a[i] ; i - ) a [i+1] = a [ i ]; a[ i+1 ] = temp;}
Insertion Sort contd. The loop performs the insertion sort The elements are inserted at appropriate places in the ascending order printf (The sorted list is :\n) for (k = 0 ; k< n ; k++) printf( \n%d, a[k]); }
arr[0] arr[1]
Rule: all but leftmost dimension must be specified Compiler can compute leftmost dimension OK to specify leftmost dimension as well
Program to add two matrices # include <studio.h> int main (void) { int sMatrix [3] [3] = {{1,2,3}, {4,5,6}, (7,8,8}}; int bMatrix{[3][3] = {{4,5,6}, {3,2,1} (9,8,7}}; int cMatrix[3][3]; int, j; for ( i= 0; I < 3; i++ ) for (j = 0; j <3; J++) cMatrix[i] [j] =aMatrix [i] [j] + bMatrix [i] [j];
add two matrices contd. printf (ADDED MATRIX\n); for ( i = 0; i < 3; I++ ) { for (j = 0; j < 3; j++ ) printf( %d , cMatrix [i] [j]); printf (/n); }} The output of the program will be ADDED MATRIX 5 7 9 7 7 7 16 16 16
Exercises
Question Write a program to display the reverse a string. Write a program to concatenate a string to the end of another string
Strings
String
The most common array is the string, which is simply an one-dimensional array of characters terminated by a null. The End-of-String Sentinel (delimiter) #define MAXWORD 100 \0.
int main(void){ char w[MAXWORD]; w[0] = A; w[1] = \0; /*.*/
When declaring a character array that will hold a string, you need to declare it to be one character longer than the largest string that it will hold. WHY?
//to declare an array str that can hold a //10 characters string char str[11];
General form: char array_name[size] = string; char str[9] = I like C; char str[9] = {'I', ' ', 'l', 'i', 'k', 'e',' ', 'C', '\0'}; char *p = I like C;
String Initialization
The format %s is used for a string. scanf(%s, w); //if w is a string var printf(%s, w); a and a are very different. a a a character constant a array of characters with two elements.
String-Handling Functions
Standard header <string.h> strcpy(s1, s2) Copies s2 into s1 strcat(s1, s2) Concatenates s2 onto the end of s1. strlen(s1) Returns the length of s1 strcmp(s1, s2) Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2
strchr(s1, ch)
strstr(s1, s2)
#include <stdio.h>
printf("lengths: %d %d\n", strlen(s1), strlen(s2)); if(!strcmp(s1, s2)) printf("The strings are equal\n");
e is in hello
found hi strcpy(s1, "This is a test.\n"); printf(s1); if(strchr("hello", 'e')) printf("e is in hello\n"); if(strstr("hi there", "hi")) printf("found hi"); return 0; }
/* Allocate space for a string dynamically, request user input, and then print the string backwards. */ #include <stdlib.h> #include <stdio.h> #include <string.h> int main(void) { char *s; int t; s = malloc(80); if(!s) { printf(''Memory request failed.\n"); exit (1); } gets(s); for(t=strlen(s)-2; t>=0; t--) putchar(s[t]); free(s); return 0; }
STORAGE CLASSES
Auto Variables
The storage class auto can only be used in a block: it cannot be used at the global level.
1) Spatial Limitation(scope): The auto variable is limited to the block in which it is defined and its sub-blocks. LOCAL.
2) Temporal Limitation(extent): Are alive only when the block in which they are defined is running. Variable does not exist before block execution, when block terminates it dies(mortal).
Impact of Auto
Auto is the default SC for local vars because it makes the most efficient use of memory. Good programmers use Auto when ever possible because their lifetime is brief and their scope is limited to one function. They provide an effective way to isolate the actions of each program unit from the others.
Most common of the four storage classes. Variables declared within function bodies are auto by default. Thus auto is rarely explicitly specified. auto int a,b,c; auto float f;
auto
Unintentional interference between functions is minimized and, making it much easier to debug large programs.
Constant allocation and deallocation of auto vars does add some overhead to the the execution time, but since is done quite efficiently, the time wasted is minimal and the advantages of the added modularity are great.
When a block is entered, the system allocates memory for the auto variables. LOCAL i.e., Those declared in the block.
When Block is exited the variables are released and their values lost. IF re-enter the Block? _________ Memory is reallocated.
Primary purpose is to make variables visible to other compilation units. Must be defined in the global area of a program, that is outside of any block. All global variables( i.e., those defined outside any function) are EXTERN by default.
Extern
Extern Characteristics
Spatial Limitation(global): It is visible from its definition to the end of the program. It can be referred to and changed by all blocks that come after it as well as by other programs that are aware of its existence. Temporal Limitation(Immortal): The whole life of the program. From the time of its allocation till the end of the program.
extern (cont.)
Variables declared outside of a function have extern storage class by default. i.e., even if dont use keyword extern. Extern Vars are initialized to 0 automatically.
Typically, the compiler has only a few such registers available. Many are required for system use & cant be allocated otherwise: * Base Address of program * Return Address after program execution ends, * Instruction register, program counter, etc..
It is an attempt to improve execution speed. Most frequently accessed variable loop control variable or function parameters. register int i ; for (i = d, i <LIMIT, ++i){ }
Locally defined Static variables are one of the truly significant features of the C language. 1) Allow a Local variable to retain its previous value when a block is re-entered. (Not the case with Auto) 2) In other languages, these variables must be declared globally, which reduces the benefits of data hiding and isolation. 3) The variable will be automatically initialized to 0 when allocated.
Void f(void) { static int cnt = 0; ++ cnt; if (cnt % 2 == 0) . . . . . . else . . . . . } * 1st Time Function Invoked cnt is set to 0. * Upon EXIT cnt NOT cleared from memory * Next invocation ,retains previous value.
To prevent a global variable from being exported to the LINKER for reference by other compilation units, it can be declared static.
Restricted in scope to the remainder of the file in which they are defined. Not known to other files(compilation units). void f(void) { /* v not available here */ } static int v; void g(void) } /* v can be used here */ }
A Function can be Static: The scope of the function is limited to this file only(privacy concern). Is known throughout the entire file.
void f(int a) { .. } static int g(void) { .. }
Default Initialization
Extern & Static vars are initialized to 0 by the system. Auto & Register are usually not initialized by system. Start will garbage.
Type Qualifiers
Two type qualifiers: const volatile They are used in declarations and must be coded after the storage class but precede the type names that they qualify. static const int k = 3;
const
Variables of type const may not be changed by your program. The compiler is free to place variables of this type into read-only memory (ROM). const int a=10; const int a=7; const int a=7; int *p=&a; //wrong
A definition causes a compiler to set aside memory at compile time (every variable definition is a declaration) - not always the reverse.
e.g. when you introduce a variable outside of any function definition (global variable), you both declare and define the variable, because you have: a) informed the compiler about the variables type. b) caused the compiler to set aside memory for the variable at compile time.
When you introduce a variable inside a function definition(local), you only declare that variable, because the compiler does not set aside memory for such variable at compile time [memory in stack frame]. Functions are both declared & defined
Because: a) must specify return type. b) compiler sets aside memory functions at compile time.
for
Exercise
Q 1: Differentiate between external and local static variables.
Q 2: Explain the utility and requirement of declaring a variable external. as
Lecture 10-13
Structured Programming
Structured programming is a problem-solving strategy and a programming methodology.
The construction of a program should embody topdown design of the overall problem into finite subtasks.
Each subtask can be coded directly as a function. These functions can be used in main to solve the overall problem.
Functions are the building blocks of C and the place where all program activity occurs. Function topics include:
Function types Function variables Function arguments Function scopes Return values Function prototypes Recursion
Functions
General syntax: ret-type function-name (parameter list) { body of the function return (expression) } A function may return any type of data except an array. The parameters receive the values of the arguments when the function is called.
VOID
Not Return
a Value.
No Received
Values.
Variables
A variable is a named location in memory that is used to hold a value that can be modified by the program.
All variables must be declared before they can be used.
Local variable
Declared inside a function. Can be used only by statements that are inside the block in which the variables are declared. A local variable is created upon entry into its block and destroyed upon exit.
void func1(void) { int x; x = 10; } void func2(void) { int x; x = -199; }
void f(void) { int t; scanf("%d", &t); if(t==l) { char s[80]; /* this is created only upon entry into this block */ /* do something . . . */ } /* s not known here */ }
if(x == 10) { int x; /* this masks the outer x */ x = 99; printf("Inner x: %d\n", x); 99 }
printf("Outer x: %d\n", x); 10 return 0;
The value will be assigned to the variable each time the block of code in which it is declared is entered.
#include <stdio.h> void f(void); int main(void) { int i; for(i=0; i<10; i++) f(); return 0; } void f(void) { int j = 10; printf("%d ", j); j++; /* this line has no lasting effect */ }
Global Variables
They are known throughout the program in which they are defined. They will hold their value throughout the program execution. They are declared outside of any function Storage for global variables is in a fixed region and not the run-time stack.
#include <stdio.h>
void func1(void) { int temp; temp = count; func2(); printf("count is %d", count); }
int main(void) { void func2(void) count = 100; { func1(); int count; /* LOCAL */ printf("count is %d", count); for(count=l; count<10; count++) return 0; putchar('.'); } printf("count is %d", count); }
General form:
Function Parameters
All function parameters must be declared individually, each including both the type and name. void f(int i, int k, int j) /* correct */ void f(int i, k, float j) /* wrong */ Parameters behave like any other local variable.
Variables that are defined within a function are local variables. Such variables are freed from memory when their function completes execution.
Therefore, a local variable cannot hold its value between function calls. A global variable has extern storage class. We will see the impact of this later.
The formal parameters to a function also fall within the function's scope.
A parameter is known throughout the entire function. A parameter comes into existence when the function is called and is destroyed when the function is exited,( I.e., the Extent of the variable).
Call by Value
* When an Argument (variable, constant, or expression) is passed to a matching parameter (declared in Function Heading), A Copy of the Argument is made and is passed to the parameter.
* Changes made to the parameter have no effect on the argument. i.e., the parameter is implemented as a local variable which is initialized to the value passed from the Argument.
It is often convenient to have functions modify the values of the variables referred to in the Argument list. The address of an argument is copied into the parameter. Inside the subroutine, the address is used to access the actual argument used in the call. To effect call-by-reference we must use pointers in the Argument list & pass addresses of variables
Call by Reference
int main(void) { int t=10; printf("%d %d", sqr(t), t); return 0; } int sqr(int t) { t = t*t; return t; }
Placement of Functions: Before the compiler sees a call to a function it wants to know the Number and Type of its Parameters and the type of the Return Value of the Function. Two methods of doing so:
1. Place Function Before main function 2. Provide Function Prototype Before the call.
#include <stdio.h>
Before Main
Function Prototypes
In C - A Function call can appear Before the function is Defined (i.e., code of function): * The called function can be defined later in the same file. * The called function can be in another file.
/* This function returns the average of 3 exam scores which are passed call-by-value. */ double average(int exam1, int exam2, int exam3) { double testavg; testavg = (exam1 + exam2 + exam3)/ 3; return testavg;
}
The value of expression will become the return value of the function.
You can use as many return statements as you like within a function. However, the function will stop executing as soon as it encounters the first return.
/* Return 1 if c is part of string s; 0 otherwise. */ int is_in(char *s, char c) { while (*s) if(*s==c) return 1; else s++; return 0; {
Rules
The } that ends a function also causes the function to return. It is the same as a return without any specified value. If this occurs within a non-void function, then the return value of the function is undefined. A function declared as void cannot contain a return statement that specifies a value.
x = power(y);
Programmers frequently use exit when a mandatory condition for program execution is not satisfied. #include <stdlib.h> int main(void) { if(!virtual_graphics()) exit(1); play(); ... }
Exercise
Fill in the blanks The region where a variable name can be used is called the _______ of the variable. The variables declared inside a function or blocks have ______ scope. The three kinds of score are ____, _______ and ________. ________ and _______ variables have block scope by default. Auto variable cannot be _______ variables. Functions have _________ scope. Functions have _______ scope. Labels have _____ scope. Variable declared outside a block have _______ scope. Function declaration should be done ______ a function call.
Function scope can be told as a form of block scope. Allocated memory in a block is automatically released before the block ends. Variables with the same name in different block use the same memory locations. Block variables can be global variables also. File scope variables can be accessed by all functions in the file. File scope variables can be local variables also. It is possible to jump out of functions using labels. Using global variables allows sharing of data between functions. Using global variables increased the structural organization of a program. It is must to declare functions before they are used.
Exercise contd.. Functions cannot be considered as a source for reusability of code. Function prototype and function definition should match in the function name, the return value, the number and type of parameters. Arguments are mandatory in any function. The arguments passed to a function are mapped to the function prototype. A function can take no arguments also. Functions can take no arguments also. Parameters are values passed to a function and arguments are the variable that received the values.
Q 1: Write a function int power(int x, int n) to return xn. Q 2: Write a function int sum(int x, int n) which returns the sum of the following series: 2x + 4x + 6x + _ _ _ _ _ _ _ _ _ n terms Q 3: Write a function to return the factorial of a number. Q 4: Write a function, int sum(int x, int n) to return the sum of the following series : 2 3 x x x + ____ + ______ + _ _ _ _ _ _ n terms 2! 3! Q 5: Write a function int isPrime(int n) that returns 1 if its argument is a prime number, else returns 0.
Q 6: Write a function int arrSum(int arr[], int num) that takes two arguments: an integer array and the number of elements in the array. Hence the function returns as its result, the sum of the elements in the array. Q 7: What is the output : void f(int x[], int y); main() { int a[5], b, i; for(i = 0; i < 5; i++) a[i] = 2 * i; b = 15; f(a, b); for(i = 0; i < 5; i++) printf("%d\n", a[i]); printf("%d", b); } void f(int x[], int y) { int i; for(i = 0; i < 5; i++) x[i] += 2; y += 2; }
RECURSION
Recursion is the ability of a C function to call itself. Recursion is capable of defining an object in terms of a simpler case of itself. Recursion is a function, which keeps on calling itself. So, when will the function stop? There should be if condition upon which recursion stops.
Recursion
A function calls itself (circular definition).
/* non-recursive */ int fact(int n) { int t, answer; answer = 1; for(t=1; t<=n; t++) answer=answer*t; return answer; } } /* recursive */ int factr(int n) { int answer; if(n==l) return 1; /* recursive call */ answer = factr(n-l)*n; return answer ;
Recursion exercise
Fill in the Blanks _________ is the ability of a C program to call itself. Recursive code works _____ than iterative code. The point at which the program stops recursion is called ____. ______ is an elegant way of solving towers of Hanoi. Disks of ______ dimensions are present in the towers Hanoi. Recursive code necessarily needs a _______. Quick sort algorithm terminates when ______. Quick sort was developed by ________. Quick sort divides the array into _____ using ______.
Exercise
Q 1: What is the advantage of using a Recursive Technique ? Q 2: What will be the output of the following : #include <stdio.h> main() { printf("hello"); main(); } Q 3: Write a recursive function, int sum(int n), that returns: 2 + 4 + 6 + _ _ _ _ + 2n Q 4: Write a recursive function to print the binary equivalent of an integer.
Pointers
They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such as binary trees and linked lists.
Why Pointers
A pointer is the memory address of an object. A pointer variable is a variable that is specifically declared to hold a pointer to an object of its specified type.
This address is the location of another object (typically another variable) in memory.
. . .
Pointer Declaration
General syntax: type *name; int *m; //The variable m can hold a //pointer to type int. char *ch;
int count, *y, q;
&
*
Both & and * have a higher precedence than all other arithmetic operators except the unary minus, with which they share equal precedence.
& Operator
The & is a unary operator that returns the memory address of its operand. & the address of
m = &count; m receives the address of count. m count
100
* Operator
* is the complement of &. It is a unary operator that returns the value located at the address that follows. * at address
q = *m; q receives the value at address m.
#include <stdio.h> int main(void) { int target, source=10; Put the int *m; value 10 m = &source; into a target = *m; variable called target. printf("%d", target);
return 0;
}
Pointer Assignments
You can use a pointer variable on the right-hand side of an assignment statement to assign its value to another pointer.
When both pointers are the same type, the situation is straightforward.
#include <stdio.h> int main(void) { int x = 99; int *p1, *p2; p1 = &x; p2 = p1; printf("%p %p", p1, p2); printf(''%d %d\n", *p1, *p2); return 0; }
Illustrates Distinction between a pointer var value & a Dereferenced var. main( ) { int i = 777, *p = &i; printf (value of i:%d\n, *p); printf (Addr of i:%u or %p\n, p, p); } Output Value of i: 777 Address of i: 234880259 or dfffcfc
u - (unsigned Dec integer) p - (whatever way is Default for system) - Here is Hex.
Example 1
int i = 1, *j, *k; Assume addresses of i, j, k are respectively Byte addresses 10, 20, 30
1 i:10 1. j = &i; int var 1 i:10 Pointer var 10 j:20 Pointer var ? k:30 ? j:20 ? k:30
2. *j = 2;
1 2 10 ?
i:10
j:20
k:30
* has higher precedence than +. Assigns to i the contents of the location pointed to by j, incremented by 1.
4. k = &i;
3 10 10
i:10
j:20
k:30
42 53
42 53
Example 3 int *p1, v1; v1 = 0; p1 = &v1; int a=8, b=9; *p1 = 42; int *p1, *p2; v1? p1? *p1? p1 = &a;
p2 = &b; p1 = p2; vs. *p1 = *p2;
p1
p2
p1
p2 after p1 p2
8 9
9 9
Example 4
# include <stdio.h> main( ) { int j, i, *intptr; scanf(%d%d, &i, &,j); intptr = i > j ? &i:&j; printf(%d\n, *intptr); } Address of the larger var is stored in ? : then the larger number is output.
Example 5
int a=3,b=7,*p; 3 p = &b; 7
a
*p=2**pa;
11
Pointer Initialization
int i, *p = &i;
int *p = &i, i;
correct
sequence wrong.
p = &i;
p = 0;
p points to i
Null is usually defined as 0. Pointer constant points nowhere.
p = NULL;
i:10
p:50
1) p = i + 7;
ILLEGAL
The only integer value that can be assigned to a pointer variable directly is the special value 0 (NULL).
2 3 10
i:10
p:5
3) r = &x;
Illegal
Why?
x is a double variable r is pointer to int.
i:10 3 p
j 5 q
1. 2. 3. 4. 5
5) *(r = &j) *= *p 4 2 1 5 3 j 5 r i
1. &j - Address of j 1 2. r = 1 r points to j 3. *p contents of thing pointed to by p i.e., 3 4. *( ) Location pointed to by r, i.e., j.
5. *= *r *= *p; *r = *r * *p;
Pointer Arithmetic
int *v=(int *)100; Byte Address. 100 102 104 106 108 v v+1 v+2 v+3 v+4
i
i+1
i+2
Cannot multiply or divide pointers. Cannot add two pointers. Cannot add or subtract type float or double to or from pointers.
Call by Reference
Passing a ADDRESS of the argument to a formal parameter which is a POINTER of the same type as the argument.
Code within the function can change the value of the argument passed to the function.
Steps
1) Declare a function parameter to be a pointer. 2) Pass an address as an argument when the function is called. 3) Use the dereferenced pointer in the function body to reference the argument in the calling function.
#include <stdio.h> void swap(int *x, int *y); int main (void) { int i=10, j=20; printf("i and j before swapping: %d %d\n", i, j); swap(&i, &j); /* pass the addresses of i and j */ printf("i and j after swapping: %d %d\n", i, j);
return 0;
}
{
int temp;
temp=*x; /* save the value at address x */ *x =*y; /* put y into x */ *y=temp; /* put x into y */ }
Exercise
Fill in the blanks _________gives C the power to deal with machine architecture. _______ gets the value stored by location pointed by a pointer. If int *ptr = &temp;, then ptr = ____________. NULL is defined in _________. Address of different data types assigned to pointers of different data types give rise to ________ errors. If int a = 0, b = 1; int *pl = &a, *ps = &b; *p1 = p1+p2; *p = ________(taking &a = 1000 and &b =20). 7. float a =1.5, *ptr = &a; ptr = (int) (ptr + a); thus p = _______ (taking &p = 100).
Exercise Contd
True / False 1. Pointers hold address of memory locations. 2. & is called the indirection operator. 3. p = * (&p) 4. p = &(*p) 5. Addition of pointers is illegal. 6. We can apply bit operations on pointers. 7. NULL points to nothing. 8. (ptr1-ptr2) = (ptr1+ptr2)/size of object pointed by ptr1. (given ptr1 and ptr2 point to elements of the same array. 9. Pointers of the same type can be compared. 10. Pointers cannot be compared for equality at any time.
Exercise Contd
Q: Write a function, Fact(int i, int *j), to find the factorial of an integer, i, and store it in *j.
Q : Write a function int LetterCnt(char *p) which returns count of all alphabets in a character string. Q: Write a function using pointers to copy a string to another string.
Q : Write a function using pointers that appends one string to another.
Structures
Structures
A structure is a collection of variables referenced under one name, providing a convenient means of keeping related information together.
It allows us to organize related data of different types in one structure.
Structure Declaration
A structure declaration forms a template that can be used to create structure objects (instances of a structure).
The variables that make up the structure are called members.
General Form
struct tag { type member-name; type member-name; type member-name; . . . } structure-variable(s);
keyword structure tag name struct addr { char name[30]; char street[40]; char city[20]; char state[3]; unsigned long int zip; }; Terminated by a semicolon
No variable has actually been created.
Name
Street City State
30 bytes
40 bytes 20 bytes 3 bytes
You can declare one or more objects when declare a struct type
struct addr { char name[30]; char street[40]; char city[20]; char state[3]; unsigned long int zip; } addr_info, binfo, cinfo;
Initialization of Structures
All, Extern and Static Variables including
e.g., addr_info.zip = 12345; printf("%lu", addr_info.zip); gets(addr_info.name); for(t=0; addr_info.name[t]; ++t) putchar( addr_info.name[t] );
Structure Assignments
#include <stdio.h> int main(void) { struct { int a; Do not need to assign int b; the value of each } x, y; member separately x.a = 10; y = x; /* assign one structure to another */ printf("%d", y.a); return 0; }
Array of Structures
WHY?
What does an array of structures allow us to do that is not possible with any other single structure?
Arrays of Structures
To declare an array of structures, you must first define a structure and then declare an array variable of that type. struct addr addr_list[100];
Passing Structure Members to Functions When you pass a member of a structure to a function, you are passing the value of that member to the function. It is irrelevant that the value is obtained from a member of a structure.
struct friend { char x; int y; float z; char s[10]; } mike;
func(mike.x); /* passes character value of x func2(mike.y); /* passes integer value of y func3(mike.z); /* passes float value of z func4(mike.s); /* passes address of string s func(mike.s[2]); /* passes character value of s[2]
*/ */ */ */ */
func(&mike.x); /* passes address of character x */ func2(&mike.y); /* passes address of integer y */ func3(&mike.z); /* passes address of float z */ func4(mike.s); /* passes address of string s */ func(&mike.s[2]);/* passes address of character s[2] */
parm);
arg;
must match
parm)
In Header File:
cl_info.h
#define CLASS_SIZE 100 struct student { char *last_name; int student_id; char grade; }; In Program File : #include cl_info.h MAIN( ) { struct student temp, class [CLASS_SIZE]; .. } e.g.: To count the number of failing students in a given Class.
Structure Pointers
When a pointer to a structure is passed to a function, only the address of the structure is pushed on the stack. This makes for very fast function calls. Passing a pointer makes it possible for the function to modify the contents of the structure used as the argument via call-byreference.
To create linked lists and other dynamic data structures that rely on dynamic allocation.
p = &person;
struct student
temp, *p = &temp;
Expression
Equivalent
(*p).student_id 590017 Parenthesis are necessary (dot) has higher priority than *
y.a[3][7]
Using sizeof to Ensure Portability struct s { Type Size in Bytes char ch; char 1 int i; int 4 double f; double 8 } s_var;
sizeof(s_var) is 13 (8+4+1).
typedef
You can define new data type names by using the keyword typedef
You are not actually creating a new data type. You define a new name for an existing type.
The primary advantage of the type definition is that it allows you to replace a complex name, such as a pointer declaration, with a mnemonic that makes the program easier to read and follow.
General Form:
E.g.,
STRING StrPtrAry[20];
STUDENT
pupil;
Exercise
Q 1: How does an array differ from structure ? Q 2: What is a structure tag and what is its purpose ? Q 3: Define a structure which stores the name of a student, his roll number, and marks in three subjects. There are 10 students. Write a program to print roll number and name of student who gets the maximum and the one who gets the minimum marks. Also display the Average marks of each student. Q 4: Write a function to swap two dates using a structure. Use this function to swap an array of dates.
File handling
File accessing Function
Classes of Files There are two broad classes of files: Text Files: All the data are stored as characters which must be converted to internal formats when entered into memory. Text files are organized around lines which end with a new line(|n).
Binary Files: Store data in internal computer formats, such as integer and floating-pt numbers. Take less time to I/O because no format conversion is necessary.
Files are stored on auxiliary or secondary storage devices. Two most common are disk and tape. A buffer is a temporary storage area which holds data while they are being transferred to or from memory. Its primary purpose is to synchronize the physical devices to your program needs(e.g., more data can be input at one time then your program can use. The buffer holds extra data until you are ready for it).
These buffering activities are taken care of by software know as device drivers or access methods, which are provided by the supplier of the Operating System you are using.
The term file table implies that several things are stored. It contains ALL the info needed to locate your file wherever it is stored outside of the computer. It also contains info such as the file name, the location of its file buffer, and the current state of the file. We define a file table with the standard FILE type. There will be a file table for each file that our program will access.
Each stream that is associated with a file has a file control structure of type FILE.
The file pointers(stdin, stdout, stderri.e., Tables) are automatically opened when the program starts. File tables are created that POINT to these file streams.
stderr
Connected to the keyboard Standard output Connected file to the screen Standard error file Connected to the screen
fopen( ) Opens a file Commonly fclose( ) Closes a file used C fileputc( ) Writes a char. to a file fputc( ) Same as putc( ) system getc( ) Reads a character from a file functions fgetc( ) Same as getc( ) fgets( ) Reads a string from a file fputs( ) Writes a string to a file fseek( ) Seeks to a specified byte in a file ftell( ) Returns the current file position fprintf( ) Is to a file what printf( ) is to the console fscanf( ) Is to a file what scanf( ) is to the console feof( ) Returns true if end-of-file is reached rewind( ) Resets the file position indicator to the begin of the file remove( ) Erases a file Fflush() Flushes a file
FILE *fp;
The fopen( ) function opens a stream for use and links a file with that stream. Then it returns the file pointer associated with that file. General form:
Opening a File
filename is a pointer to a string of characters that make up a valid filename and may include a path specification.
mode determines how the file will be opened. fopen( ) function returns a file pointer which should not be altered by your code. If an error occurs when it is trying to open the file, fopen( ) returns a null pointer.
Legal Mode Meaning r Open a text file for reading values for w Create a text file for writing Mode a Append to a text filer b Open a binary file for reading wb Create a binary file for writing ab Append to a binary filer r+ Open a text file for read/write w+ Create a text file for read/write a+ Append or create a text file for read/write r+b Open a binary file for read/write w+b Create a binary file for read/write a+b Append or create a binary file for read/write
FILE *fp; if ((fp = fopen("test","w"))==NULL) { printf(''Cannot open file.\n"); exit(1); } The number of files that may be open at any one time is specified by FOPEN_MAX. This value will be at least 8. If, when opening a file for read-only operations, the file does not exist ,fopen ( ) will fail. When opening a file using append mode, if the file does not exist, it will be created.
When a file is opened for append: - All new data written to the file will be added to the end of the file. - The original contents will remain unchanged. When a file is opened for writing: - If the file does not exist, it will be created. - If it does exist, the contents of the original file will be destroyed, and a new file will be created.
- If the file already exists, opening it with w+ destroys its contents; opening it with r+ does not.
Closing a File
General form:
fclose( ) closes a stream that was opened by a call to fopen( ). It writes any data still remaining in the disk buffer to the file and does a formal operating-system-level close on the file.
Failure to close a stream invites all kinds of trouble, including :lost data, destroyed files, and possible intermittent errors in your program.
It also frees the file control block associated with the stream, making it available for reuse.
int putc(int ch, FILE *fp); Returns the character written if successful. Otherwise, returns EOF.
Reading a Character
getc( ) and fgetc( ) General form: int getc(FILE *fp); Returns EOF when the end of the file has been reached.
do { ch = getc(fp); } while(ch!=EOF);
/* KTOD: A key to disk program. */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { KTOD TEST FILE *fp; Reads characters from the keyboard and writes them to a char ch; if(argc!=2) { printf(''You forgot to enter the filename.\n");
disk file until the user types a dollar sign.
exit(1); }
feof( )
General form: int feof(FILE *fp); Returns true if the end of the file has been reached; otherwise, returns zero.
while(!feof(fp)) ch = getc(fp);
fgets( )
General form:
char *fgets(char *str, int length, FILE *fp); It reads a string from the specified stream until either a newline character is read or length1 characters have been read.
If a newline is read, it will be part of the string (unlike the gets( ) function).
rewind( )
General Format: void rewind(FILE *fp);
Although it is most commonly used with tape files, it can be used with disk as well. It simply sets the file position indicator to the beginning of the file.
A common use of REWIND is to change a work file from a write state to a read state. Often it is necessary to place data in a file temporarily for later processing. When all the data have been written and you are ready to begin reading, you rewind the file and simply start reading.
You must open the file in read/write mode.
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str[80]; FILE *fp; if((fp = fopen("TEST", "w+"))==NULL) { printf("Cannot open file.\n"); exit(1); }
do { printf("Enter a string (CR to quit):\n"); gets(str); strcat(str, "\n"); /* add a newline */ fputs(str, fp); } while(*str!='\n'); /* now, read and display the file */ rewind(fp); /* reset to start of file */ while(!feof(fp)) { fgets(str, 79, fp); printf(str); } return 0;
}
Erasing Files
General form:
int remove(const char *filename); It returns zero if successful. Otherwise, it returns a nonzero value.
#include <stdio.h> #include <stdlib.h> #include <ctype.h> int main(int argc, char *argv[]){ char str[80]; if(argc!=2) { printf(''usage: erase <filename>\n"); exit(1); }
#include <stdio.h> #include <conio.h> #include <stdlib.h> int main(void) { FILE *fp; char s[80]; int t;
if((fp=fopen("test", "w")) == NULL) { printf(''Cannot open file.\n"); exit(1); }
printf("Enter a string and a number: "); fscanf(stdin, "%s%d", s, &t); /* read from keyboard */ fprintf(fp, "%s %d", s, t); /* write to file */ fclose(fp); if((fp=fopen("test","r")) == NULL) { printf("Cannot open file.\n"); exit(1); } fscanf(fp, "%s%d", s, &t); /* read from file */ fprintf(stdout, "%s %d", s, t); /* print on screen */ return 0; }
Questions
Suppose that the file data.dat is ABCDEFGHIJKLMNOPQRSTUVWXYZ What is printed ? #include <stidio.h> main() { char 1; FILE *fp; fp = fopen (data.dat, rb); 1 = getc (fp); printf(%c\n, 1) fseek (fp, OL, 2); if (( 1 = getc(f[)) = = EOF) printf( EOF \n); else pintf(%c\n, 1); fseek(fp, -5L, 2); 1 = getc (fp); printf(%c, 1); }
LINKED LIST
LINKED LIST DATA STRUCTURE A Linked List is an ordered collection of data in which each element contains 2 parts: data and link.
The data part holds info fields and the link is used to chain the data together. It contains a pointer that identifies the in next node the list. A Pointer variable points to the first node (HEAD) in the list. Memory for each node is allocated dynamically.
Head
Data
Data
Data
Data
The Head ptr gives acess to the LINKED LIST which is a sequence of linked nodes.
Self-Referential Structures The node in a linked list are called selfreferential structures: Each instance of the structure contains a pointer member to another instance of the same type. This gives us the ability to create our linked list structure in which one instance of a node structure points to another instance of the node structure.
typedef struct nodetag { DATA data; struct nodetag *link; } NODE; A TYPE for EACH NODE
Primitive List Functions To work with a linked list we need some basic operations that manipulate the nodes. INSERT a Node: At the beginning. At the end. Anywhere in the list. DELETE a Node: At the beginning. At the end. Anywhere it is. SEARCH for a Find the location for node. above activities.