C Slides
C Slides
Introduction
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Introduction
1. Programming Language(PL)
4. First Programmer
6. Applications of C
8. Features of C
PROBLEM SOLVING WITH C
Introduction
● Imperative
● First do this and next do that
● FORTRAN, Algol, COBOL, Pascal
● Structured programming
● Single entry and single exit. Avoid GOTO
● C
● Procedural
● Subset of imperative
● Use of subroutines
●C
● Declarative
● Declares a set of rules about what outputs should result from which inputs
● Lisp, SQL
PROBLEM SOLVING WITH C
Introduction
Paradigm – Continued..
● Functional
● Function should be the first class citizen. No side effects. Assign Function
name to another, pass function name as an argument, return function itself
● If and recursion. No loops
● Scheme, Haskell, Miranda and JavaScript
● Logical
● Uses predicates
● Extraction of knowledge from basic facts and relations
● ASP, Prolog and Datalog
● Object-Oriented
● User perception is taken into account.
● Data needs protection
● Java, c++, Python
PROBLEM SOLVING WITH C
Introduction
History.. Continued...
● Development of C
● Martin Richards, around 60’s developed BCPL [Basic Combined
Programming Language]
● Enhanced by Ken Thompson and Introduced B language.
● C is Originally developed between 1969 and 1973 at Bell Labs by
Dennis Ritchie and Kernighan. Closely tied to the development of
the Unix operating system
FYK
• Dennis Ritchie
• Brian Kernighan
PROBLEM SOLVING WITH C
Introduction
Features of C
THANK YOU
Department of Computer Science and Engineering
3. First Program in C
4. Structure of C Program
6. C Compiler standards
First Program in C
#include<stdio.h>
int main()
{
printf(“Hello PES\n”);
return 0;
}
Program Structure
● Case sensitive
● Comments in C
● Using // for single line comment
● Using /* and */ for multiline comment
PROBLEM SOLVING WITH C
C Programming Environment
Way 1:
Step1: gcc <filename> // image a.out is the output
Step2: ./a.out OR a.exe
C Compiler standards
Using c99:
gcc -std=c99 program.c
Using c11:
gcc -std=c11 program.c
Nitin V Pujari
Faculty, Computer Science
Dean - IQAC, PES University
1 of 39
UE24CS151B: Problem Solving with C - Syllabus
Unit I: Problem Solving Fundamentals - 14 Hours - 18 Slots
Introduction to Programming, Salient Features of ‘C’, Program Structure, Variables, Data Types & range of values
,Qualifiers, Operators and Expressions, Control Structures, Input/Output Functions, Language Specifications
-Behaviors, Single character input and output, Coding standards and guidelines
2 of 39
UE24CS151B: Problem Solving with C - Course Objectives
The objective(s) of this course is to make students
● CObj4: Appreciate and gain knowledge about the issues with C Standards and
its respective behaviours
3 of 39
Bloom’s Taxonomy
4 of 39
UE24CS151B: Problem Solving with C - Course Outcomes
At the end of the course, the student will be able to
● CO3: Understand, analyse and apply text processing and string manipulation
methods using Arrays, Pointers and functions
● CO4: Understand user defined type creation and implement the same using C
structures, unions and other ways by reading and storing the data in secondary
systems which are portable.
5 of 39
UE24CS151B: Problem Solving with C Text Book
6 of 39
UE24CS151B: About Text Book Authors
7 of 39
UE24CS151B: Problem Solving with C Reference Books
8 of 39
UE24CS151B: Problem Solving with C Reference Books
9 of 39
UE24CS151B : PSWC: Unit 1 - gcc Insights
● The original author of the GNU C Compiler (gcc) is Richard Stallman, the founder of the GNU Project
● The GNU Project was started in 1984 to create a complete Unix-like operating system as free software, in
order to promote freedom and cooperation among computer users and programmers
● The first release of gcc was made in 1987, as the first portable ANSI C optimizing compiler released as free
software
● A major revision of the compiler came with the 2.0 series in 1992, which added the ability to compile C++
● The acronym gcc is now used to refer to the “GNU Compiler Collection”
● gcc has been extended to support many additional languages, including Fortran, ADA, Java and
Objective-C
● Its development is guided by the gcc Steering Committee, a group composed of representatives from gcc
user communities in industry, research and academia
10 of 39
UE24CS151B : PSWC: Unit 1 - gcc Features
● gcc is a portable compiler, it runs on most platforms available today, and can produce output for
many types of processors
● gcc is not only a native compiler, it can also cross-compile any program, producing executable files
for a different system from the one used by gcc itself.
● gcc allows software to be compiled for embedded systems which are not capable of running a
compile
● gcc written in C with a strong focus on portability, and can compile itself, so it can be adapted to new
systems easily
● gcc can compile or cross-compile programs in each language, for any architecture
● gcc, for example,can compile an ADA program for a microcontroller, or a C program for a
supercomputer 11 of 39
UE24CS151B : PSWC: Unit 1 - gcc Features
● gcc has a modular design, allowing support for new languages and
architectures to be added.
● gcc is free software, distributed under the GNU General Public License
(GNU GPL), which means we have the freedom to use and to modify
gcc, as with all GNU software.
● gcc users have the freedom to share any enhancements and also make
use of enhancements to gcc developed by others.
● Historically, c has been used for writing low-level systems software, and applications
where high performance or control over resource usage are critical
● In addition to C , the GNU Project also provides other high-level languages, such as
C++, GNU Common Lisp (gcl), GNU Smalltalk (gst), the GNU Scheme extension
language (guile) and the GNU Compiler for Java (gcj).
● These languages with exception to c and c++, do not allow the user to access memory
directly, eliminating the possibility of memory access errors.
● This compiles the source code in PESU.c to machine code and stores it in an executable file PESU’.
● The output file for the machine code is specified using the ‘-o’ option.
● -o option is usually given as the last argument on the command line, If it is omitted, the output is written
to a default file called ‘a.out’.
● If a file with the same name as the executable file already exists in the current directory it will be
overwritten
● The option ‘-Wall’ turns on all the most commonly-used compiler warnings, it is recommended that we
always use this option!
● gcc will not produce any warnings unless they are enabled.
● Source code which does not produce any warnings by gcc, is said to be compile cleanly.
15 of 39
UE24CS151B : PSWC: Unit 1 - Finding errors in a simple program using gcc
● Compiler warnings are an essential aid when programming in c
● Error is not obvious at first sight, but can be detected by the compiler if the warning
option ‘-Wall’ has been enabled for safety
● If there are any functions which are not used correctly they can cause the program to
crash or produce incorrect results.
● Turning on the compiler warning option ‘-Wall’ for safety will catch many of the
commonest errors which occur in c programming
16 of 39
UE24CS151B : PSWC: Unit 1 - Creating object files from source files using gcc
● The command-line option ‘-c’ is used to compile a source file to an object file.
● ‘-c’ produces an object file ‘<filename>.o’ containing the machine code for the
main function.
● There is no need to use the option ‘-o’ to specify the name of the output file in
this case.
● When compiling with ‘-c’ the compiler automatically creates an object file
whose name is the same as the source file, but with ‘.o’ instead of the original
extension 17 of 39
UE24CS151B : PSWC: Unit 1 - Compilation options - Setting search paths using
gcc
● The list of directories for header files is often referred to as the include path,
and the list of directories for libraries as the library search path or link path
● The compiler options ‘-I’ and ‘-L’ add new directories to the beginning of the
include path and library search path respectively
18 of 39
UE24CS151B : PSWC: Unit 1 - c Language Standards using gcc
● By default, gcc compiles programs using the GNU dialect of the C language, referred to as GNU C
● This dialect incorporates the official ANSI/ISO standard for the C language with several useful GNU extensions,
such as nested functions and variable-size arrays.
● The command-line option ‘-pedantic’ in combination with ‘-ansi’ will cause gcc to reject all GNU C extensions, not
just those that are incompatible with the ANSI/ISO standard
● The following options are a good choice for finding problems in C programs
Note: While this list is not exhaustive, regular use of these options will catch many common errors. 19 of 39
UE24CS151B : PSWC: Unit 1 - Errors
● Error
○ a mistake
● Preprocessor Error
○ Linker Errors are the errors encountered when the executable file of
the code can not be generated even though the code gets compiled
successfully.
○ This Error is generated when a different object file is unable to link with
the main object file.
○ Sometimes, we do not get the output we expected after the compilation and execution of a
program.
○ Even though the code seems error free, the output generated is different from the expected
one.
● Semantic Errors
○ Errors that occur because the compiler is unable to understand the written code are called
Semantic Errors.
○ A semantic error will be generated if the code makes no sense to the compiler, even though it is
syntactically correct.
○ It is like using the wrong word in the wrong place in the English language
24 of 39
UE24CS151B : PSWC: Unit 1 - Simple Input / Output Function
● Input and output functions are available in the c language to perform the most common tasks.
● In every c program, three basic functions take place namely accepting of data as input, the
processing of data, and the generation of output
● When a programmer says input, it would mean that they are feeding some data in the program.
● Programmer can give this input from the command line or in the form of any file.
● The c programming language comes with a set of various built-in functions for reading the input
and then feeding it to the available program as per our requirements.
● When a programmer says output, they mean displaying some data and information on the printer,
the screen, or any other file.
● The c programming language comes with various built-in functions for generating the output of the
data on any screen or printer, and also redirecting the output in the form of binary files or text file.
25 of 39
UE24CS151B : PSWC: Unit 1 - Unformatted I/O
● The unformatted functions are not capable of controlling the format that is involved in writing and reading the
available data.
● Hence these functions constitute the most basic forms of input and output.
● The supply of input or the display of output isn’t allowed in the user format, hence we call these functions as
unformatted functions for input and output.
○ We use the character input functions for reading only a single character from the input
device by default the keyboard
■ getchar(), getche(), and the getch() refer to the input functions of unformatted type
○ we use the character output functions for writing just a single character on the output
source by default the screen
■ the putchar() and putch() refer to the output functions of unformatted type
26 of 39
UE24CS151B : PSWC: Unit 1 - Unformatted I/O
● The unformatted functions are not capable of controlling the format that is involved in writing and reading the
available data.
● Hence these functions constitute the most basic forms of input and output.
● The supply of input or the display of output isn’t allowed in the user format, hence we call these functions as
unformatted functions for input and output.
○ In any programming language including c, the character array or string refers to the
collection of various characters
○ Various types of input and output functions are present in c programming that can easily
read and write these strings.
■ The puts() and gets() are the most commonly used ones for unformatted forms
■ gets() refers to the input function used for reading the string characters
■ puts() refers to the output function used for writing the string characters
27 of 39
UE24CS151B : PSWC: Unit 1 - Formatted Output in C - printf
● printf()
○ This function is used to display one or multiple values in the output to the user at the console.
■ int printf(const char *format, ...)
■ Predefined function in stdio.h
■ Sends formatted output to stdout by default
■ Output is controlled by the first argument
■ Has the capability to evaluate an expression
■ On success, it returns the number of characters successfully written on the output.
■ On failure, a negative number is returned.
■ Arguments to printf can be expressions
○ While calling any of the formatted console input/output functions, we must use a specific format
specifiers in them, which allow us to read or display any value of a specific primitive data type.
There are
33
keywords
in python
29 of 39
UE24CS151B : PSWC: Unit 1 - Compile time and Runtime in c Language
● Compile time is the
period when the
programming code is
converted to the machine
code.
31 of 39
UE24CS151B : PSWC: Unit 1 - sizeof operator in c Language
● The sizeof operator is the most common operator in C.
● It can be applied to any data type, float type, pointer type variables
● When sizeof() is used with the data types, it simply returns the amount of
memory allocated to that data type.
● The output can be different on different machines like a 32-bit system can
show different output while a 64-bit system can show different of same data
types 32 of 39
UE24CS151B : PSWC: Unit 1 - Literals and Constants in c Language
● Literals are the constant values assigned to the constant variables.
■ Integer literal
■ Float literal
● It is a literal that contains only floating-point values or real numbers.
● These real numbers contain the number of parts such as integer part, real part,
exponential part, and fractional part.
○ Decimal form
■ The decimal form must contain either decimal point, real part, or both.
■ If it does not contain either of these, then the compiler will throw an error.
■ The decimal notation can be prefixed either by '+' or '-' symbol that specifies the
positive and negative numbers.
■ Float literal
● The floating-point literal must be specified either in decimal or in
exponential form.
○ Exponential form
35 of 39
UE24CS151B : PSWC: Unit 1 - Literals and Constants in c Language
● Literals are the constant values assigned to the constant variables.
○ Exponential form
■ Syntax of float literal in exponential form
● [+/-] <Mantissa> <e/E> [+/-] <Exponent>
● We can use both the signs, i.e., positive and negative, before the mantissa
and exponent. Spaces are not allowed
36 of 39
UE24CS151B : PSWC: Unit 1 - Literals and Constants in c Language
● Literals are the constant values assigned to the constant variables.
■ Character Literal
● A character literal contains a single character enclosed within single quotes.
● If we try to store more than one character in a character literal, then the warning of a
multi-character character constant will be generated.
● We can also use the ASCII in integer to represent a character literal. For
example, the ascii value of 65 is 'A'.
■ String Literal
Nitin V Pujari
Faculty, Computer Science
Dean - IQAC, PES University
[email protected]
For Course Digital Deliverables visit www.pesuacademy.com
39 of 39
Problem Solving With C - UE24CS151B
Variables and Data Types
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Variables and Data Types
1. Identifiers
3. Keywords
4. Data types
PROBLEM SOLVING WITH C
Variables and Data Types
Identifiers
● It is a name used to identify a variable, keyword, function, or any
other user-defined item.
Keywords
● Are identifiers which have special meaning in C.
● Few here: auto, else, long, switch, break, enum, case, extern, return
char, float, for, void, sizeof, int, double …
Data Types
● The amount of storage to be reserved for the specified variable.
1. Introduction
2. Size Qualifiers
3. Sign Qualifiers
4. Type Qualifiers
Introduction
• Keywords which are applied to the data types resulting in Qualified type
• Applied to basic data types to alter or modify its sign or size
• Types of Qualifiers
• Size Qualifiers
• Sign Qualifiers
• Type qualifiers
PROBLEM SOLVING WITH C
Qualifiers in C
Size Qualifiers
• short int <= int <=long int // short int may also be abbreviated as short and long int as long. But,
there is no abbreviation for long double.
• Coding Examples
PROBLEM SOLVING WITH C
Qualifiers in C
Sign Qualifiers
• A signed qualifier specifies a variable which can hold both positive and negative integers
• Coding Examples
PROBLEM SOLVING WITH C
Qualifiers in C
Type Qualifiers
• A way of expressing additional information about a value through the type system and
ensuring correctness in the use of the data
3. float No qualifier
4. double long
5. void No qualifier
THANK YOU
Department of Computer Science and Engineering
3. Unformatted functions
PROBLEM SOLVING WITH C
Simple Input/Output
Format string
● % [flags] [field_width] [.precision] conversion_character
where components in brackets [] are optional. The minimum requirement is %
and a conversion character (e.g. %d).
● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output
Escape sequences
● Represented by two key strokes and represents one character
● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output
Unformatted functions
● Character input and output functions – getchar() and putchar()
● String input and output functions – gets() and puts() This will be discussed in unit – 2
● Coding examples
THANK YOU
Department of Computer Science and Engineering
2. Expression
Expression
● An expression consists of Operands and Operators
● Evaluation of Operands: Order is not defined
● Evaluation of Operators: Follows the rules of precedence and rules of
Associativity
http://web.cse.ohio-state.edu/~babic.1/COperatorPrecedenceTable.pdf
● L-value and R-values.
● Side effects of Expression
● Coding examples
PROBLEM SOLVING WITH C
Operators in C
1. Selection structures
2. Looping structures
4. Practice Programs
PROBLEM SOLVING WITH C
Control Structures
Selection Structures
▪ If ▪ Switch
if (e1) switch (expression)
<block>|<stmt> {
▪ If – else case integral constant: <stmt> break;
if (e1) case integral constant: <stmt> break;
<block>|<stmt> default: <stmt>
else }
<block>|<stmt>
<block>|<stmt>
else if (e2)
<block>|<stmt>
else
<block>|<stmt>
PROBLEM SOLVING WITH C
Control Structures
Looping Structures
▪ for
for(e1; e2; e3)
<block>|<stmt>
▪ while
while(e2)
<block>|<stmt>
▪ do while
do { <block>
}while(e2);
e1,e2,e3 are expressions where e1: initialization, e2: condition, e3: modification
▪ Infinite loop
▪ Coding Examples
PROBLEM SOLVING WITH C
Control Structures
▪ One if may be inside another: inner if is reached only if the Boolean condition of the outer if is
true
▪ Coding Examples
PROBLEM SOLVING WITH C
Control Structures
Practice Programs
▪ WAP to count the number of digits which are divisible by 2 in a given integer.
▪ WAP to input a floating point number from the user and print the count of digits which are
divisible by 3 after the decimal point.
▪ Input 10 characters from the user and check the count of vowels and print same.
THANK YOU
Department of Computer Science and Engineering
Storing more than one value in single variable of primitive type - Possible?
Code for Real World applications developed by one person or by a Team?
You Tube code is written in one language and that code is available in one file?
PROBLEM SOLVING WITH C
Single character Input Output
Approaches:
scanf and printf – Formatted IO functions
getchar and putchar - Commonly used in console applications or loops for
handling text input and output efficiently
The getchar reads a single character from the standard input (stdin) and
returns it as an int, allowing it to handle ASCII values or detect EOF (End of
File). It waits for the user to press Enter before processing the input.
putchar() is used to print a single character to the standard output (stdout). It
takes a character as an argument and displays it on the screen, making it
useful for character-by-character output.
Coding examples
PROBLEM SOLVING WITH C
Single character Input Output
Approaches:
getc() and putc()
getc reads a character from an input stream and returns the corresponding
integer value on success. It returns EOF on failure.
int getc(FILE *stream)
putc writes a character into a file
int putc(int character, FILE *stream)
Coding examples
PROBLEM SOLVING WITH C
Single character Input Output
1. Language Specification
2. Standards
Language Specification
▪ A documentation that defines a programming language so that users
and implementers can agree on what programs in that language mean.
▪ Are typically detailed and formal, and primarily used by implementers referring
to them in case of ambiguity.
Standards
de Facto: Practices that are legally recognized, regardless of whether the
practice exists in reality.
de Jure: Describes situations that exist in reality, even if not legally recognized
▪ Language may have one or more implementations which acts as deFacto Language may
be implemented and then specified, or vice versa or together.
▪ Languages can exist and be popular for decades without a specification - Perl
▪ After 20 years of usage, specification for PHP in 2014
▪ ALGOL 68 : First (and possibly one of the last) major language for which a full formal
definition was made before it was implemented
PROBLEM SOLVING WITH C
Language Specifications/Behaviors
▪ It is the name of a list of conditions that the program must not meet.
▪ Standard imposes no requirements: May fail to compile, may crash, may generate
incorrect results, may fortunately do what exactly programmer intended
▪ Coding Examples
THANK YOU
Department of Computer Science and Engineering
• Reduces debugging and development time, especially when multiple developers are
working on the same code.
• In certain cases, even improves the runtime and security of your code.
PROBLEM SOLVING WITH C
C Standards and Guidelines
Documentation
• Add clear, concise comments for complex logic
• Include file headers with purpose, author, date, and version.
• Maintain external documentation where needed.
Error Handling
• Check return values of functions (malloc, scanf, etc.) to account for any unforeseen
behaviour.
• Use errno and perror() for error messages that may pop up in your code5.
• Use assertions (assert.h) for debugging6.
5 - Source: https://www.gnu.org/prep/standards/
• Avoid using the ‘goto’ construct for any flow control6. 6 - Source: https://www.oreilly.com/library/view/code-
complete-second/0735619670/
PROBLEM SOLVING WITH C
C Standards and Guidelines
Maintain Modularity
• Keep all functions short, modular, and primarily focused on a single purpose3.
3 - Source: https://www.oreilly.com/library/view/clean-code/9780136083238/
4 - Source: https://www.misra.org.uk/misra-c/
PROBLEM SOLVING WITH C
C Standards and Guidelines
Security Practices
• Validate all inputs to prevent buffer overflows and other vulnerabilities.
• Prefer safe functions (e.g., strncpy() over strcpy()) when handling strings and buffers.
1. What is an Array?
2. Properties of Arrays.
3. Classification of Arrays
6. Array Traversal
PROBLEM SOLVING WITH C
Arrays, Initialization and Traversal
What is an Array?
A linear data structure, which is a Finite collection of similar data items stored in
successive or consecutive memory locations
Homogenous types of data allowed in any array. May contain all integer or all
character elements, but not both together.
Properties of Arrays
Classification of Arrays
Category 1:
• Fixed Length Array
• Size of the array is fixed at compile time
• Variable Length Array
Category 2:
• One Dimensional (1-D) Array
• Stores the data elements in a single row or column.
• Multi Dimensional Array
PROBLEM SOLVING WITH C
Arrays, Initialization and Traversal
Declaration
Syntax:
Data_type Array_name[Size];
Data_type: Specifies the type of the element that will be contained in the array
Array_name: Identifier to identify a variable
Size: Indicates the max no. of elements that can be stored inside the array
Example: double x[15]; // Can contain 15 elements of type double, 0 to 14 are valid array indices or subscript
• Subscripts in array can be integer constant or integer variable or expression that yields integer
• C performs no bound checking. Care should be taken to ensure that the array indices are within the declared
limits
PROBLEM SOLVING WITH C
Arrays, Initialization and Traversal
Initialization
0 1 2 3 4 5
Index
PROBLEM SOLVING WITH C
Arrays, Initialization and Traversal
Traversal
• int a[10];
• How do you access the 5th element of the array? // a[4]
• How do you display each element of the array? // Using Loop
• How much memory allocated for this?
Number of bytes allocated = size specified*size of integer
• Coding examples
THANK YOU
Department of Computer Science and Engineering
Multi-Dimensional Arrays
1. Introduction
Introduction
• An array with more than one level or dimension.
• 2-Dimensional and 3-Dimensional and so on.
xx x x x xx x xx x
PROBLEM SOLVING WITH C
Multi-Dimensional Arrays
Initialization
• Column Major Ordering: All elements of one column are followed by all elements of the next
column and so on.
• Address of A[i][j] = Base_Address +( (i * No. of columns in every row) + j)*size of every element;
• Consider, int matrix[2][3]={1,2,3,4,5,6}; // base address is 100 and size of integer is 4 bytes
• Address of matrix[1][0]=100+((1*3)+0)*4=100+3*4=112
PROBLEM SOLVING WITH C
Multi-Dimensional Arrays
Demo of C Code
• Coding examples
PROBLEM SOLVING WITH C
Multi-Dimensional Arrays
• Consider, int arr[3][4] = {11, 22, 33, 44, 55, 66, 77, 88, 99, 100, 111, 121};
arr – points to 0th elements of arr- Points to 0th 1-D array-5000
arr+1-Points to 1st element of arr-Points to 1st 1-D array-5016
arr+2-Points to 2nd element of arr-Points to 2nd 1-D array
arr+ i Points to ith element of arr ->Points to ith 1-D array
PROBLEM SOLVING WITH C
Multi-Dimensional Arrays
• Using p[5] results in 66. But p[1][1] results in error. p doesn’t know the size of the column.
• Write a function to add, subtract and multiply two matrices. Display appropriate message
when these two matrices are not compatible for these operations.
• Write a program to take n names from the user and print it. Each name can have maximum
of 20 characters.
PROBLEM SOLVING WITH C
Multi-Dimensional Arrays
• First dimension represents table ,2nd dimension represents number of rows and 3rd
dimension represents the number of columns
• int arr[2][3][2] = { {{5, 10}, {6, 11}, {7, 12}}, {{20, 30}, {21, 31}, {22, 32}} }; //2 table 3 rows 2
coloumns.
PROBLEM SOLVING WITH C
Multidimensional Arrays
Practice programs
1. Given two matrices, write a function to find whether these two are identical.
4.Write a function to check whether the given matrix is identity matrix or not.
1. What is a Pointer?
What is a Pointer?
• A variable which contains the address. This address is the location of another object in the
memory
• Pointer of particular type can point to address of any value in that particular type.
2000 p a
2000 100
2000
sum p
PROBLEM SOLVING WITH C
Pointers
• Coding examples
PROBLEM SOLVING WITH C
Pointers
• Size of the array returns the number of bytes occupied by the array. But the
size of pointer is always constant in that particular system.
int *p1; float *f1 ; char *c1;
printf("%d %d %d ",sizeof(p1),sizeof(f1),sizeof(c1)); // Same value for all
Example code:
• int a[] = {22,11,44,5};
• int *p = a;
• a++;// Error : a is constant pointer
• p++; // Fine
• p[1] = 222;
• a[1] = 222 ; // Fine
• If variable i is used in loop for the traversal, a[i], *(a+i), p[i], *(p+i), i[a], i[p] are all same.
PROBLEM SOLVING WITH C
Pointers
Array and Pointer continued..
Differences
1. the sizeof operator
a. sizeof(array) returns the amount of memory used by all elements in array
b. sizeof(pointer) only returns the amount of memory used by the pointer variable itself
2. the & operator
a. &array is an alias for &array[0] and returns the address of the first element in array
b. &pointer returns the address of pointer
3. string literal initialization of a character array
a. char array[] = “abc” sets the first four elements in array to ‘a’, ‘b’, ‘c’, and ‘\0’
b. char *pointer = “abc” sets pointer to the address of the “abc” string (which may be stored
in read-only memory and thus unchangeable)
4. Pointer variable can be assigned a value whereas array variable cannot be.
5. Arithmetic operations on pointer variable is allowed. On array, not allowed all.
THANK YOU
Department of Computer Science and Engineering
• Introduction
• Demo of C Code
PROBLEM SOLVING WITH C
Array of Pointers
Introduction
• Used to create complex data structures such as linked lists, trees, graphs
PROBLEM SOLVING WITH C
Array of Pointers
Demo of C Code
• Program to swap first and last elements of the array of integers using array of pointers
and display the array of integers using array of pointers.
THANK YOU
Department of Computer Science and Engineering
1. Introduction to functions
2. Types of Functions
5. Parameter passing in C
PROBLEM SOLVING WITH C
Functions
Introduction
Types of Functions
• Coding examples
PROBLEM SOLVING WITH C
Functions
• The arguments must match the parameters in the function definition in it’s type, order and
number.
• Coding examples
PROBLEM SOLVING WITH C
Functions
• In ‘C’, function returns a single value. The expression of return is evaluated and copied to the temporary location by
the called function. – No name
• If the return type of the function is not same as the expression of return in the function definition, the expression is
cast to the return type before copying to the temporary location
• The value that‘s returned to the calling program is the value that results when expression is evaluated, and this
should be of the return type specified for the function.
• Coding examples
PROBLEM SOLVING WITH C
Functions
Parameter passing in C
• All the operations that are valid for pointer will be applicable for array too in the
body of the function.
• Array being actual parameter – Indicated using the name of the array
Array a is declared as int a[5];
Then myfun is called as myfun(a,n);
• Array being actual parameter – Indicated using the name of the array
Array a is declared as int a[5];
Then myfun is called as myfun(a,n);
• If a function should not modify the elements in the array, use the keyword const
• Example:
void show_the_world(const int a[ ], int size);
• The compiler will issue an error if there is a statement inside the body of the
function to modify the array elements
• Coding examples
PROBLEM SOLVING WITH C
Arrays and Functions
• Program contains these declarations: int a[10]; int i; void myfunc(int n);
• Variables a[0] through a[9] are of type int, making below calls is legal
myfunc(a[0]);
myfunc(a[3]);
myfunc(a[i]); // i is between 0 and 9
THANK YOU
Department of Computer Science and Engineering
• Introduction
• Automatic Variables
• External Variables
• Static Variables
• Register Variables
• Global Variables
PROBLEM SOLVING WITH C
Storage classes in C
Introduction
• To describe the features of a variable/function . Features include scope(visibility) and
life-time to trace the existence of a particular variable/function during the runtime
Automatic Variables
• A variable declared inside a function without any storage class specification is by default
an automatic variable
• Created when a function is called and are destroyed automatically when the function
execution is completed
• Also called as called local variables because they are local to a function. By default,
assigned to undefined values
• Can be accessed outside their scope. But how ?
• By using Pointers
• Coding Examples
PROBLEM SOLVING WITH C
Storage classes in C
External Variables
• To inform the compiler that the variable is declared somewhere else and make it
available during linking
• Does not allocate storage for variables
• The default initial value of external integral type is 0 otherwise null.
• All functions are of type extern
• Coding Examples
PROBLEM SOLVING WITH C
Storage classes in C
Static Variables
• Tells the compiler to persist the variable until the end of program.
• Initialized only once and remains into existence till the end of program
• Can either be local or global depending upon the place of declaration
• Scope of local static variable remains inside the function in which it is defined but the life
time of is throughout that program file
• Global static variables remain restricted to scope of file in each they are declared and life
time is also restricted to that file only
• All static variables are assigned 0 (zero) as default value
• Coding Examples
PROBLEM SOLVING WITH C
Storage classes in C
Register Variables
• Registers are faster than memory to access. So, the variables which are most frequently
used in a program can be put in registers using register keyword
• The keyword register hints to compiler that a given variable can be put in a register. It’s
compiler’s choice to put it in a register or not.
• Compilers themselves do optimizations and put the variables in register. If a free register
is not available, these are then stored in the memory only
• If & operator is used with a register variable, then compiler may give an error or warning
• Coding Examples
PROBLEM SOLVING WITH C
Storage classes in C
• The variables declared outside all function are called global variables. They are not
• Coding Examples
THANK YOU
Department of Computer Science and Engineering
1. Points to Discuss
2. Introduction
4. Demo of C Callback
PROBLEM SOLVING WITH C
Callback in C
Points to Discuss!!!
• How to extend the features of one function using another one? - What is the method used if
one function communicates with the other through parameter?
• How to have one common method to develop libraries and event handlers for many
programming languages?
• How redirect page action is performed for the user based on one click action?
PROBLEM SOLVING WITH C
Callback in C
Introduction
• Any executable code that is passed as an argument to other code, which is expected to call
(execute) the argument at a given time.
• In simple language, if a function name is passed to another function as an argument to call it,
then it will be called as a Callback function.
● Coding Examples
PROBLEM SOLVING WITH C
Callback in C
Demo of C Callback
• Mimic map, filter and reduce function of python in C using user defined function
THANK YOU
Department of Computer Science and Engineering
1. Introduction
2. Why Recursion?
5. Practice Programs
PROBLEM SOLVING WITH C
Recursion
Introduction
Recursive Function
• A function that calls itself Directly or indirectly
Why Recursion?
• The exit condition is defined by the base case and the solution to the base case is
provided
• The solution of the bigger problem is expressed in terms of smaller problems called
as recursive relationship
PROBLEM SOLVING WITH C
Recursion
• Values are not retained from one call to next (or among recursions)
PROBLEM SOLVING WITH C
Recursion
2. Introduction
3. Searching Algorithms
4. Linear Search
• What if one wants to save the time consumed in looking to each item in a collection of
items?
PROBLEM SOLVING WITH C
Searching
Introduction
Searching Algorithms
● Random Search
Linear Search
• Performs search on any kind of data
• Coding Example
PROBLEM SOLVING WITH C
Searching algorithms
Binary Search
1. Why Sorting?
2. Sorting Algorithms
4. Demonstration of C Code
PROBLEM SOLVING WITH C
Sorting
Why Sorting ?
• Think about searching for something in a sorted drawer and unsorted drawer
• If the large data set is sorted based on any of the fields, then it becomes easy to search for
a particular data in that set.
PROBLEM SOLVING WITH C
Sorting
Sorting Algorithms
• Bubble Sort
• Insertion Sort
• Quick Sort
• Merge Sort
• Radix Sort
• Selection Sort
• Heap Sort
PROBLEM SOLVING WITH C
Sorting
• In every iteration, the minimum element (considering ascending order) from the unsorted
sub-array is picked and moved to the sorted sub-array.
PROBLEM SOLVING WITH C
Sorting
Demonstration of C Code
1. Introduction
2. Declaration
3. Initialization
4. Demo of C Code
5. String v/s Pointer
PROBLEM SOLVING WITH C
Strings in C
Introduction
• An array of characters and terminated with a special character ‘\0’ or NULL.
ASCII value of NULL character is 0.
• String constants are always enclosed in double quotes. It occupies one byte
more to store the null character.
Declaration
Initialization
Version 1:
• char a1[] = {'a', 't', 'm', 'a', '\0' };
• Shorthand notation: char a1[] = ”atma”;
Initialization continued..
Version 5: char a5[ ] = {'a', 't', 'm', 'a', '\0', 't', 'r', 'i', 's', 'h', 'a', '\0' };
Demo of C Code
• To read and display a string in C
• Points to note:
• If the string is hard coded, it is programmer’s responsibility to end the string with ‘\0‘
character.
• scanf terminates when white space is given in the user input.
• scanf with %s will introduce '\0' character at the end of the string. printf with %s
requires the address and will display the characters until '\0' character is encountered
• If you want to store the entire input from the user until user presses new line in one
character array variable, use [^\n] with %s in scanf
PROBLEM SOLVING WITH C
Strings in C
• char x[] = "pes"; // x is an array of 4 characters with ‘p’, ‘e’, ‘s’, ‘\0
Stored in the Stack segment of memory
• Can change the elements of x. x[0] = ‘P’;
• Can not increment x as it is an array name. x is a constant pointer.
• char *y = “pes”;
y is stored at stack. “pes” is stored at code segment of memory. It is read only.
• y[0] = ‘P’ ; // undefined behaviour
• Can increment y . y is a pointer variable.
THANK YOU
Department of Computer Science and Engineering
• strlen(a) – Expects string as an argument and returns the length of the string, excluding the NULL
character
• strcpy(a,b) – Expects two strings and copies the value of b to a.
• strcat(a,b) – Expects two strings and concatenated result is copied back to a.
• strchr(a,ch) – Expects string and a character to be found in string. Returns the address of the
matched character in a given string if found. Else, NULL is returned.
• strcmp(a,b) – Compares whether content of array a is same as array b. If a==b, returns 0. Returns
1, if array a has lexicographically higher value than b. Else, -1.
PROBLEM SOLVING WITH C
String manipulation Functions & Errors
Error Demonstration
• Introduction
• Demo of C Code
PROBLEM SOLVING WITH C
Command Line Arguments
Introduction
• Providing data to the program whenever the command to execute is used
• Provided after the name of the executable in command-line shell of Operating Systems
Example: a.exe 18 27 // a.exe is the executable for the code to add two numbers
// 8 27 are numbers to be added
• All the arguments which are passed in the command line are accessed as strings inside the
program .
• Use atoi function to convert to integer if integers are passed in Command line
PROBLEM SOLVING WITH C
Command Line Arguments
Demo of C Code
2. Memory Allocation
3. Dynamic allocation
• Example: A[1000] can be used but what if the user wants to run the code for only 50 elements
//memory wasted
Memory Allocation
1. Static allocation
- decided by the compiler
- allocation at load time [before the execution or run time]
- example: variable declaration (int a, float b, a[20];)
2. Automatic allocation
- decided by the compiler
- allocation at run time
- allocation on entry to the block and deallocation on exit
- example: function call (stack space is used and released as soon as callee function returns back to the
calling function)
3. Dynamic allocation
- code generated by the compiler
- allocation and deallocation on call to memory allocation and deallocation functions
PROBLEM SOLVING WITH C
Dynamic Memory Management
Dynamic Allocation
• malloc()
• calloc()
• realloc() Code
• free() segment
• Available in stdlib.h
Memory space
PROBLEM SOLVING WITH C
Dynamic Memory Management
• Allocates requested size of bytes and returns a void pointer pointing HEAP
to the first byte of the allocated space on success. Else returns NULL 5000 X
STACK
5001 X
• The return pointer can be type-casted to any pointer type 5002 X
ptr 5000 5003 X
• Memory is not initialized 5004 X
5005 X
• Syntax: 5006 X
void *malloc(size_t N); // Allocates N bytes of memory 5007 X
• Example: 5008 X
int* ptr = (int*) malloc(sizeof (int)); // Allocate memory for an int 5009 X
• Coding example
PROBLEM SOLVING WITH C
Dynamic Memory Management
• Allocates space for elements, initialize them to zero and then returns a HEAP
5000
void pointer to the memory. Else returns NULL STACK
5001
0
5002
• The return pointer can be type-casted to any pointer type ptr 5000 5003
5004
• Syntax: 5005
void *calloc(size_t nmemb, size_t size); 5006
0
//allocates memory for an array of nmemb elements of size bytes each 5007
5008
• Example: 5009
0
int* ptr = (int*) calloc (3,sizeof (int)); 5010
//Allocating memory for an array of 3 elements of integer type 5011
5012 X
• Coding example 5013 X
PROBLEM SOLVING WITH C
Dynamic Memory Management
• Modifies the size of previously allocated memory using malloc or calloc functions
• Returns a pointer to the newly allocated memory which has the new specified size. Returns
NULL for an unsuccessful operation
• If realloc() fails, the original block is left untouched
• Syntax: void *realloc(void *ptr, size_t size);
• If ptr is NULL, then the call is equivalent to malloc(size), for all values of size
• If size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr)
• This function can be used only for dynamically allocated memory, else behavior is undefined
PROBLEM SOLVING WITH C
Dynamic Memory Management
realloc() continued..
• The content of the memory block is preserved up to the lesser of the new and old sizes, even
if the block is moved to a new location
• If the new size is larger than the old size, then it checks if there is an option to expand or not.
• If the existing allocation of memory can be extended, it extends it but the added memory will not be
initialized.
• If memory cannot be extended, a new sized memory is allocated, initialized with the same older elements
and pointer to this new address is returned. Here also added memory is uninitialized.
• If the new size is lesser than the old size, content of the memory block is preserved.
• Coding examples
PROBLEM SOLVING WITH C
Dynamic Memory Management
free()
• Releases the allocated memory and returns
HEAP HEAP
it back to heap 5000
N Bytes
STACK
• Syntax:
free (ptr); //ptr is a pointer to a memory block
which has been previously created using malloc/calloc ptr (5000) free(ptr)
AVAILABLE
MEMORY
• No size needs to be mentioned in the AVAILABLE
free(). MEMORY
Structures in C
• Introduction
• Characteristics
• Declaration
• Accessing members
• Initialization
• Memory allocation
• Comparison
PROBLEM SOLVING WITH C
Structures in C
Introduction
• A user-defined data type that allows us to combine data of different types together.
• Provides a way of storing many different values in variables of potentially different types
under the same name.
Characteristics/Properties
• Order of fields and the total size of a variable of that type is decided when the
new type is created
Syntax :
• Keyword struct is used for creating a structure. Example: User defined type Student entity is
created.
• The format for declaring a structure is as below:
struct <structure_name> struct Student
{ {
data_type member1; int roll_no;
data_type member2; char name[20];
….. int marks;
data_type memebern; };
}; // semicolon compulsory
Declaration
s1
• Members of a structure can be accessed only when instance variables are roll_no X
created
name X
• If struct Student is the type, the instance variable can be created as: marks X
struct student s1; // s1 is the instance variable of type struct
Fig. 1. After declaration, only
Student undefined entries (X)
• Declaration (global) can also be done just after structure body but before
semicolon.
PROBLEM SOLVING WITH C
Structures in C
Initialization
• Structure members can be initialized using curly braces ‘{}’ and separated by comma.
• Data provided during initialization is mapped to its corresponding members by the compiler
automatically.
s1
• Further extension of initializations can be: roll_no 11
name J O H N \0
1. Partial initialization: Few values are provided.
Remaining are mapped to zero. For strings, ‘\0’. marks 65
2. Designated initialization: Fig. 2. After initialization, entries are mapped
- Allows structure members to be initialized in any order.
- This feature has been added in C99 standard.
- Specify the name of a field to initialize with ‘.member_name =’ OR
‘member_name:’ before the element value. Others are initialized to default value.
PROBLEM SOLVING WITH C
Structures in C
• Any member of a structure can be accessed using the pointer to a structure as:
pointer_variable->member_name
Example: s2->roll_no
// where s2 is the pointer to structure variable and we want to access roll_no member of s2.
PROBLEM SOLVING WITH C
Structures in C
Memory allocation
• At least equal to the sum of the sizes of all the data members.
• Coding Examples
PROBLEM SOLVING WITH C
Structures in C
Comparison of structures
• Coding examples
THANK YOU
Array of Structures
1. Introduction
Introduction
• Think about storing the roll number, name and marks of one student
We need structures to store different types of related data.
struct student s;
• Think about storing the roll number, name and marks of 100 students
We need an Array of structures
struct student S[100];
• S[0] stores the information of first student, S[1] stores the information of second student and so on.
S
S[0] S[1] S[2] S[3] S[99]
2000 . . .
2000
roll_no X X X X . . . X
name X X X X . . . X
marks X X X X . . . X
PROBLEM SOLVING WITH C
Array of Structures
- After structure declaration (either inside main or globally using struct keyword)
struct student s[100];
• Coding examples
PROBLEM SOLVING WITH C
Array of Structures
struct student S[] = { {1, “John”, 60}, {2,”Jack”, 40}, {3, “Jill”, 77} };
struct student S[3] = { {11, “Joseph”, 60}}; //partial initialization
struct student S[2] = {1, “John”, 60, 2,”Jack”, 40};
• Coding examples
PROBLEM SOLVING WITH C
Array of Structures
• Used to access the array of structure 1000 1030 1060 1090 1120
variables efficiently
ST[0] ST[1] ST[2] ST[3] ST[5]
struct student
{ int roll_no;
ptr++
char name[22];
int marks;
1000
}ST[5];
ptr
1. Why Sorting?
2. Sorting Algorithms
4. Demonstration of C Code
PROBLEM SOLVING WITH C
Sorting
Why Sorting ?
• Think about searching for something in a sorted drawer and unsorted drawer
• If the large data set is sorted based on any of the fields, then it becomes easy to search for
a particular data in that set.
PROBLEM SOLVING WITH C
Sorting
Sorting Algorithms
• Bubble Sort
• Insertion Sort
• Quick Sort
• Merge Sort
• Radix Sort
• Selection Sort
• Heap Sort
PROBLEM SOLVING WITH C
Sorting
• An array is traversed from left and adjacent elements are compared and the higher
one is placed at right side.
• In this way, the largest element is moved to the rightmost end at first.
• This process is continued to find the second largest number and this number is
placed in the second place from rightmost end and so on until the data is sorted.
PROBLEM SOLVING WITH C
Sorting
Demonstration of C Code
Bit fields in C
Unions in C
• What is Union?
• Union vs Structure
PROBLEM SOLVING WITH C
Unions in C
What is Union?
• A user defined data type which may hold members of different sizes and types
• Allow data members which are mutually exclusive to share the same memory
• Unions provide an efficient way of using the same memory location for multiple-purpose
• At a given point in time, only one can exist
• The memory occupied will be large enough to hold the largest member of the union
• The size of a union is at least the size of the biggest component
• All the fields overlap and they have the same offset : 0.
• Used while coding embedded devices
PROBLEM SOLVING WITH C
Unions in C
Union Vs Structure
THANK YOU
Enums(Enumerations) in C
• Introduction
• Enum creation
• Demo of Enums in C
PROBLEM SOLVING WITH C
Enumerations
Introduction
• A way of creating user defined data type to assign names to integral constants. Easy to
remember names rather than numbers
• The names are symbols for integer constants, which won't be stored anywhere in
program's memory
Enum creation
• Syntax:
enum identifier { enumerator-list }; // semicolon compulsory
// identifier optional
• Example:
enum Error_list { SUCCESS, ERROR, RUN_TIME_ERROR, BIG_ERROR };
• Coding Examples
PROBLEM SOLVING WITH C
Enumerations
• We can assign values to some of the symbol names in any order. All unassigned names get
value as value of previous name plus one.
• Enumerated Types are Not Strings. Two enum symbols/names can have same value
• All enum constants must be unique in their scope. It is not possible to change the constants
• Storing the symbol of one enum type in another enum variable is allowed
• One of the short comings of Enumerated Types is that they don't print nicely
PROBLEM SOLVING WITH C
Enumerations
Domo of Enum in C
1. Introduction
3. Characteristics
5. Pictorial Representation
6. Different Types
7. Applications
PROBLEM SOLVING WITH C
Linked List
Introduction
● Collection of nodes connected via links.
● The node and link has a special meaning in C.
● Few points to think!!
- Can we have pointer data member inside a structure? - Yes
- Can we have structure variable inside another structure? - Yes
- Can we have structure variable inside the same structure ? – No
Solution is: Have a pointer of same type inside the structure
PROBLEM SOLVING WITH C
Linked List
Characteristics
● Insertion
● Deletion
● Search
● Display
● Merge
● Concatenate
PROBLEM SOLVING WITH C
Linked List
Pictorial Representation
s info link info link info link
p
Fig2: Displaying the Linked list
PROBLEM SOLVING WITH C
Linked List
Different Types
Applications
1. Introduction to Queue
2. Operations on Queue
3. Types of Queues
4. Priority Queue
5. Applications of Priority Queue
PROBLEM SOLVING WITH C
Priority Queue
Introduction to Queue
● A line or a sequence of people or vehicles awaiting for their turn to be attended or to proceed.
definite order
● A Data structure which has 2 ends – Rear end and a Front end. Open ended at both ends
● Data elements are inserted into the queue from the Rear end and deleted from the front end.
Operations on Queue
● Enqueue − Add (store) an item to the queue from the Rear end.
● Dequeue − Remove (access) an item from the queue from the Front end.
PROBLEM SOLVING WITH C
Priority Queue
Types of Queues
● Ordinary Queue - Insertion takes place at the Rear end and deletion takes place at the
Front end
● Priority Queue - Special type of queue in which each element is associated with a
priority and is served according to its priority. If elements with the same priority occur,
they are served according to their order in the queue
● Circular Queue - Last element points to the first element of queue making circular link.
● Double ended Queue - Insertion and Removal of elements can be performed from both
front and rear ends
PROBLEM SOLVING WITH C
Priority Queue
Priority Queue
● Type of Queue where each element has a "Priority" associated with it.
● The Enque operation stores the item and the “Priority” information
3. Prim’s Algorithm
4. Data Compression
File Handling in C
1. Points to Discuss
2. Introduction
3. Need of Files
4. File Classification
5. Operations on Files
Points to Discuss!!!
• Can we use the data entered by the user in one program execution, in another program
execution without asking the user to enter again?
• Program stores the result what if one wants to store other data too?
• To persist data even after the program execution is complete, use Files
• The keyboard and the output screen are also considered as files
PROBLEM SOLVING WITH C
File Handling
Need of Files
• When a program is terminated, the entire data is lost. Storing in a data file will preserve the
data even if the program terminates
• If the data is too large, a lot of time spent in entering them to the program every time the
code is run
• If stored in a data file, easier to access the contents of the data file using few functions in C
PROBLEM SOLVING WITH C
File Handling
File Classification
● Text File
● Contains textual information in the form of alphabets, digits and special characters or
symbols
● Created using a text editor
● Binary File
● Contain bytes or a compiled version of a text file i.e. data in the form of 0’s and 1’s
● Can store larger amount of data that are not readable but secured.
PROBLEM SOLVING WITH C
File Handling
Operations on Files
Note: To perform any operation on Files, The physical filename, the logical filename and the
mode must be connected using fopen()
• Physical Name: A file is maintained by the OS. The OS decides the naming convention of a file
• Logical Name: In a C Program, identifier is used to refer to a file. Also called as File Handle
fopen()
Syntax: fopen(“path of the file with filename”, “mode”);
// mode can be r, w, a, r+, w+, a+
● Opens a file in the specified mode and returns a FILE pointer(address of the structure which
contains information about the attributes of the file) if it succeeds. Else returns NULL.
● Initializing a FILE pointer does not mean that the whole file is made available in memory.
Other functions are required to access the contents
PROBLEM SOLVING WITH C
File Handling
fclose()
● Closes the stream. All buffers are flushed
Syntax: fclose(file_pointer);
● Coding Examples
PROBLEM SOLVING WITH C
File Handling
Read /Write operations on File
● Categories
● Character read/write
● fputc() , fgetc(), getc() and putc().
● String read/write
● fgets() and fputs().
● Formatted read/write
● fscanf() and fprinft().
● Block read/write
● fread() and fwrite()
PROBLEM SOLVING WITH C
File Handling
• Reads a character from the file and increments the file pointer position.
• Syntax: int fgetc(FILE *fp);
• Return Value:Next byte from the input stream on success, EOF on error.
• Write operation at current file position and increments the file pointer position.
• Syntax: int fputc(int c,FILE *fp);
• Return Value:Character that is written on success, EOF on error.
• getc() and putc() are macros while fgetc() and fputc() are functions
• Coding Examples
PROBLEM SOLVING WITH C
File Handling
•Reads a line of characters from file and stores it into the string pointed to by char_array
variable. It stops when either (n-1) characters are read, the newline character is read, or the end-
of-file is reached, whichever comes first
• Syntax: char* fgets(char *char_array, int n, FILE *stream)
• Return Value: Pointer to the string buffer on success, NULL on EOF or Error.
• Coding examples
PROBLEM SOLVING WITH C
File Handling
● Reads the formatted data from the file instead of standard input.
● Syntax: int fscanf(FILE *fp,const char *format[,address,…..]);
● Return Value: The number of values read on success ,EOF on failure.
● Coding Examples
PROBLEM SOLVING WITH C
File Handling
● The function returns the current pointer position ,value from the beginning of file.
● Syntax: ftell(FILE* pointer)
● Return Value: 0 or a positive integer on success and -1 on error.
● File handling in C programming enables the reading from and writing to files stored on disk
or other permanent storage media.
● This feature is vital for tasks that require data persistence, such as saving program outputs,
processing input from files, or managing logs.
Opening a File
● It requires two arguments: the name of the file and the mode in which to open it.
● r for reading.
● w for writing (file need not exist).
● a for appending (file need not exist).
● r+ for reading and writing from the beginning.
● w+ for reading and writing (also creates file).
● a+ for reading and appending.
FILE *fp;
fp = fopen("NSectionData.txt", "w");
if (fp == NULL)
{
printf("Error opening file\n");
return 1;
}
Closing a File
● To close a file, use the fclose() function, which helps prevent data loss and frees up
resources.
Syntax:
int fclose(FILE *stream);
fclose(fp);
Nitin V Pujari 1
Writing to a File
● The fprintf(), fputc(), and fwrite() functions are commonly used for writing to files.
Positioning in a File
● fseek(), ftell(), and rewind() are used to manipulate the file pointer.
Nitin V Pujari 2
Error Handling
if (ferror(fp))
{
printf("Error reading from file\n");
} else if (feof(fp))
{
printf("End of file reached\n");
}
#include <stdio.h>
int main() {
FILE *fp;
char dTw[50] = "PES University N Section";
char dTr[50];
return 0;
}
Nitin V Pujari 3
Using Binary File - Examples in C Language - Reading and writing block of data
● In C language, fread() and fwrite() are standard library functions used for reading from and
writing to binary files, respectively.
● Binary files contain data in its raw form, without any special formatting like newline
characters or encoding.
● This makes them ideal for storing complex data structures or preserving data integrity
across different systems.
fread()
● fread() is used to read data from a binary file. Its syntax is:
○ size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
Example:
Suppose you have a binary file containing integer data. You want to read 5 integers from this file
into an array.
#include <stdio.h>
int main() {
FILE *FilePointer;
int NSectionData[5];
Nitin V Pujari 1
// Display the read integers
for (int i = 0; i < 5; i++) {
printf("%d ", data[i]);
}
return 0;
}
fwrite()
#include <stdio.h>
int main() {
FILE *FilePointer;
int NSectionData[5] = {10, 20, 30, 40, 50};
return 0;
}
Nitin V Pujari 2
● The above examples illustrate the basic usage of fread() and fwrite() functions for handling
binary files in C.
● Remember to handle file opening errors and close the file properly after reading from or
writing to it.
● Also, ensure compatibility of data types and endianness when reading or writing binary data
across different systems.
Nitin V Pujari 3
Using Binary File - Examples in C Language - Reading and writing structures
● This program defines a simple structure called Person which contains information about a
person including their name and age.
● The program reads data from the user, writes it into a binary file, then reads the data from
the binary file and prints it out
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *FilePointer;
struct Person person; // Declare a variable of type Person
// Read data from the user and write it to the binary file
printf("Enter name: ");
fgets(person.name, sizeof(person.name), stdin); // Read name from user
strtok(person.name, "\n"); // Remove trailing newline
printf("Enter age: ");
scanf("%d", &person.age); // Read age from user
Nitin V Pujari 4
// Open the binary file in read mode
file = fopen("persons.bin", "rb");
if (FilePointer == NULL) {
perror("Error opening file");
return 1;
}
return 0;
}
● The main() function begins. It declares a file pointer file and a Person struct variable person.
● It opens a binary file named "persons.bin" in write mode ("wb"). If there's an error, it prints an
error message and returns 1.
● It prompts the user to enter a name and age, reads them, and writes them into the binary file
using fwrite().
● The file is opened again, this time in read mode ("rb"). If there's an error, it prints an error
message and returns 1.
● It reads the structure from the binary file using fread() and prints out the name and age.
Nitin V Pujari 5
C program that demonstrates appending and reading structures in binary files, along with
comments to explain each part of the code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
if (file == NULL) {
printf("Error opening file!\n");
return;
}
// Function to read and print all person records from a binary file
void readPersons(const char *filename) {
FILE *file = fopen(filename, "rb"); // Open file in read binary mode
if (file == NULL) {
printf("Error opening file!\n");
return;
}
Nitin V Pujari 6
int main() {
struct Person p1 = {"Alice", 25, 5.6}; // Sample person record
● We define a structure Person to represent a person, containing fields for name, age, and
height.
● It opens the file in append binary mode and writes the Person structure to the file using
fwrite. Then, it closes the file.
● In the main function, we create a sample Person structure p1 and append it to the file using
appendPerson.
● We create two more sample Person structures p2 and p3 and append them to the file using
appendPerson.
● Finally, we call readPersons to read and print all person records from the file.
Nitin V Pujari 7
Parsing and Processing CSV Files in C
● Parsing and processing CSV (Comma-Separated Values) files is a common task in many
programming contexts, including C. CSV files are used to store tabular data in plain text
format, where each line represents a data record, and each record consists of fields or
columns separated by commas.
● This format is widely used due to its simplicity and interoperability with various systems,
including spreadsheets and databases.
● Opening and reading the file: Using standard file I/O functions.
● Parsing each line: Breaking down each line into individual fields.
● Processing the data: Depending on the application, processing might involve storing data in
memory, performing calculations, or outputting processed data.
● Error handling: Ensuring robust handling of file errors, malformed data, etc.
● Tools and Libraries: While it's possible to manually parse CSV files using standard C library
functions, libraries like libcsv can simplify the task by handling edge cases and complexities
such as:
○ Fields containing commas (e.g., "Hi, PESU", “N”, “Section”).
○ Handling newline characters within quoted fields.
○ Efficient memory management.
For this example, Let us demonstrate how to parse a CSV file manually without external libraries,
focusing on fundamental C programming techniques.
Example Scenario
Suppose we have a CSV file named data.csv containing information about students and their
scores. The file format is as follows:
SRN,Age,Score
SRN1,21,88
SRN2,22,92
SRN3,20,76
Nitin V Pujari 1
Our goal is to read this file, parse it, and calculate the average score.
Step-by-Step Implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
3. Parsing Function
This function takes a string (a line from the CSV), parses it, and fills a Student struct with the data:
Open the file, read each line, parse it, and calculate the average score:
int main() {
FILE* fp = fopen("data.csv", "r");
if (!fp) {
perror("File opening failed");
return EXIT_FAILURE;
}
Nitin V Pujari 2
char line[MAX_LINE_LENGTH];
int count = 0;
int totalScore = 0;
Student student;
if (count > 0) {
printf("Average Score: %.2f\n", (double)totalScore / count);
}
fclose(fp);
return EXIT_SUCCESS;
}
Note:
Conclusion and Further Considerations
● For more robust applications, consider using a dedicated CSV parsing library that can
handle complex CSV features like multi-line fields, different delimiters, etc.
● Error handling is also crucial, especially for large or malformed CSV files.
● Ensure your program gracefully handles unexpected formats, corrupted files, and runtime
errors like file read errors.
Nitin V Pujari 3
Problem Definition
● Given a large CSV file containing healthcare data, the task is to read, parse, and process the
file efficiently in C.
● The data should be loaded into a suitable data structure, allowing for subsequent
operations such as searching, sorting, and filtering.
Assumptions
● Each line in the .csv file represents one record, and the first line contains column headers.
● Typical operations might include searching for records based on conditions, summarizing
data, and exporting results.
For demonstration purposes, consider a .csv file with the following structure:
ID,Name,Age,Gender,Diagnosis
1,XXX,30,M,Diabetes
2,YYY,,25,F,Hypertension
...
● Data Storage:
○ Define structures to store the parsed data.
○ Opt for dynamic data structures that can handle large datasets efficiently.
Nitin V Pujari 4
● Memory Management:
○ Allocate and deallocate memory appropriately.
○ Ensure there are no memory leaks.
● Operations on Data:
○ Implement functions to search, sort, and filter the records.
● Output/Reporting:
○ Allow results to be outputted back into .csv format or other formats.
Detailed Implementation
Data Structures
Define a structure to represent each record:
typedef struct {
int id;
char name[100];
int age;
char gender;
char diagnosis[50];
} PatientRecord;
Nitin V Pujari 5
File Reading and Parsing
return record;
}
char line[MAX_LINE_LENGTH];
fgets(line, sizeof(line), file); // Skip header line
Nitin V Pujari 6
}
fclose(file);
}
process_csv(argv[1]);
return 0;
}
● Efficiency:
○ Reading the file line by line minimizes memory usage.
○ Efficient data structures (e.g., hash tables for quick lookup).
● Robustness:
○ Proper error handling to catch I/O errors, memory allocation failures, and data
parsing issues.
○ Validate all inputs and handle data anomalies.
Note:
● Parsing and processing large .csv files in C for healthcare data can be managed
effectively by careful implementation of file handling, data parsing, and memory
management strategies.
Nitin V Pujari 7
Example Scenario: Agricultural Dataset
Let’s consider a scenario where we have a CSV file named agriculture_data.csv containing data
like the following:
Region,Year,Crop,Area(Acres),Yield(Ton/Acre)
Punjab,2022,Corn,5000,3.2
Karnataka,2022,Ragi,3000,2.8
Maharashtra,2022,Wheat,4500,2.5
...
We need to parse this file and calculate the total yield per region.
C Code Example
● Below is an example of how one might write C code to parse this file, calculate the required
statistics, and handle large files efficiently.
Nitin V Pujari 8
Helper Functions for Parsing
return record;
}
Nitin V Pujari 9
while (fgets(buffer, BUFFER_SIZE, fp))
{
AgricultureRecord record = parse_csv_line(buffer);
printf("Region: %s, Year: %d, Crop: %s, Area: %d, Yield: %.2f\n",
record.region, record.year, record.crop, record.area, record.yield);
// Here you could aggregate data, calculate statistics, etc.
}
fclose(fp);
}
Main Function
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: %s <csv_file>\n", argv[0]);
return EXIT_FAILURE;
}
process_csv(argv[1]);
return EXIT_SUCCESS;
}
● Line Buffer: BUFFER_SIZE should be large enough to handle the longest expected line in
your CSV. If lines are very long, consider dynamic allocation and reallocation strategies.
● Error Handling: Robust error handling (for file I/O failures, memory issues, etc.) is crucial in
real-world applications.
Nitin V Pujari 10
Note:
● The provided code example demonstrates a basic approach to parsing CSV files in C.
● For production systems, especially with large datasets, consider advanced techniques such
as memory-mapped files, optimized I/O operations, and parallel processing to handle data
efficiently and robustly.
● This is particularly relevant in fields like agriculture where data-driven decisions can
significantly impact productivity and sustainability.
Nitin V Pujari 11
Example Project Spatial Computing
● The goal of this project is to develop a C program that can efficiently handle large .csv files
containing spatial data.
● We will specifically focus on parsing .csv files with spatial data (like geographic
coordinates), processing this data (e.g., filtering or transforming coordinates), and finally,
outputting the processed data.
Key Features
● Efficient CSV Parsing: Implement a robust CSV parser that can handle large files without
exhausting system memory.
● Data Filtering: Provide functionality to filter records based on specific spatial criteria.
Step-by-Step Breakdown
Nitin V Pujari 12
● Step 2: CSV Parser Implementation
○ Reading Files
○ Use fopen to open the file.
○ Read the file line by line using fgets.
○ Parsing Lines
○ Use strtok to tokenize each line by commas.
○ Convert strings to appropriate data types (e.g., atof for floating points).
○ Storing Data
○ Define a struct to store each row's data.
○ Use dynamic memory allocation (e.g., malloc) to handle large datasets.
Nitin V Pujari 13
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: %s <csv_file>\n", argv[0]);
return 1;
}
parse_csv(file);
fclose(file);
return 0;
}
Note:
● This basic setup provides a framework for handling large spatial computing datasets in C,
with focus on efficient data handling and processing.
● By using simple file and string manipulation techniques from the C standard library, we can
achieve robust CSV parsing suitable for various applications in the spatial computing
domain.
● As improvements, one could integrate more sophisticated spatial data handling libraries or
parallel processing techniques to enhance performance for very large datasets.
Nitin V Pujari 14
Objective: To develop a C program that can efficiently parse large .CSV files containing IoT
sensor data, extract relevant information, and perform some basic analysis.
Dataset Example:
● Timestamp
● SensorID
● Temperature
● Humidity
● Pressure
Each row in the CSV file represents a reading from an IoT device.
Output:
● Average, minimum, and maximum values of temperature, humidity, and pressure for each
sensor.
Steps to Approach:
● Reading Large CSV Files: Implement buffered reading to handle large files without
consuming excessive memory.
● Parsing CSV Data: Develop a function to parse each line using delimiters (e.g., commas).
● Error Handling: Properly manage potential errors in file handling and data parsing.
Nitin V Pujari 15
Implementation
Below are the detailed steps and code snippets to help you implement the project.
1. Data Structures
Define structures to hold sensor data and statistics.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char timestamp[20];
int sensorID;
double temperature;
double humidity;
double pressure;
} SensorData;
typedef struct {
double minTemperature;
double maxTemperature;
double avgTemperature;
double minHumidity;
double maxHumidity;
double avgHumidity;
double minPressure;
double maxPressure;
double avgPressure;
int count;
} SensorStats;
2. Parsing Function
This function reads and parses each line of the CSV.
int parse_csv_line(char *line, SensorData *data)
{
char *token;
token = strtok(line, ",");
if (!token) return 0;
strcpy(data->timestamp, token);
token = strtok(NULL, ",");
if (!token) return 0;
data->sensorID = atoi(token);
Nitin V Pujari 16
token = strtok(NULL, ",");
if (!token) return 0;
data->temperature = atof(token);
token = strtok(NULL, ",");
if (!token) return 0;
data->humidity = atof(token);
token = strtok(NULL, ",");
if (!token) return 0;
data->pressure = atof(token);
return 1;
}
Use buffered reading to process each line from the CSV file.
void process_file(const char *filename)
{
FILE *file = fopen(filename, "r");
if (!file) {
perror("Failed to open file");
return;
}
char buffer[BUFFER_SIZE];
SensorData data;
fclose(file);
}
4. Main Function
The entry point of the program, initiating file processing.
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "Usage: %s <csv_file>\n", argv[0]);
return EXIT_FAILURE;
}
Nitin V Pujari 17
process_file(argv[1]);
return EXIT_SUCCESS;
}
● Error Handling: Add robust error checking after each file and memory operation.
● Memory Management: Efficiently manage memory if dynamically allocating large data
structures.
● Multi-threading: Use POSIX threads to handle different parts of the CSV file in parallel to
utilize multi-core processors efficiently.
Note:
● This project outline and code snippets provide a basic structure.
● To expand it, you can incorporate more sophisticated statistical analyses, handle multiple
files simultaneously, or optimize memory and CPU usage further by using advanced data
structures like linked lists or hash tables for sensor data aggregation.
Nitin V Pujari 18
Approach to build a C project to parse a large .CSV file relevant to AR/VR. The project will involve
reading a large dataset, parsing the CSV format, and processing data to generate useful statistics.
● Requirements:
○ Efficiently handle large datasets.
○ Extract and summarize data (e.g., count total interactions per object).
○ Handle potential errors in data formats.
○
Step 2: Plan the CSV Structure
The .CSV file might look like this:
timestamp,user_id,interaction_type,object_id
2024-04-29T12:00:00,1001,grab,501
2024-04-29T12:00:01,1002,move,502
2024-04-29T12:00:02,1001,rotate,501
...
// Function prototypes
void parse_csv(const char* filename);
void process_line(char* line);
Nitin V Pujari 19
int main(int argc, char** argv)
{
if (argc < 2) {
printf("Usage: %s <csv_file>\n", argv[0]);
return 1;
}
parse_csv(argv[1]);
return 0;
}
char buffer[BUFFER_SIZE];
fgets(buffer, BUFFER_SIZE, file); // Skip header line
fclose(file);
}
Nitin V Pujari 20
// Output parsed data (for debugging)
printf("Timestamp: %s, User ID: %d, Interaction Type: %s, Object ID: %d\n",
interaction.timestamp, interaction.user_id, interaction.interaction_type,
interaction.object_id);
}
void print_summary() {
for (int i = 0; i < MAX_OBJECTS; i++) {
if (interaction_counts[i] > 0) {
printf("Object ID %d had %d interactions\n", i, interaction_counts[i]); } }}
Step 7: Optimization
For handling very large datasets:
● Consider multithreading to process chunks of the file in parallel.
● Optimize memory usage and I/O operations.
● Use profiling tools to find and fix bottlenecks.
Note:
● This project illustrates basic CSV parsing and data processing in C for AR/VR
interaction data.
● The use of efficient data structures and careful implementation choices allows
handling large datasets effectively.
● This framework can be extended with more complex analytics, real-time processing
capabilities, or integration into larger systems.
Nitin V Pujari 21
Function pointers in C
● Function pointers in C are pointers that point to functions, allowing for dynamic function
calls and implementations.
● They are a powerful feature of the C language, enabling functionality such as callbacks,
dynamic dispatch, and function arrays.
● Understanding function pointers is crucial for advanced C programming and is often used
in systems programming, embedded systems, and other low-level programming tasks.
● In C, like other pointers, function pointers hold the memory address of a function.
● Here, return_type is the return type of the function, pointer_name is the name of the pointer,
and parameter_list is the list of parameters that the function takes.
Nitin V Pujari 22
#include <stdio.h>
int main()
{
int (*operation)(int, int); // Declare a function pointer
return 0;
}
● Callbacks: Function pointers are often used as callbacks, allowing a function to call another
function dynamically.
■ For example, in event-driven programming or asynchronous I/O, a callback
function can be registered to be called when a certain event occurs.
● Dynamic Dispatch:
○ Function pointers enable dynamic dispatch, where the appropriate function to call is
determined at runtime.
● Function Arrays: Function pointers can be stored in arrays, allowing for dynamic selection
and invocation of functions based on runtime conditions.
Nitin V Pujari 23
#include <stdio.h>
void fun1() {
printf("Function 1\n");
}
void fun2() {
printf("Function 2\n");
}
int main() {
void (*fun_ptr_arr[])(void) = {fun1, fun2}; // Array of function pointers
return 0;
}
Note:
● Function pointers in C provide a flexible and powerful mechanism for dynamic function
calls and implementations.
● Understanding function pointers is essential for writing efficient, modular, and reusable C
code.
Nitin V Pujari 24
Callback in Language
● Callbacks are an essential concept in programming, allowing for flexible and dynamic
behavior within functions.
Definition:
● The receiving function can then execute the callback function at a later time or under
certain conditions.
Purpose:
Function Pointers:
● In C, callbacks are typically implemented using function pointers
Usage:
● The process function can now accept any function that matches the specified signature
(void function(int)) as its callback.
Scenario: Consider a program that performs various mathematical operations on a given number
using callbacks.
Nitin V Pujari 25
#include <stdio.h>
// Callback functions
void square(int num)
{
printf("Square of %d is %d\n", num, num * num);
}
int main() {
int number = 5;
printf("Number: %d\n", number);
// Using callbacks
performOperation(number, square);
performOperation(number, cube);
return 0;
}
Explanation: In the above example, the performOperation function takes a number and a callback
function as arguments. It then executes the specified callback function on the given number.
Nitin V Pujari 26
Advantages of Callbacks:
● Reusability: Callbacks promote code reuse by separating generic functionality from specific
implementation details.
Limitations of Callbacks:
● Performance Overhead: Indirect function calls through function pointers may incur a slight
performance overhead compared to direct function calls.
Note:
● Callbacks are a powerful mechanism in C programming that enable dynamic and flexible
behavior.
● Understanding and effectively utilizing callbacks can significantly enhance the design and
functionality of C programs
Nitin V Pujari 27
PROBLEM SOLVING WITH C
UE23CS151B
2. Error Handling
3. Demo of Errors
4. Best Practices
PROBLEM SOLVING WITH C
File Handling
Error Handling
● When a function is called, a global variable named as errno is automatically assigned a value
used to identify the type of error that has been encountered
errno value Type of Error
1 Operation not permitted
2 No such file or directory
5 I/O error
7 Argument list too long
9 Bad file number
11 Try again
12 Out of memory
13 Permission denied
● Coding Examples
PROBLEM SOLVING WITH C
File Handling
• Two-status library functions are used to prevent performing any operation beyond EOF
• The error indication will last until the file is closed(fclose())or cleared by the clearerr() function.
PROBLEM SOLVING WITH C
File Handling
Best Practices
● Given a file pointer check whether it is NULL before proceeding with further operations
● Use errno.h and global variable errno to know the type of error that occurred. Usage of
strerror() and perror() helps in providing textual representation of the current errno value
● Good to check whether EOF is reached or not before performing any operation on the file
THANK YOU
2. Problem Statements
4. Demo of C Solution
PROBLEM SOLVING WITH C
Problem Solving: File Handling
Problem Statements
Demo of C Solution
• Demonstration of C Code
THANK YOU
Searching
2. Introduction
3. Searching Algorithms
4. Linear Search
• What if one wants to save the time consumed in looking to each item in a collection of
items?
PROBLEM SOLVING WITH C
Searching
Introduction
Searching Algorithms
● Random Search
Linear Search
• Performs search on any kind of data
• Coding Example
PROBLEM SOLVING WITH C
Searching algorithms
Binary Search
2. Problem Statement
4. Demo of C Solution
PROBLEM SOLVING WITH C
Problem Solving: Sorting using Array of Pointers
Problem Statement
• Create a menu driven program to perform bubble sort based on roll_number and name.
Use student.csv to extract the dataset and write the sorted record to a new file.
PROBLEM SOLVING WITH C
Problem Solving: Sorting using Array of Pointers
• Creating the student type with two data members – roll_no and name
• Reading the csv file line by line
• Splitting the line based on the delimiter using strok function
• Copying the data from the data file to the data members of the student structure
• Client code requires menu driven code - Provide the option to the user to sort based on
roll_no or name
• Perform bubble sort based on the option from the user
• Create a new file using fopen and sorted record write to a new file(roll_no+name)
PROBLEM SOLVING WITH C
Problem Solving: Sorting using Array of Pointers
Demo of C Solution
• Demonstration of C Code
THANK YOU
1. Problem Statement
3. Demo of C Solution
PROBLEM SOLVING WITH C
Problem Solving: Callback
Problem Statements
• Perform Binary search on a collection of elements. Client is adding constraints every now and
then . Initial constraints to perform search are as follows.
i) Display only if the number is even
ii) Display only the number is less than 22
• Create a menu driven code to perform Bubble sort on a collection of students using an array of
pointers. Use student.csv as the data file to process. Right now there are 2 headers in this csv
file: Roll_no and Name.
Perform sort based on Roll_no
Perform fort based on Name
Anytime client might add more information about students to the data file and requirement
might change to sort based on that added info.
PROBLEM SOLVING WITH C
Problem Solving: Callback
• Create a type called student with two data members: roll_no and name
• Read csv file and copy the data to array of structures of student type
• Initialize the Array of pointers with the address of each structure in the array
• Bubble sort function must be modified to have function pointer parameter. This will be called
inside the bubble sort function based on the choice from the client/user.
• Create two function definitions separately to compare two roll_numbers and names.
• Pass these functions to the bubble sort as an argument based on the choice from the
client/user.
PROBLEM SOLVING WITH C
Problem Solving: Callback
Demo of C Solution
Qualifiers in C
1. Introduction
2. Size Qualifiers
3. Sign Qualifiers
4. Type Qualifiers
Introduction
• Keywords which are applied to the data types resulting in Qualified type
• Applied to basic data types to alter or modify its sign or size
• Types of Qualifiers
• Size Qualifiers
• Sign Qualifiers
• Type qualifiers
PROBLEM SOLVING WITH C
Qualifiers in C
Size Qualifiers
• short int <= int <=long int // short int may also be abbreviated as short and long int as long. But,
there is no abbreviation for long double.
• Coding Examples
PROBLEM SOLVING WITH C
Qualifiers in C
Sign Qualifiers
• A signed qualifier specifies a variable which can hold both positive and negative integers
• Coding Examples
PROBLEM SOLVING WITH C
Qualifiers in C
Type Qualifiers
• A way of expressing additional information about a value through the type system and
ensuring correctness in the use of the data
3. float No qualifier
4. double long
5. void No qualifier
THANK YOU
Preprocessor Directives
• Introduction
• Types of Pre-processor Directives
• Macros
• Points to know about Macros
• Predefined Macros
• Macro vs Enum
• File Inclusion Directives
• Conditional compilation Directives
• Other Directives
PROBLEM SOLVING WITH C
Preprocessor Directives
Introduction
• The lines of code in a C program which are executed by the ‘C’ pre-processor
• It must be the first nonblank character and for readability, pre-processor directive
should begin in the first column conventionally
PROBLEM SOLVING WITH C
Preprocessor Directives
• File Inclusion
• Conditional Compilation
• Other directives
• Possible to see the effect of the pre-processor on source files directly by using the -E
option of gcc
PROBLEM SOLVING WITH C
Preprocessor Directives
Macros
• Coding Examples
PROBLEM SOLVING WITH C
Preprocessor Directives
Predefined Macros
PROBLEM SOLVING WITH C
Preprocessor Directives
Macro vs Enum
• Macro doesn’t have a type and enum constants have a type int.
• Macro can be redefined using #define but enum constants cannot be redefined. However
assignment operator on a macro results in error
PROBLEM SOLVING WITH C
Preprocessor Directives
File Inclusion Directives
• Instructs the pre-processor to include a file in the program using #include directive
• Two types of files
• Header File or Standard files: Included between < and >
• Contains the definition of pre-defined functions like printf(), scanf() etc.
• To work with these functions, header files must be included
• User defined files: Included using “ and “
• When a program becomes very large, it is good practice to divide it into smaller
files and include whenever needed.
• A few blocks of code will be compiled in a particular program based on the result of some
condition
• Conditions can be mentioned using - #ifdef, #ifndef, #if, #else, #elif, #else, #endif
• Coding Examples
PROBLEM SOLVING WITH C
Preprocessor Directives
Other Directives
• After this statement every “#ifdef LIMIT” statement will evaluate to false
• #pragma startup and #pragma exit: Helps to specify the functions that are needed to run
before program startup and just before program exit
• #pragma warn: This directive is used to hide the warning messages which are displayed
during compilation using –rvl, -par and -rch
THANK YOU
• Problem Statement
• Requirements
• Demo of C Solution
PROBLEM SOLVING WITH C
Portable Program Development
Problem Statement
• Demonstrate the real use of conditional compilation and pre-defined macros. Make
the code portable across different platforms. Based on the current platform the code
is run, particular part of the code must be compiled and executed
PROBLEM SOLVING WITH C
Portable Program Development
Requirements
• Part of the code to be compiled and executed depends on the macro set or not
If mingw in windows system, the value of __MINGW32__ will be 1
If unix/Linux system is used, the value of __unix__ is 1
If mac system is used, the value of __APPLE is 1
Note that there is no {} to specify the block
No usage of ( ) to specify the macro
PROBLEM SOLVING WITH C
Portable Program Development
Demo of C Solution
• See the output of preprocessing on the terminal using gcc –E and then execute the
code
THANK YOU
In C, a pointer is a variable that stores a memory address, while an array is a collection of elements stored in contiguous memory locations . The distinction implies that while an array name acts as a constant pointer to its first element, allowing element access but not pointer arithmetic, a pointer provides more flexibility with its arithmetic operations and different allocation strategies. This has significant implications for memory management, particularly in dynamic memory allocation and data structure manipulation.
The '-Wall' option in GCC enables all the most commonly-used compiler warnings, which helps detect potential issues in the code that might not be immediately obvious . This option is recommended because it serves as an essential aid in ensuring code safety by alerting developers to potential problems that could lead to program crashes or incorrect results.
Pointer arithmetic in C allows direct manipulation of memory addresses, which can be advantageous when navigating arrays. For instance, when traversing an array, a pointer can efficiently access each element by incrementing itself. This is beneficial for performance, as operations like `*(p + i)` are equivalent to `array[i]` and allow easy iteration over elements . However, pointer arithmetic also introduces risks, such as accessing memory outside the bounds of an array, which leads to undefined behavior . For example, using `p++` in a loop to traverse an array can inadvertently move beyond the array’s end, accessing adjacent memory that may not be part of the array, leading to potential data corruption or crashes . Therefore, while pointer arithmetic can enhance performance and flexibility, it demands careful handling to avoid errors .
Multi-dimensional arrays in C are arrays with more than one level, such as two-dimensional or three-dimensional arrays, useful for representing data in tabular forms or grid layouts . They are particularly useful in scenarios requiring matrix operations, geometric transformations, image processing, and complex data storage, allowing for structured organization and efficient data retrieval.
Enhancing GCC for new features or hardware requires considering the specific needs such as supporting a new CPU architecture or programming language, ensuring that the enhancements do not introduce bugs, and potentially hiring expertise to handle complex modifications. Additionally, it is crucial to consider maintaining compatibility with existing systems and adhering to the guidelines of the GNU project .
Differentiating between compile-time and runtime in C programming is crucial because compile-time is when the source code is converted to machine code, whereas runtime is when the program is executed . Confusion between the two can lead to errors such as mismanagement of dynamically allocated memory, misconceptions about variable initialization, or misinterpretation of scope and lifetime of variables, resulting in unpredictable program behavior or crashes.
Functions in C enhance program design and maintenance by breaking down tasks into smaller, manageable units, promoting code reuse, and reducing development time. Functions act as black boxes where internal processes are hidden, simplifying debugging and enhancing program structure by allowing focus on specific tasks without altering the entire program .
In C, pointers and arrays are closely related; an array name acts as a pointer to its first element. This influences programming techniques by allowing arrays to be manipulated using pointer arithmetic, providing flexibility in data handling. However, programmers must be cautious as this relationship enables direct memory access, which can lead to errors if not managed properly .
Array traversal in C involves accessing each element of the array using both array notation and pointer arithmetic. With array notation, elements are accessed using indices, for example, `arr[i]` accesses the ith element of the array, where i is an integer index starting from 0 . Pointer arithmetic provides an alternative way where pointers can traverse the array. When a pointer points to an array, incrementing the pointer (`p++`) moves it to the next element in the array. This can be achieved using expressions like `*(p+i)`, `p[i]`, or even `i[p]` which is equivalent to `*(arr+i)` when `p` is assigned to `arr` . Pointer arithmetic allows addition or subtraction of integers from pointers, which effectively moves the pointer by that many elements, making it possible to navigate through the array without using indices explicitly . Furthermore, both array notation and pointer arithmetic treat array names as pointers to their first element at run-time, highlighting their interchangeability within C programs . Being aware of the array bounds is crucial since accessing outside these bounds can lead to undefined behavior .
The memory address of an array element in C can be calculated using the formula: Address of ith element = Base address + (size of each element * i). For a two-dimensional array, the address of element A[i][j] is calculated as: Address = Base_Address + ((i * number of columns in every row) + j) * size of each element . Using these formulas allows efficient access to array elements and supports operations like traversal and manipulation through pointers, as the name of the array acts as a pointer to its first element . However, caution is needed; accessing elements outside the declared bounds results in undefined behavior, which can lead to runtime errors .