












Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!













These notes are for the Computer Engineering and Programming course at Pokhara University, revised syllabus 2012. The course code is CMP 103.3, titled "Programming in C" with a (3-0-3) structure. The evaluation includes theory and practical components. Theory accounts for 80% (30% sessional, 50% final) and practical accounts for 20% (sessional). The total marks are
The course aims to introduce students to the fundamental principles of programming and software system development. It covers using programming systems to achieve goals, identifying programming abstractions, developing formal program models, formalizing programming language semantics, specifying programs, and verifying programs. The focus is on clarifying concepts applicable across various programming contexts.
The course is divided into nine chapters:
Chapter 1: Introduction (3 Hrs) : History of computing and computers, programming concepts, computer block diagrams, computer generations, computer types, software, programming languages, and traditional vs. structured programming. Chapter 2: Programming Logic (5 Hrs) : Problem-solving (understanding problems, feasibility, and requirement analysis), design (flowcharts & algorithms), program coding (execution, translator), testing and debugging, implementation, evaluation, maintenance, and documentation. Chapter 3: Variables and Data Types (3 Hrs) : Constants and variables, variable declaration, variable types, simple input/output functions, and operators. Chapter 4: Control Structures (6 Hrs) : Introduction to control statements, sequential control, branching (if, else, else-if, switch), case, break, continue, looping (for, while, do-while), nested loops, and goto statements. Chapter 5: Arrays and Strings (6 Hrs) : Introduction to arrays, array initialization, multidimensional arrays, strings, and string-related functions. Chapter 6: Functions (6 Hrs) : Introduction to functions, returning values, sending values, arguments, parsing arrays and structures,
external variables, storage classes, pre-processor directives, C libraries, macros, header files, and prototyping. Chapter 7: Pointers (7 Hrs) : Definition of pointers for arrays, returning multiple values from functions using pointers, pointer arithmetic, pointers for strings, double indirection, pointers to arrays, and memory allocation (malloc and calloc). Chapter 8: Structure and Unions (5 Hrs) : Definition of structures, nested structures, arrays of structures, structures and pointers, unions, and self-referential structures. Chapter 9: Files and File Handling (4 Hrs) : Operating files in different modes (Read, Write, Append) and creating files in different modes (Read, Write, Append).
The laboratory work will emphasize verifying programming concepts learned in class, including the use of loops, functions, pointers, structures, and unions.
The following books are recommended:
Programming with C by Byron Gottfried C Programming by Balagurusami A Book on C by A. L. Kelley and Ira Pohl The C Programming Language by Kernighan, Brain, and Dennis Ritchie Depth in C by Shreevastav
Computer Types
Based on nature, computers are classified into Analog and Digital computers. Based on application, computers are classified as special purpose and general purpose computers. Special purpose computers are designed for specific tasks, while general purpose computers cater to a variety of users.
Computer Components
The main components of a computer are the Input Unit (IU), Central Processing Unit (CPU), and Output Unit (OU). The CPU consists of the Memory Unit, Control Unit, and Arithmetic and Logical Unit (ALU). The memory unit stores information, including programs.
Rules for Variable Names
It is discouraged to start variable names with an underscore.
Input/Output Functions
C provides built-in functions to read input and write data, such as scanf() and printf().
Operators
An operator is a symbol that performs specific mathematical or logical functions. C provides arithmetic, relational, logical, bitwise, assignment, and miscellaneous operators.
Arithmetic Operators
The basic arithmetic operators are +, - , *, /, and %. The order of precedence is %, /, *, +, -.
sizeof() Operator
The sizeof() operator returns the size of a variable or data type in bytes. The sizeof() an integer is typically 2 bytes, float is 4 bytes, double is 8 bytes, and char is 1 byte.
Data Types in C
Type Size (Bytes) Range char 1 -127 to 127 int 2 -32,767 to 32, float 4 1 10^-37 to 1 10^37 (6-digit precision) double 8 1 10^-37 to 1 10^37 (10-digit precision) long int 4 -2,147,483,647 to 2,147,483,
Control Statements
C provides branching structures like if, else, else if, and switch statements. Looping structures include for, while, and do-while loops. The break statement exits a loop or switch statement. The continue statement skips the current iteration of a loop. The goto statement transfers control to a labeled statement.
Functions
Functions can return a value or accept arguments. Arrays can be passed as arguments to functions.
Storage Classes
Storage classes define the scope and lifetime of variables.
Pointers
Pointers can be used to return multiple values from a function.
File Handling
Files can be opened in different modes (Read, Write, Append).
Relational and Logical Operators
Relational operators, such as < (less than), <= (less than or equal to), > (greater than), >= (greater than or equal to), == (equal to), and != (not equal to), compare values and produce a true/false result. For instance, given i = 1 , j = 2 , and k = i + j, the expression k > 5 evaluates to false, while k < 5 evaluates to true.
Logical operators, including && (and), || (or), and! (not), combine or modify true/false values. The! operator is a unary operator, acting on a single logical expression.
Assignment operators include =, +=, -=, *=, /=, and %=.
A conditional expression has the form expression1? expression2 : expression3. If expression1 is true, expression2 is evaluated and its value is returned; otherwise, expression3 is evaluated and its value is returned.
Bitwise Operators
C supports bitwise operators for manipulating data at the bit level.
Operator Precedence
Operator precedence determines the order in which operators are evaluated in an expression. For example, multiplication (*) has higher precedence than addition (+). In the expression x = 7 + 3 * 2 , x is
Branching structures allow the program to make decisions based on conditions.
if Statement
An if statement executes a block of code if a Boolean expression is true (non-zero and non-null).
if...else Statement
An if statement can be followed by an optional else statement, which executes if the Boolean expression is false.
if...else if...else Statement
The if...else if...else statement tests multiple conditions.
Nested if Statement
It is possible to nest if statements within other if or else if statements.
switch Statement
A switch statement tests a variable for equality against a list of values. The expression must be of an integral or enumerated type. The break statement terminates the switch and transfers control to the next line after the switch.
Looping structures allow the program to execute a block of code multiple times.
while Loop
A while loop repeatedly executes a block of code as long as a condition is true.
for Loop
A for loop efficiently executes a block of code a specific number of times.
do...while Loop
A do...while loop executes a block of code at least once and then repeatedly as long as a condition is true.
Nested Loops
C allows nesting loops (e.g., for inside for, while inside while, do...while inside do...while).
break Statement
The break statement terminates a loop (for, while, do...while) or switch statement immediately.
continue Statement
The continue statement skips the rest of the current iteration of a loop and proceeds to the next iteration.
goto Statement
The goto statement transfers control to a labeled statement within the same function. It is generally discouraged due to potential code complexity and difficulty in following program flow.
Arrays and Strings
Arrays are data structures that store a fixed-size, sequential collection of elements of the same type. They can be viewed as a collection of variables of the same type. Instead of declaring individual variables, an array variable is declared, and its elements are accessed using an index.
Declaring and Initialising
Arrays are declared using the syntax: data type array name [array size];. For example, double balance[10]; declares an array named balance that can hold 10 double values. The size of the array determines the number of elements it can store.
A program example to find the sum of marks of n students is provided, demonstrating array usage for storing and processing numerical data.
C allows the creation of arrays of arrays, known as multidimensional arrays. For example, int c[2][3] = {{1, 3, 0}, {-1, 5, 9}}; declares a 2x integer array. Alternatively, int c[2][3] = {1, 3, 0, -1, 5, 9}; achieves the same result, where the compiler infers the row structure.
User Defined Functions in C
C allows programmers to define their own functions, known as user-defined functions, to meet specific requirements. Every function in C should be declared before it is used; this declaration is also called a function prototype. The function prototype provides the compiler with information about the function's name, the types of arguments it accepts, and its return type. An example of a function prototype is int add ( int a , int b ) ;.
The general structure of a function definition in C consists of a function header and a function body. The function header specifies the return type, function name, and parameter list. The return type indicates the data type of the value the function returns. The function name and parameter list together form the function signature. The parameter list defines the type, order, and number of parameters the function accepts. The function body contains the statements that define the function's actions.
Functions can be called with or without a return value, using different syntax. When data is passed by value, a copy of the data is passed to the function. If the data is modified inside the function, the changes only affect the copy within the function's scope.
void callbyvalue ( int x) { printf ( ”x = %d before adding 10.\n” , x ) ; x += 10; printf ( ”x = %d after adding 10.\n” , x ) ; }
int main () { int a=10; printf ( ”a = %d before function .\ n” , a ) ; callbyvalue ( a ) ; printf ( ”a = %d after function .\ n” , a ) ; return 0; }
In the main() function, an integer a is initialized to 10. The callbyvalue() function is called with a as an argument. Inside callbyvalue(), the value of x (which is a copy of a) is modified, but this does not affect the original value of a in main().
When data is passed by reference, a pointer to the data is copied instead of the actual variable. This allows the function to modify the original data.
void callbyreference ( int ∗y) { printf ( ”b = %d before function .\ n” , *y ) ; ∗y += 10; printf ( ”b = %d after function .\ n” , *y ) ; }
int main () { int b=10; printf ( ”b = %d before function .\ n” , b ) ; callbyreference (&b ) ; printf ( ”b = %d after function .\ n” , b ) ; return 0; }
In this example, the address of b is passed to callbyreference(). Inside the function, *y is used to access the value at the memory location pointed to by y, and modifying *y directly changes the value of b in main().
Arrays can be passed as arguments to functions.
float largest ( float a [ ] , int size ){ int i ; float max; max=a [ 0 ] ; for ( i =1; i<size ; i ++){ if (max<a [ i ] ) max=a [ i ] ; } return (max ) ; }
Storage classes define the scope and lifetime of variables.
auto
The auto storage class is the default for local variables. It can only be used within functions.
register
The register storage class suggests that a local variable should be stored in a register instead of RAM for faster access. It is suitable for variables like counters that require quick access.
Preprocessor Syntax Description Header Inclusion #include Includes the source code of the specified file. Conditional Compilation
#ifedf, #endif,#if,#else
Includes or excludes sets of commands based on a condition.
Other directives #undef,#pragma
#undef undefines a defined macro variable. #pragma is used to call a function before and after a function in a C program.
Examples:
#define PI 3. #define count 100 #define area 5∗12. #define cube (x) (x∗x∗x)
A pointer is a variable that stores the memory address of another variable. The general form of a pointer variable declaration is type ∗var−name ;, where type is the pointer's base type and var-name is the name of the pointer variable.
int ∗ip ; /*pointer to an integer / double ∗dp ; /pointer to a double / float ∗fp ; /pointer to a float / char ∗ch /pointer to a character */
Using Pointers
int var = 20; /* actual variable declaration / int ∗ip ; /pointer variable declaration / ip = &var ; / store address of var in pointer variable */
printf ( ”Address of var variable : %x\n” , &var ) ; /*address stored in pointer variable / printf ( ”Address stored in ip variable : %x\n” , ip ) ; /access the value using the pointer */ printf ( ”Value of ∗ip variable : %d\n” , ∗ip ) ;
Null Pointer
Assigning NULL to a pointer variable is a good practice when an exact address is not available.
int ∗ptr = NULL; printf ( ”The value of ptr is : %x\n” , ptr ) ;
A pointer in C holds a numeric address value.
Incrementing Pointers
Pointers can be incremented to access consecutive memory locations.
int var [ 3 ] = {10 , 100 , 200}; int i , ∗ptr ; ptr = var ;
for ( i = 0; i < 3; i ++) { printf ( ”Address of var[%d ] = %x\n” , i , ptr ) ; printf ( ”Value of var[%d ] = %d\n” , i , ∗ptr ) ; ptr ++; }
Decrementing Pointers
Pointers can also be decremented.
int var [ 3 ] = {10 , 100 , 200}; int i , ∗ptr ; ptr = &var [ 2 ] ;
for ( i = 2; i >= 0; i −−) { printf ( ”Address of var[%d ] = %x\n” , i , ptr ) ; printf ( ”Value of var[%d ] = %d\n” , i , ∗ptr ) ; ptr −−; }
An array name is a constant pointer to the first element of the array.
double ∗p ; double balance [ 1 0 ] ; p = balance ; //p=&balance [ 0 ] ;
It is valid to use array names as constant pointers and vice versa. For example, *(balance + 4) is equivalent to balance[4].
Pointers and Arrays
The base address of an array can be assigned to a pointer. The value of the element pointed to by the pointer can be accessed using the indirection operator *. Incrementing the pointer p++ increases the address it points to by the size of the data type it points to (e.g., 2 bytes for an integer).
The malloc() function reserves a block of memory of a specified size and returns a pointer of type void, which can be cast into a pointer of any type.
ptr=(cast−type ∗) malloc ( byte−s i z e )
calloc() allocates space for an array of elements, initializes them to zero, and returns a pointer to the memory.
c a l l o c (n , element−s i z e ) ;
free() deallocates the previously allocated space.
f r e e ( ptr ) ;
Structures and Unions
A structure is a collection of logically related data items grouped together under a single name, called a structure tag.
struct structure name { data type member1 ; data type member2 ; data type member3 ; }
The members of a structure do not occupy memory until they are associated with a structure variable.
The members of a structure can be accessed with the help of the. (dot) operator.
s t r u c t v a r i a b l e. name ;
Arrays of structures can be initialized.
A member of a structure can be another structure. This is called a nested structure.
A pointer variable of a structure can be declared. The address of the structure variable can be assigned to the pointer variable. The members of the structure can be accessed using the -> operator.
pstructvar−>emp id
A structure can have members that point to a structure variable of the same type. These types of structures are called self-referential structures. They are widely used in dynamic data structures like linked lists and trees.
Unions are similar to structures, but with subtle differences. The declaration of a union is the same as that of a structure.
Structure Union Keyword struct defines structure Keyword union defines Union All members get allocated Only one member is active at a time
File Handling in C
A file represents a sequence of bytes on the disk where a group of related data is stored. A file is created for permanent storage of data. In C, a structure pointer of file type is used to declare a file.
FILE ∗fp ;
The fopen() function is used to create a new file or to open an existing file.
FILE *fopen(const char *filename, const char *mode);
The fclose() function closes the file.
int f c l o s e ( FILE ∗fp ) ;
Mode Description r Opens a text file in reading mode w Opens or creates a text file in writing mode a Opens a file in append mode r+ Opens a file in both reading and writing mode w+ Opens a file in both reading and writing mode a+ Opens a file in both reading and writing mode
This section presents a program to write student details to a file and then read and display those records.
A student structure is defined, containing name (character array of size 20), age (integer), and dept (character array of size 20).
In the main function, a file pointer fp is declared and assigned the result of opening "student.txt" in "w+" mode (write and read).
A loop iterates twice to collect data for two students. Inside the loop, the program prompts the user to enter the name and department for each student, storing the input into the s array of student structures. The fwrite function writes the contents of the s[i] structure to the file.
The rewind(fp) function resets the file pointer to the beginning of the file.
Another loop iterates twice to read the student data back from the file. The fread function reads data from the file into the s[i] structure. The program then prints the name, age, and department of each student.
The file is closed using fclose(fp).
This section outlines a program to input data for 100 employees into a file and then display the records of those employees living in "Kathmandu".
An employee structure is defined, containing name (character array of size 100), address (character array of size 100), and salary (float).
The program opens a file named "employee.txt" in write mode ("w").
A loop iterates 100 times to collect data for each employee. Inside the loop, the program prompts the user to enter the name, address, and salary for each employee, storing the input into the e array of employee structures. The fwrite function writes the contents of the e[i] structure to the file.
Another loop iterates through the e array. Inside the loop, the strcmp function compares the employee's address with "Kathmandu". If the addresses match, the employee's address and salary are printed.
This section describes a program to read book data from a file and display the names and prices of books with a price greater than 300.0.
A book structure is defined, containing name (character array of size 100), author (character array of size 100), and price (float).
The program opens a file named "library.dat" in read mode ("r").
A while loop reads book records from the file using fread. The loop continues as long as fread successfully reads a record.
Inside the loop, an if statement checks if the book's price is greater than 300.0. If it is, the book's name and price are printed.
This section presents a program to create a "student.txt" file to store records for 100 students, including their date of birth.
A student structure is defined, containing roll (integer), name (character array of size 20), address (character array of size 20), faculty (character array of size 20), and a nested structure dob for date of birth, containing mm (month), dd (day), and yy (year).
The program opens a file named "student.txt" in write mode ("w").
A loop iterates 100 times to collect data for each student. Inside the loop, the program prompts the user to enter the roll number, name, address, faculty, and date of birth for each student, storing the input into the s array of student structures. The fwrite function writes the contents of the s[i] structure to the file.
Another loop iterates through the s array. Inside the loop, the strcmp function compares the student's faculty with "Pokhara". If they don't match, the student's name, faculty, and date of birth are printed.