Computer Programming - Theory
(CSI101)
Course Instructor: Binanda Sengupta (Assistant Prof. @CSE)
Email:
[email protected] Webpage: https://people.iitism.ac.in/~binanda/
Lecture Plan
Introduction to Computer Programming
• What is a computer?
• What is computer programming?
• What is a pseudocode?
• What is a programming language?
• We will focus on C programming language only
C Programming Language
• C is a high-level language (which is understandable to human with strong
abstraction from the details of the computer)
• C is a procedural language
• C is a case-sensitive language
• C relies on “libraries” containing standard functions
• C is highly portable: C programs written for one computer can be run on
other computer with no modification
Basic Structure of a C Program
A Simple Program to Start with
#include <stdio.h> // Preprocessor directive to include
// standard I/O library
int main(){ // function “main” does not have any parameters
printf("Hello World!\n");/* “main” calls “printf” to print a sequence
of characters; \n is newline character */
return 0; /* optional – returns 0 to calling function;
implies normal termination */
}
Data Types
Data Types
A Simple Program with Integer Data Type
#include <stdio.h>
int main() {
int i, j, k;
i = 3;
j = 5;
k = i + j;
printf("Sum of %d and %d = %d.\n", i, j, k);
return 0;
}
Variables in C
• Names are unique that simply reference to memory locations, which can
hold values (data)
• Names formed by combining letters (both upper and lowercase), digits
(0—9) and underscore ( _ )
• Rules for naming are:
• The first character must be a letter (non-digit) including underscore ( _ )
• The blank or white space character is not permitted. Space, tab, newline characters
are "white-space characters“ - they serve the same purpose as the spaces between
words and lines on a printed page.
• Can be any length but implementation dependent
• Reserved words/keywords cannot be used
Variables in C
Correct Wrong
secondName 2ndName /* starts with a digit */
_addNumber %calculateSum /* contains invalid
character */
charAndNum char /* reserved word */
annual_rate annual rate /* contains a space */
stage4mark my\nName /* contains new line
character, \n */
Variable Declaration in C
• A variable has two properties in syntax: name — a unique identifier & type
— what kind of value is stored
• Value may change during the program execution
• Every variable, stored in the computer’s memory, has a name, a value and
a type
• Declaration is different from initialization (can be done simultaneously)
Variable Declaration in C
Correct Wrong Comment
int x, y, z; int 3a, 1, -p;
short number_one; short number+one;
long TypeofCar; long #number
unsigned int positive_number; …
char Title;
float commission, yield = 4.52;
int my_data = 4;
char the_initial = 'M'; A char
Char studentName[20] = "Anita"; A string
Scope of Variables
• Automatic variables — local variables declared in a function (scope is within that
function only)
• Automatic variables — come into existence during function invocation, disappear after
function exit (no value retention across function calls)
• External variables — external to all functions (defined outside any function and scope
is global across all functions)
• External variables — must be declared in respective functions (keyword extern)
• External variables — definition (created and storage allocated); declaration (nature
stated, no storage allocation) — retain value
Constants in C
Symbolic constants – #define name replacement_text
Keywords/Reserved Words in C
• Reserved words in C – not available for re-definition
A Simple Program to Read from Standard Input
#include <stdio.h>
int main() {
int i, j, k;
printf("Enter the value of i: ");
scanf("%d", &i);
printf("Enter the value of j: ");
scanf("%d", &j);
k = i + j;
printf("Sum of %d and %d is %d.\n", i, j, k);
return 0;
}
Operators and Expressions
Arithmetic Operators
Relational and Logical Operators
• Relational Operators
>
>=
<
<=
==
!=
• Logical Operators
&&
||
Unary negation operator ! converts non-zero operand into 0, and zero operand into 1
Assignment Operators
Conditional Expressions
• Ternary operator “?:”
Bitwise Operators
Type Conversions
• Operators having two operands with different data types
• “Lower” type is promoted to “higher” type before operation proceeds
Type Conversions
• Explicit/forceful type conversion
• (type_name) expression (unary operation called a cast)
• sqrt function defined in <math.h> expects a double argument, but it may
produce garbage values otherwise
int n = 16; sqrt((double) n);
Operator Precedence and Associativity
• Precedence determines which operation is performed first in an expression with
more than one operators with different precedence
• Expression “10 + 20 * 30” is calculated as “10 + (20 * 30)”
• Associativity is used when two operators of same precedence appear in an
expression – can be either Left to Right (L2R) or Right to Left (R2L)
• * and / have same precedence and their associativity is Left to Right, so the expression “100 / 10 *
10” is treated as “(100 / 10) * 10”
• Associativity does not define
• The order in which operands of a single operator are evaluated
• The order in which arguments of a function are evaluated
Operator Precedence and Associativity
Control Flow
Brief Overview of Statements and Blocks
• Statement: An expression followed by a semicolon (‘;’)
• arr[10] = 30;
• k = i + j;
• Block: One or more statements grouped together into a compound
statement (surrounded by braces)
• if (a > b) {
c = a;
++c;
printf("c = %d\n", c);
} // no semicolon after the right brace ending the block
Decision and Branching
• if-else
• if-else if
• switch
if-else Statement
if-else Statement
Statements can be
replaced by blocks
if-else Statement
if-else Statement
else associated with the
closest previous else-less if
if-else if Construction
switch Statement
All values must
be different
switch Statement
char c = 'b';
switch (c) {
case 'a':
printf("Vowel\n");
case 'e':
printf("Vowel \n");
case 'i': What is the output?
printf("Vowel \n");
case 'o':
printf("Vowel \n");
case 'u':
printf("Vowel \n");
default:
printf("Not a Vowel \n");
}
switch Statement
char c = 'b';
switch (c) {
case 'a':
printf("Vowel\n");
case 'e':
printf("Vowel \n");
case 'i': What is the output?
printf("Vowel \n");
case 'o': "Not a Vowel"
printf("Vowel \n");
case 'u':
printf("Vowel \n");
default:
printf("Not a Vowel \n");
}
switch Statement
char c = 'a';
switch (c) {
case 'a':
printf("Vowel\n");
case 'e': Falls through all the subsequent cases
printf("Vowel \n");
case 'i':
printf("Vowel \n");
case 'o':
printf("Vowel \n");
case 'u':
printf("Vowel \n");
default:
printf("Not a Vowel \n");
}
switch Statement
char c = 'a';
switch (c) {
case 'a':
printf("Vowel\n");
case 'e': Falls through all the subsequent cases
printf("Vowel \n");
Output:
case 'i':
printf("Vowel \n");
Vowel
case 'o': Vowel
printf("Vowel \n"); Vowel
case 'u': Vowel
printf("Vowel \n"); Vowel
default: Not a Vowel
printf("Not a Vowel \n");
}
switch Statement
char c = 'b';
switch (c) {
case 'a': printf("Vowel\n");
break;
case 'e': printf("Vowel \n");
break;
case 'i': printf("Vowel \n");
break;
case 'o': printf("Vowel \n");
break used to avoid falling
break; through the subsequent cases
case 'u': printf("Vowel \n");
break;
default: printf("Not a Vowel \n");
break;
} // Outputs "Not a Vowel"
Loops
• while
• for
• do-while
while Loops
while Loops
do-while Loops
for Loops
for Loops
for Loops
for Loops
for Loops
for Loops
for Loops
Nested Loops
Nested Loops
Example: Matrix Multiplication
Example: Matrix Multiplication
break Statement
continue Statement
goto Statement and Labels
Tutorial
1. What is the output?
2. Which special symbol is permitted in an
identifier’s name?
3. What is the type name the reserved word
‘short’ for?
4. What is the output?
5. How to declare the main function with
command-line arguments?
6. Which of the following typecasting is
accepted by C language?
A - Widening conversions
B - Narrowing conversions
C - Widening & Narrowing conversions
D - None of the above
7. What is #include <stdio.h>?
A - Preprocessor directive
B - Definition directive
C - None of the above
8. What is the output?
A - Choice other than 1 and 2
B - Choice is 1
C - Choice is 2
D - Compilation error
9. What is the output?
A - Wed
B-3
C-2
D - Compilation error
10. What is the output?
11. What is the output?
A - 50
B - 51
C - 30
D - Compilation error
12. What is the output?
A-1
B-2
C-3
D - Compilation error
13. What is the output?
A-2
B-3
C - Compilation error
D - Runtime error
14. What is the output?
A - Compilation error
B - Runtime error
C – Hi. Hi again.
D – Hi again.
Arrays and String Handling
What Is an Array?
• Sequenced collection of similar data items/elements
• float employee_age[10];
• char employee_firstname_initial[10];
• Each item indexed (and accessed) uniquely
• printf("%c", employee_firstname_initial[2]);
• Contiguous memory allocation
Declaration of One-Dimensional Array
Initialization of One-Dimensional Array
Compile-Time Initialization
√
Run-Time Initialization
Declaration of Two-Dimensional Array
Initialization of Two-Dimensional Array
Memory Layout of Two-Dimensional Array
int matrix[2][3] = {1, 2, 3, 4, 5, 6};
Static Arrays
Strings
“Hello World!”
“ Hello World ! ”
Strings
“Hello World!”
“ Hello World ! ”
printf("Hello World!");
printf(" Hello World ! ");
Strings
“Hello World!”
“ Hello World ! ”
printf("Hello World!");
printf(" Hello World ! ");
““ Hello World! ””
How to print this string?
Strings
“Hello World!”
“ Hello World ! ”
printf("Hello World!");
printf(" Hello World ! ");
““ Hello World! ””
printf("\"Hello World!\"");
Declaration and Initialization of Strings
char str[20] = "IIT (ISM)";
char str[20] = {‘I’, ‘I’, ‘T’, ‘ ’, ‘(’, ‘I’, ‘S’, ‘M’, ‘)’, ‘\0’};
char str[] = "IIT (ISM)";
char str[] = {‘I’, ‘I’, ‘T’, ‘ ’, ‘(’, ‘I’, ‘S’, ‘M’, ‘)’, ‘\0’};
Declaration and Initialization of Strings
char str[20] = "IIT (ISM)";
char str[20] = {‘I’, ‘I’, ‘T’, ‘ ’, ‘(’, ‘I’, ‘S’, ‘M’, ‘)’, ‘\0’};
char str[] = "IIT (ISM)";
char str[] = {‘I’, ‘I’, ‘T’, ‘ ’, ‘(’, ‘I’, ‘S’, ‘M’, ‘)’, ‘\0’};
Difference between character arrays and strings?
Declaration and Initialization of Strings
char str[20];
str = "IIT (ISM)";
char str[20] = "IIT (ISM)";
char str_new[20];
str_new = str;
Reading and Writing Strings
char line[20];
scanf("%s", line); //whitespace and single ‘\0’
printf("%s", line);
gets(line); //similar to getchar()
puts(line); //similar to putchar()
Format Specifiers for Strings
char line[20];
scanf("%3s", line);
scanf("%[^\n]", line); //‘edit conversion code’ or ‘scanset’
// to read a line
printf("%10.3s", line);
printf("%*.*s", 10, 3, line);
Characters, Integers and Strings
Integer representation of characters
Characters can be displayed as integers
Arithmetic operations can be performed on characters
int a = 2*'a';
char c = '8'; int a = c – '0';
String-to-integer conversion: int x = atoi(str); //stdlib.h
ASCII (American Standard Code for Information
Interchange)
Invalid String Operations
str = "Hello World"; //invalid assignment
str1 = str2 + str3; //invalid concatenation
if (str1 == str2) … //invalid equality checking
String-Handling Functions
#include <string.h>
strcat() and Similar Functions
strcat() and Similar Functions
Is there anything
wrong here?
strcat() and Similar Functions
strncat(str1, str2, n);
Concatenates first (leftmost) n characters of str2 to str1
strcmp() and Similar Functions
strcmp(str1, str2);
Returns 0 if two strings are equal
Returns -1 if str1 is alphabetically above str2
Returns 1 if str2 is alphabetically above str1
strcmp() and Similar Functions
What is the output?
strcmp() and Similar Functions
What is the output?
strcmp() and Similar Functions
What is the output?
stricmp(str1, str2);
strcmp() and Similar Functions
strncmp(str1, str2, n);
Compares first (leftmost) n characters of str1 with str2
strcpy() and Similar Functions
strcpy(str1, str2);
Copies the content of str2 to str1
strcpy() and Similar Functions
strncpy(str1, str2, n);
Copies first (leftmost) n characters of str2 to str1
strlen() Function
strlen(str);
Returns the length (number of characters excluding ‘\0’) in str
Tutorial
1. What is the output?
2. What is the output?
3. Which option is correct?
4. Which option is correct?
5. Which option is correct?
6. Which option is correct?
7. What is the output?
8. What is the output?
Functions
What Are Functions?
• “Program modules” dedicated to perform specific tasks
• Function for printing a given number on the terminal
• Function for calculating the larger root of a given quadratic equation
What Are Functions?
• “Program modules” dedicated to perform specific tasks
• Function for printing a given number on the terminal
• Function for calculating the larger root of a given quadratic equation
• Library (in-built) functions and user-defined functions
• printf() and main()
What Are Functions?
• “Program modules” dedicated to perform specific tasks
• Function for printing a given number on the terminal
• Function for calculating the larger root of a given quadratic equation
• Library (in-built) functions and user-defined functions
• printf() and main()
• Usefulness
• Breaking into smaller components – useful for maintaining, testing and debugging
• Can be reused – called from several functions (calling/caller function and called
function)
• Abstract view of functionalities
Elements of User-Defined Functions
Elements of User-Defined Functions
Elements of User-Defined Functions
Formal and actual arguments/parameters
Elements of User-Defined Functions
Formal and actual arguments/parameters
Elements of User-Defined Functions
“int sum(int x, y)”?
Elements of User-Defined Functions
“int sum(int x, y)”?
Function Definition
Function Definition
When return_type is omitted, int is assumed
Function Definition
• return statement
• Transfers control immediately to the calling function with or without a
return value (can be anywhere in the called function)
• Without return, execution falls off the function end by reaching
closing right bracket
• return;
• return expression;
Function Definition
• return statement
• Transfers control immediately to the calling function with or without a
return value (can be anywhere in the called function)
• Without return, execution falls off the function end by reaching
closing right bracket
• return;
• return expression;
• Return value automatically cast to the return_type of the function
Function Calls
return value directly assigned
Function Calls
Function Declaration or Prototype
When return_type is omitted, int is assumed
Function Declaration or Prototype
• Parameter names are not necessary in function declaration, only their
types are required
• int sum(int, int);
• Parameter types and order should match that in function definition
• Global and local prototype declaration
Call by Value
Call by Value
What is the output when 10 and 5
are entered as values of x and y?
Call by Value
What is the output when 10 and 5
are entered as values of x and y?
Call by Value
Arguments are passed to a
function by value
❑ Data items are copied to the
function
❑ Changes made in the called
function are NOT reflected in
the calling function
Nested Functions
Nested Functions
Call stack in memory for functions
Passing Arrays to Functions
Recursion
Recursion
Factorial of a number
Recursion
Factorial of a number
Base case/condition:
x == 1
Recursion
Factorial of a number
What happens without
the base case?
Recursion
Fibonacci numbers
Recursion
Fibonacci numbers
Recursion
Fibonacci numbers
Storage Classes in C
Pointers
Address of Variable
• Address of a variable can be determined using ‘&’ operator (‘&’ is called
“address-of” operator)
• int xyz = 50;
50 can be accessed using xyz
or the value stored at &xyz (i.e., 1380)
• ‘&’ operator can be used only with a simple variable or an array element
• &xyz &123
• &a[1] &(x+y)
What Is a Pointer?
• A pointer is just a variable whose value is the address of another variable
var (i.e., the pointer variable stores the memory address of var)
• Content of var can be accessed using the pointer variable
• Pointer variables must be declared and initialized before being used
Pointer Declaration
data_type *pointer_name;
Example: int *ptr;
float *p;
double *q;
- Asterisk (*) designates ptr as a pointer variable
- ptr can be used to point to a variable of type int
Pointer Initialization
• After declaration, we can initialize the pointer to a valid address or we can
set the pointer to NULL (NULL pointer points nowhere)
int *ptr = NULL;
•
Pointer Initialization
• After declaration, we can initialize the pointer to a valid address or we can
set the pointer to NULL (NULL pointer points nowhere)
int *ptr = NULL;
•
Dereference or Indirection
‘*’ operator (“value-at” operator) can be used to access/modify the value
at corresponding address (it can be used with a pointer variable only)
Pointers and Arrays
Array name is a constant pointer to the first element of the array
Pointers and Arrays
Array name is a constant pointer to the first element of the array
What are the values of x and &x[0]?
Pointers and Arrays
Array name is a constant pointer to the first element of the array
x = &x[0] = 2500
Pointers and Arrays
Array name is a constant pointer to the first element of the array
x = &x[0] = 2500
Pointers and Arrays
Array name is a constant pointer to the first element of the array
x = &x[0] = 2500
int *p;
p = x; OR p = &x[0];
Pointers and Arrays
int *p; p = &x[0];
p = &x[0] = 2500
p+1 = &x[1] = 2504
p+2 = &x[2] = 2508
p+3 = &x[3] = 2512
p+4 = &x[4] = 2516
Pointers and Arrays
int *p; p = &x[0];
p = &x[0] = 2500 = x
p+1 = &x[1] = 2504 = x+1
p+2 = &x[2] = 2508 = x+2
p+3 = &x[3] = 2512 = x+3
p+4 = &x[4] = 2516 = x+4
Pointers and Arrays
int *p; p = &x[0];
p = &x[0] = 2500 = x Both (p+i) and (x+i) denote the
p+1 = &x[1] = 2504 = x+1 address of x[i]
p+2 = &x[2] = 2508 = x+2
p+3 = &x[3] = 2512 = x+3
p+4 = &x[4] = 2516 = x+4
Pointers and Arrays
int *p; p = &x[0];
p = &x[0] = 2500 = x Both (p+i) and (x+i) denote the
p+1 = &x[1] = 2504 = x+1 address of x[i]
p+2 = &x[2] = 2508 = x+2 Each of *(p+i), *(x+i) and p[i]
p+3 = &x[3] = 2512 = x+3 denotes the value of x[i]
p+4 = &x[4] = 2516 = x+4
Pointers and Arrays
int *p; p = &x[0];
p = &x[0] = 2500 = x Both (p+i) and (x+i) denote the
p+1 = &x[1] = 2504 = x+1 address of x[i]
p+2 = &x[2] = 2508 = x+2 Each of *(p+i), *(x+i) and p[i]
p+3 = &x[3] = 2512 = x+3 denotes the value of x[i]
p+4 = &x[4] = 2516 = x+4
Example: *p = 1
*(p+3) = 4
Pointers and Arrays
Pointers and Arrays
Pointers and Arrays
Pointers and Arrays
Pointer Arithmetic
Dereferenced pointers can be treated as ordinary variables
and arithmetic operations can be performed on them
Example:
int sum = (*ptr1) + (*ptr2);
int prod = (*ptr1) * (*ptr2);
*ptr1 = *ptr1 + 3;
int x = *ptr1 / *ptr2 + 7;
Pointer Arithmetic
Certain arithmetic operations can be performed on pointers
• Adding an integer to a pointer (e.g., ptr++, ptr = ptr + 5)
• Subtracting an integer from a pointer (e.g., ptr--, ptr = ptr - 3)
• If ptr1 and ptr2 are pointers to two elements of the same array, then
ptr2 - ptr1 denotes the number of elements between ptr1 and ptr2
Pointer Arithmetic
Certain arithmetic operations cannot be performed on pointers
Example:
ptr1 = ptr1 + ptr2;
ptr1 = ptr2 / 9;
ptr1 = ptr1 – ptr2 * 3;
Pointers as Arguments to Function
Data items in the calling function can be accessed by the called
function (through addresses) and modified
Recall:
Arguments are passed to a function by value
❑ Data items are copied to the function
❑ Changes made in the called function are NOT reflected
in the calling function
Pointers as Arguments to Function
Copies of addresses are passed to the called function
Pointers as Arguments to Function
Copies of addresses are passed to the called function
a = 5, b = 20 a = 20, b = 5
Pointers as Arguments to Function
Can a function “return” multiple values using pointers?
Pointers as Arguments to Function
Can a function “return” multiple values using pointers?
Pointers as Arguments to Function
Are there any differences among the following prototypes?
int func_name ( int A[], ... );
int func_name ( int A[100], ... );
int func_name ( int *A, ... );
Pointers as Arguments to Function
Are there any differences among the following prototypes?
int func_name ( int A[], ... );
int func_name ( int A[100], ... );
int func_name ( int *A, ... );
NO
Pointers as Arguments to Function
Are there any differences among the following prototypes?
int func_name ( int A[], ... );
int func_name ( int A[100], ... );
int func_name ( int *A, ... );
NO
A is an int pointer
A is a copy of the address passed to func_name
Pointers as Arguments to Function
Can a function
return a pointer?
Pointers as Arguments to Function
Can a function
return a pointer?
Pointers as Arguments to Function
Can a function
return a pointer?
Should a pointer to an
automatic variable be
returned from containsA?
Pointers as Arguments to Function
Can a function
return a pointer?
Should a pointer to an
automatic variable be
returned from containsA?
What about a pointer
to a static variable?
Dynamic Memory Allocation
Problem with static arrays: Size predetermined during
compile time
Dynamic Memory Allocation
Problem with static arrays: Size predetermined during
compile time
Dynamic memory allocation: Memory space required can be
specified during runtime
Dynamic Memory Allocation
Problem with static arrays: Size predetermined during
compile time
Dynamic memory allocation: Memory space required can be
specified during runtime
C supports dynamic memory allocation using library functions
malloc, calloc, realloc //heap memory; stdlib.h
Dynamic Memory Allocation: malloc()
Dynamic Memory Allocation: calloc()
Dynamic Memory Allocation: realloc()
Dynamic Memory Allocation
What happens when malloc(), calloc() or realloc() fails?
Dynamic Memory Allocation
What happens when malloc(), calloc() or realloc() fails?
It returns NULL
Dynamic Memory Allocation: free()
Dynamic Memory Allocation: free()
Dynamically allocated memory remains alive until freed (or program exits)
Dynamic Arrays Using Pointers
1-dimensional arrays
int A[20]; //static array
int *p;
p = (int *) malloc(20 * sizeof(int));
. . .
free(p);
Dynamic Arrays Using Pointers
2-dimensional arrays
Example: Fixed number of rows, variable number of columns
int A[3][20]; //static array
int *r[3]; //array of pointers
for (int i = 0; i < 3; i++)
r[i] = (int *) malloc(col_size * sizeof(int));
. . .
for (int i = 0; i < 3; i++)
free(r[i]);
Dynamic Arrays Using Pointers
2-dimensional arrays
Example: Fixed number of rows, variable number of columns
Dynamic Arrays Using Pointers
2-dimensional arrays
Given int A[10][20], which pointer matches A?
Is int *B[20] a candidate?
Dynamic Arrays Using Pointers
2-dimensional arrays
Given int A[10][20], which pointer matches A?
Is int *B[20] a candidate?
A pointer matching A should be a pointer to an array of 20 int variables
int *B[20] declares an array of 20 int pointers, not a pointer to an array
Dynamic Arrays Using Pointers
2-dimensional arrays
Tutorial
1. How to allocate and free memory for
?
2. How to allocate and free memory for
?
3. What is the output?
4. What is the output?
5. What is the output?
6. What is the output?
(A) Compiler Error
(B) Garbage Value 12
(C) Runtime Error
(D) H 12
7. What is the output?
8. What is the output?
(A) 23 23
(B) 23 123
(C) 23 Error
(D) Error 23
Structures and Unions
What Is a Structure?
A user-defined data type to represent a group of logically related data
items which may be of different types (unlike an array)
What Is a Structure?
A user-defined data type to represent a group of logically related data
items which may be of different types (unlike an array)
• employee
employee name (string)
employee number (integer)
age (integer)
salary (integer)
• complex number
real part (floating-point number)
imaginary part (floating-point number)
Structure Definition
Structure Definition
Structure Definition
Member name can be same as a variable defined outside
Structure Definition
Structure Variable Declaration
Structure Definition
Structure Variable Declaration
- No memory is allocated
- Defines a new data type only
Structure Definition
Structure Variable Declaration
- No memory is allocated
- Defines a new data type only
Structure Definition Structure Variable Declaration
Structure Variable Declaration
- a1, a2, a3 are variables of the type
struct student
- Memory is allocated for a1, a2, a3
- No memory is allocated
- Variable declaration is allowed
- Defines a new data type only
only after structure definition
Structure Definition Structure Variable Declaration
Structure Definition and Variable Declaration
Structure Definition and Variable Declaration
Structure Definition and Variable Declaration
Structure Definition and Variable Declaration
typedef Construct and Structures
typedef construct can be used to give new names to existing data
types
typedef int age_in_years; // age_in_years is a new name for int
typedef Construct and Structures
typedef construct can be used to give new names to existing data
types
typedef int age_in_years; // age_in_years is a new name for int
age_in_years age; /* variable age of type age_in_years
is declared */
age = 25;
typedef Construct and Structures
typedef construct can be used to give new names to existing data
types
typedef Construct and Structures
typedef construct can be used to give new names to existing data
types
typedef Construct and Structures
typedef Construct and Structures
Accessing and Assigning Structure Members
A structure member can be accessed individually using
〈structure-variable-name〉.〈member-name〉
Accessing and Assigning Structure Members
A structure member can be accessed individually using
〈structure-variable-name〉.〈member-name〉
Example:
Accessing and Assigning Structure Members
A structure member can be accessed individually using
〈structure-variable-name〉.〈member-name〉
Example:
struct point {float xcoord, float ycoord}; //Definition
struct point a = {2.5, 0}, b = {3.2, 0}; //Initialization
Accessing and Assigning Structure Members
A structure member can be accessed individually using
〈structure-variable-name〉.〈member-name〉
Example:
struct point {float xcoord, float ycoord}; //Definition struct point c = a;
struct point a = {2.5, 0}, b = {3.2, 0}; //Initialization
Accessing and Assigning Structure Members
A structure member can be accessed individually using
〈structure-variable-name〉.〈member-name〉
Example:
struct point {float xcoord, float ycoord}; //Definition struct point c = a;
struct point a = {2.5, 0}, b = {3.2, 0}; //Initialization if (c == a)
Accessing and Assigning Structure Members
Accessing and Assigning Structure Members
struct student {
char name[50];
float CGPA;
int height;
} s;
s = {"Amit Trivedi", 8.40, 165};
s = (struct student){"Amit Trivedi", 8.40, 165};
√
Size of a Structure
struct student { struct student {
char name[50]; char *name;
float CGPA; float CGPA;
int height; int height;
} s; } s;
sizeof(s)?
Size of a Structure
struct structure1 {
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2 {
int id1;
char name;
int id2;
char c;
float percentage;
};
Size of a Structure
struct structure1 {
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2 {
int id1;
char name;
int id2;
char c;
float percentage; Padding: If not collectively aligned with size
};
of the largest type
Size of a Structure
struct structure1 {
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2 {
int id1;
char name;
int id2;
char c;
float percentage; Structure size may differ for
};
same set of members
Size of a Structure
struct structure1 {
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2 {
int id1;
char name;
int id2;
char c;
What happens when c is short?
float percentage;
};
Size of a Structure
struct structure1 {
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2 {
int id1;
char name;
int id2;
char c;
What happens when c is short?
float percentage; Padding occurs after name in
}; structure1 (not after c)
Arrays of Structures
struct student {
char name[50];
float CGPA;
int height;
};
struct student STUDENT[120];
Arrays of Structures
struct student {
char name[50];
float CGPA;
int height;
};
struct student STUDENT[120];
What does STUDENT[12].CGPA denote?
Structure as a Member of another Structure
typedef struct {
double x, y;
} point;
typedef struct {
point A, B, C;
double area;
} triangle;
Structure as a Member of another Structure
typedef struct {
double x, y;
} point;
typedef struct {
point A, B, C;
double area;
} triangle;
triangle t;
t.A.x = 3.0;
Structure as a Member of another Structure
struct a contains struct a variables as members
(incomplete type)
struct a contains struct b, and struct b contains
struct a
Structure as a Member of another Structure
struct a contains struct a variables as members
(incomplete type)
struct a contains struct b, and struct b contains
struct a
struct a contains a pointer to struct a
typedef struct _student {
char name[50];
√
struct _student *next; // self-referencing pointer
} student;
Functions and Structures
Functions can take structures as
arguments, and they can return
structures also
Pointers to Structures
struct student {
char name[50];
float CGPA;
int height;
};
struct student *ptr;
Pointers to Structures
struct student {
char name[50];
float CGPA;
int height;
};
struct student *ptr;
When ptr points to a struct student variable var, its
members can be accessed using either (*ptr).member
or ptr->member (arrow operator)
Pointers to Structures
(*ptr).member or ptr->member
√
*ptr.member
Difference between ++ptr->member and (++ptr)->member?
Unions
In a union, space is allocated as the union of the space required by its members
(instead of sum of spaces as in structures)
Union is used when only one of the members is needed, but not known a priori
union u_val {
int ival;
float fval;
char cval;
};
union u_val u, *U;
u.ival = 3; //U->ival = 3;
Unions
Tutorial
1. What is the output?
2. What is the output?
3. What is the output?
File Management
What Is a File?
A named collection of data, typically stored in secondary storage (e.g., HDD)
Typical operations on files:
1. Open
2. Read
3. Write
4. Close
File is stored as a sequence of bytes which are logically contiguous (may not
be physically contiguous on disk)
File Types
1. Text files contain ASCII characters (printable characters with ASCII codes
32-127) only
Each line ends with a newline character
It can be read or written by any text editor (used to store source codes also)
Last byte of a file contains end-of-file (EOF) – marks the end of file
File Types
2. Binary files may contain non-ASCII characters
Image, audio, video, executable files
Created from a program only and contents can be read only by a program
File-size value checked to detect the end of file
File Handling in C
FILE * is used to represent a pointer to a file (defined in stdio.h)
Opening a File
fopen is used to open a file (returns NULL to indicate that it is unable
to open the file)
FILE *fptr;
char filename[ ]= "file.dat";
fptr = fopen(filename,"w");
if (fptr == NULL) {
printf("Error while creating file");
exit(1); //stdlib.h
}
Modes for Opening a File
Basic modes for opening a file using fopen:
"r" opens a file for reading ("r+" allows write also)
"w" creates a file for writing; or overwrites all previous content of an
existing file ("w+" allows read also)
"a" opens a file for appending; creates a file if it does not exist ("a+"
allows read also)
Opening a Binary File
We can add b with modes to indicate a binary file
e.g., "rb", "wb", "ab", "rb+", "wb+", and so on
FILE *fptr = fopen("image.jpg", "rb");
Reading from a File
FILE *fptr;
int x, y;
fptr = fopen("input.txt", "r");
fscanf(fptr, "%d%d", &x, &y);
Reading from a File
FILE *fptr;
int x, y;
fptr = fopen("input.txt", "r");
fscanf(fptr, "%d%d", &x, &y);
File pointer moves forward with each read operation
Reading from a File
#include <stdio.h>
int main(){
FILE* fptr = fopen("abc.txt", "r");
if (fptr == NULL) return 1;
/* Assume that abc.txt has the following content
NAME AGE CITY
abc 12 Hyderabad
bef 25 Delhi
cce 65 Bangalore */
char buf[100];
while (fscanf(fptr, "%*s %*s %s ", buf) == 1) //EOF otherwise
printf("%s\n", buf);
return 0;
}
Reading from a File
#include <stdio.h>
int main (){
FILE * fptr = fopen("input.txt", "r");
char c;
do
{
c = fgetc(fptr);
if (c == EOF)
break;
printf("%c ", c);
} while(1);
return 0;
}
Reading from a File
#include <stdio.h>
#define MAX 30
int main(){
char str[MAX], *a;
FILE *fptr = fopen("input.txt", "r");
a = fgets(str, MAX, fptr); /* until MAX-1 characters,
'\n', EOF encountered */
printf("%p\t%p", str, a);
printf("String is: %s", str);
return 0;
}
Writing to a File
#include <stdio.h>
int main(){
int a = 10, b = 5;
FILE *fptr;
fptr = fopen("file.txt", "w");
fprintf(fptr, "Hello World!\n");
fprintf(fptr, "%d %d", a, b);
return 0;
}
Writing to a File
#include <stdio.h>
int main(){
char c = 'a';
FILE *fptr;
fptr = fopen("file.txt", "w");
fputc(c, fptr);
fputc('b', fptr);
return 0;
}
Writing to a File
#include <stdio.h>
int main(){
char str1[7] = "CSI101";
char str2[7] = "CSI102";
FILE *fptr;
fptr = fopen("file.txt", "w");
fputs(str1, fptr);
fputs(str2, fptr);
return 0;
}
Closing a File
#include <stdio.h>
int main(){
FILE *fptr;
fptr = fopen("file.txt", "w");
if (fptr == NULL)
exit(1);
fputc('b', fptr);
fclose(fptr);
return 0;
}
Accessing a File at Random Positions
fseek() can be used to set position of the file pointer fptr
int fseek(FILE *fptr, long int offset, int whence);
New position specified by: offset (specified in bytes) and whence (can
take the following values)
SEEK_SET beginning of the file
SEEK_END end of the file
SEEK_CUR current position of the file pointer with respect to the
beginning of the file (also returned by ftell(fptr))
Accessing a File at Random Positions
Three Special Streams
Three special file streams (defined in the <stdio.h> header)
1. stdin reads input from the keyboard
2. stdout sends output to the screen
3. stderr prints errors to an error device (usually the screen also)
Three Special Streams
#include <stdio.h>
int main(){
int var;
fprintf(stdout, “Provide a value for var : ");
fscanf(stdin, "%d", &var);
fprintf(stdout, "Value of var = %d.\n", var);
fprintf(stderr, "Show error message here.\n");
return 0;
}
Input-File and Output-File Redirection
Standard input and standard output may be redirected to other
files (other than stdin and stdout)
$ ./a.out <in.txt >out.txt
scanf() reads data input from in.txt
printf() writes data output on out.txt
Input-File and Output-File Redirection
Standard input and standard output may be redirected to other
files (other than stdin and stdout)
$ ./a.out <in.txt >out.txt
scanf() reads data input from in.txt
printf() writes data output on out.txt
$ ./a.out <in.txt >>out.txt
All the best for your examinations. ☺