0% found this document useful (0 votes)
48 views460 pages

C Slides

The document outlines a course on Problem Solving with C, detailing the programming language's features, history, and applications. It covers the programming environment, including installation of gcc, program structure, and the development life cycle. The syllabus includes topics such as data types, sorting, searching, and file handling, aiming to equip students with the skills to solve logical problems using C programming.

Uploaded by

kafogif591
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views460 pages

C Slides

The document outlines a course on Problem Solving with C, detailing the programming language's features, history, and applications. It covers the programming environment, including installation of gcc, program structure, and the development life cycle. The syllabus includes topics such as data types, sorting, searching, and file handling, aiming to equip students with the skills to solve logical problems using C programming.

Uploaded by

kafogif591
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 460

Problem Solving With C - UE24CS151B

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)

2. Why PLs? and why so many PLs ?

3. Brief introduction on Paradigms

4. First Programmer

5. Why C after Python?

6. Applications of C

7. History of PLs and Development of C

8. Features of C
PROBLEM SOLVING WITH C
Introduction

What is Programming Language(PL)?


● Formal computer language or constructed language designed to
communicate instructions to a machine, particularly a computer (wiki
defn)
● A way of telling a machine what operations to perform
● Can be used to create programs to control the behavior of a machine or
to express algorithms

Why PLs and why so many PLs?


● To choose the right language for a given problem
● Applications
● Web Browsers, Social Networks, Image Viewer
● Facebook.com, Bing, Google.com, Games
● Various OS
PROBLEM SOLVING WITH C
Introduction

Paradigm – Style of Programming

● 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

First Programmer – Ada Lovelace


PROBLEM SOLVING WITH C
Introduction

Why C after Python ?


• Paradigms - Procedural vs OOP
• Aged compared to Python
• Growth rate of PLs - TIOBE Index
PROBLEM SOLVING WITH C
Introduction

Best Applications of C/C++

❖ Linux Kernel: It is written in C


❖ Adobe Systems: Includes Photoshop and Illustrator
❖ Mozilla: Internet Browser Firefox Uses C++.
❖ Bloomberg: Provides real time financial information to investors
❖ Callas Software: Supports PDF creation, optimization, updation tools and plugins
❖ Symbian OS: Used in cellular phones.
PROBLEM SOLVING WITH C
Introduction
History of PLs
● 1820-1850 England, Charles Babbage invented two mechanical Computational device i.e., Analytical
Engine and Difference Engine
● In 1942, United States, ENIAC used electrical signals instead of physical motion
● In 1945, Von Newmann developed two concepts: Shared program technique and Conditional control
transfer
● In 1949, Short code appeared
● In 1951, Grace Hopper wrote first compiler, A-0
● Fortran: 1957, John Backus designed.
● Lisp, Algol- 1958
● Cobol: 1959
● Pascal: 1968, Niklaus Wirth
● C: 1972, D Ritchie
● C++: 1983, Bjarne Stroustrup, Compile time type checking, templates are used.
● Java: 1995, J. Gosling, Rich set of APIs and portable across platform through the use of JVM
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

● Standardized by the ANSI [American National Standards Institute] since


1989 and subsequently by ISO[International Organization for
Standardization].
● C89, C99, C11
PROBLEM SOLVING WITH C
Introduction

FYK

• Charles Babbage – Father of Computer

• Dennis Ritchie

• Brian Kernighan
PROBLEM SOLVING WITH C
Introduction

Features of C
THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
C Programming Environment
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
C Programming Environment

1. Installation of gcc on different Operating systems

2. Program Development Life Cycle [PDLC]

3. First Program in C

4. Structure of C Program

5. Steps involved in execution of C Program

6. C Compiler standards

7. Errors during execution


PROBLEM SOLVING WITH C
C Programming Environment

Installation of gcc on different Operating systems


● Windows OS – Installation of gcc using Mingw.
● https://www.youtube.com/watch?v=sXW2VLrQ3Bs

● Linux OS – gcc available by default


PROBLEM SOLVING WITH C
C Programming Environment

Program Development Life Cycle [PDLC]

Fig 1: Phases involved in PDLC


PROBLEM SOLVING WITH C
C Programming Environment

First Program in C
#include<stdio.h>
int main()
{
printf(“Hello PES\n”);
return 0;
}

//Importance of int main and return values


PROBLEM SOLVING WITH C
C Programming Environment

Program Structure

● Case sensitive

● Indentation is not a language requirement

● The main() is the starting point of execution

● Comments in C
● Using // for single line comment
● Using /* and */ for multiline comment
PROBLEM SOLVING WITH C
C Programming Environment

Steps involved in execution of code

Way 1:
Step1: gcc <filename> // image a.out is the output
Step2: ./a.out OR a.exe

Way 2: Creating the object files separately


Compile: gcc -c <filename> // filename.o is the output
Link: gcc filename.o OR gcc <list of object files> -l <library>
Execute: ./a.out OR a.exe

Way 3: Renaming the object files


Step1: gcc <filename> -o <imagename>
Step2: <imagename>
PROBLEM SOLVING WITH C
C Programming Environment

C Compiler standards

Standardized by ANSI and ISO: C89, C99 and C11

Using c99:
gcc -std=c99 program.c

Using c11:
gcc -std=c11 program.c

Use __STDC_VERSION__ we can get the standard C version


PROBLEM SOLVING WITH C
C Programming Environment

Errors during Execution

• Compile time Error


• Link time Error
• Run time Error
• Logical Error

// One Example on each of these


THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


UE24CS151B: Problem Solving with C - Introduction
for B.Tech Second Semester A & N Section - EC Campus
Lecture Slides - Slot #4, #5, #6

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

Unit II: Counting, Sorting and Searching – 14 Hours - 18 Slots


Arrays–1D and 2D, Pointers, Pointer to an array, Array of pointers, Functions, Call back, Storage classes, Recursion,
Searching, Sorting

Unit III: Text Processing and User-Defined Types - 14 Hours - 18 Slots


Strings, String Manipulation Functions & Error handling, Command line arguments, Dynamic Memory Management
functions & Error handling, Structures, #pragma, Array of Structures, Pointer to structures, Passing Structure and Array
of structure to a function, Bit fields, Unions, Enums, Lists, Stack, Queue, Priority Queue.

Unit IV: File Handling and Portable Programming – 14 Hours – 18 Slots


File IO using redirection, File Handling functions of C, Searching, Sorting, Header files, Comparison of relevant User
defined and Built-in functions, Variable Length Arguments, Environment variables, Preprocessor Directives,
Conditional Compilation.

2 of 39
UE24CS151B: Problem Solving with C - Course Objectives
The objective(s) of this course is to make students

● CObj1: Acquire knowledge on how to solve relevant and logical problems


using computing machine

● CObj2: Map algorithmic solutions to relevant features of C programming


language constructs

● CObj3: Gain knowledge about C constructs and its associated ecosystem

● 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

● CO1: Understand and apply algorithmic solutions to counting problems using


appropriate C constructs

● CO2: Understand, analyse and apply Sorting and Searching techniques

● 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

● GNU stands for GNU's not Unix

● 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 also supports microcontrollers, DSPs and 64-bit CPUs

● 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 has multiple language frontends, for parsing different languages

● 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.

● If we need support for a new type of CPU, a new language, or a new


feature we can add it ourselves, or hire someone to enhance gcc for us,
in addition we can hire someone to fix a bug if it is important for our
work 12 of 39
UE24CS151B : PSWC: Unit 1 - gcc for c programming
● c is one those languages that allow direct access to the computer’s memory.

● Historically, c has been used for writing low-level systems software, and applications
where high performance or control over resource usage are critical

● Great care is required to ensure that memory is accessed correctly, to avoid


corrupting other data-structures whenever one uses c language for programming

● 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.

● They are a safer alternative to c and c++ for many applications


13 of 39
UE24CS151B : PSWC: Unit 1 - Compiling a c program using gcc
● c programs can be compiled from a single source file or from
multiple source files, and may use system libraries and header
files

● Compilation refers to the process of converting a program


from the textual source code, in a programming language such
as c into machine code, the sequence of 1’s and 0’s used to
control the central processing unit (CPU) of the computer.

● Machine code is then stored in a file known as an executable


file, sometimes referred to as a binary file
14 of 39
UE24CS151B : PSWC: Unit 1 - Compiling a c program using gcc
● gcc -Wall PESU.c -o PESU

● 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.

● Compiler warnings are an essential aid in detecting problems when programming in c

● 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

● The compiler distinguishes between error messages, which prevent successful


compilation, and warning messages which indicate possible problems but do not stop
the program from compiling

● It is very dangerous to develop a program without checking for compiler warnings.

● 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.

● ‘<filename>.o’ contains a reference to the external function <filename>, but


the corresponding memory address is left undefined in the object file at this
stage, which will be filled in later by linking

● 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

● For example, a header file found in ‘/usr/local/include’ takes precedence over


a file with the same name in ‘/usr/include’.

● Similarly, a library found in ‘/usr/local/lib’ takes precedence over a library with


the same name in ‘/usr/lib’

● When additional libraries are installed in other directories it is necessary to


extend the search paths, in order for the libraries to be found.

● 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.

● Most ANSI/ISO programs will compile under GNU C without changes

○ gcc -Wall -ansi <filename.c>


○ gcc -Wall <filename.c>

● 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

● gcc -Wall -ansi -pedantic <filename.c>

● The following options are a good choice for finding problems in C programs

○ gcc -ansi -pedantic -Wall -W -Wconversion -Wshadow -Wcast-qual


-Wwrite-strings

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

○ the state or condition of being wrong in conduct or judgement

○ a measure of the estimated difference between the observed or


calculated value of a quantity and its true value

● Preprocessor Error

○ #error is a preprocessor directive in c which is used to raise an


error during compilation and terminate the process
20 of 39
UE24CS151B : PSWC: Unit 1 - Errors
● Compile time Error

○ When the programmer does not follow the syntax


of any programming language, then the compiler
will throw the Syntax Error, such errors are also
called Compile Time Error

○ Syntax Errors are easy to figure out because the


compiler highlights the line of code that caused the
error.
21 of 39
UE24CS151B : PSWC: Unit 1 - Errors
● Linker Error

○ Linker is a program that takes the object files generated by the


compiler and combines them into a single executable file.

○ 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.

○ We can run into a linked error if we have imported an incorrect header


file in the code
22 of 39
UE24CS151B : PSWC: Unit 1 - Errors
● Runtime Error

○ Errors that occur during the execution (or running) of


a program are called Runtime Errors. These errors
occur after the program has been compiled and
linked successfully.

○ When a program is running, and it is not able to


perform any particular operation, it means that we
have encountered a runtime error.
23 of 39
UE24CS151B : PSWC: Unit 1 - Errors
● Logical Error

○ 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.

○ These types of errors are called Logical Errors.

● 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.

● The unformatted input-output functions further have two categories:

■ The character functions

○ 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.

● The unformatted input-output functions further have two categories:

■ The string functions

○ 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.

○ % [flags] [field_width] [.precision] conversion_character where components in brackets [] are


optional.

○ The minimum requirement is % and a conversion character (e.g. %d)


■ %d, %x, %o, %f, %c, %p, %lf, %s
28 of 39
UE24CS151B : PSWC: Unit 1 - keywords in c language
There are
32
keywords
in c
Language

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.

● Runtime is the period of


time when a program is
running and generally
occurs after compile time
30 of 39
UE24CS151B : PSWC: Unit 1 - Compile time and Runtime in c
Language

31 of 39
UE24CS151B : PSWC: Unit 1 - sizeof operator in c Language
● The sizeof operator is the most common operator in C.

● It is a compile-time unary operator and is used to compute the size of its


operand.

● It returns the size of a variable.

● 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.

● There are four types of literals that exist in c programming:

■ Integer literal

● It is a numeric literal that represents only integer type values.


● It represents the value neither in fractional nor exponential part.
● It can be specified in the following three ways
○ Decimal number (base 10)
■ It is defined by representing the digits between 0 to 9. Example: 1,3,65 etc

○ Octal number (base 8)


■ It is defined as a number in which 0 is followed by digits such as 0,1,2,3,4,5,6,7.
Example: 032, 044, 065, etc

○ Hexadecimal number (base 16)


■ It is defined as a number in which 0x or 0X is followed by the hexadecimal digits
(i.e., digits from 0 to 9, alphabetical characters from (a-f) or (A-F)) Example 0XFE
33 of 39
oxfe
UE24CS151B : PSWC: Unit 1 - Literals and Constants in c Language
● Literals are the constant values assigned to the constant variables.

■ 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.

● The floating-point literal must be specified either in decimal or in exponential form.

○ 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.

■ Example: +9.5, -18.738


34 of 39
UE24CS151B : PSWC: Unit 1 - Literals and Constants in c Language
● Literals are the constant values assigned to the constant variables.

■ Float literal
● The floating-point literal must be specified either in decimal or in
exponential form.

○ Exponential form

■ The exponential form is useful when we want to represent the


number, which is having a big magnitude.

■ It contains two parts, i.e., mantissa and exponent.

■ For example, the number is 3450000000000, and it can be


expressed as 3.45e12 in an 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.

● The floating-point literal must be specified either in decimal or in exponential form.

○ Exponential form
■ Syntax of float literal in exponential form
● [+/-] <Mantissa> <e/E> [+/-] <Exponent>

■ Examples of real literal in exponential notation are


● +3e24, -7e3, +3e-15

■ Rules for creating an exponential notation


● In exponential notation, the mantissa can be specified either in decimal or
fractional form

● An exponent can be written in both uppercase and lowercase, i.e., e and E.

● 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.

● Representation of character literal

○ A character literal can be represented in the following ways:


● It can be represented by specifying a single character within single quotes. For
example, 'x', 'y', etc.

● We can specify the escape sequence character within single quotes to


represent a character literal. For example, '\n', '\t', '\b'.

● We can also use the ASCII in integer to represent a character literal. For
example, the ascii value of 65 is 'A'.

● The octal and hexadecimal notation can be used as an escape sequence to


represent a character literal. For example, '\043', '\0x22'. 37 of 39
UE24CS151B : PSWC: Unit 1 - Literals and Constants in c Language
● Literals are the constant values assigned to the constant variables.

■ String Literal

● A string literal represents multiple characters enclosed


within double-quotes

● It contains an additional character, i.e., '\0' (null


character), which gets automatically inserted.

● This null character specifies the termination of the


string.
38 of 39
UE24CS151B
End of Slot #4, #5, #6
THANK YOU

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

2. Variable declaration, definition and initialization

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.

● Starts with a letter A to Z, a to z, or an underscore '_' followed by zero


or more letters, underscores, and digits (0 to 9)

● C does not allow few punctuation characters such as #, @ and %


within identifiers
PROBLEM SOLVING WITH C
Variables and Data Types

Variable declaration, definition and initialization


● Variable is a name given to a storage area that a code can
manipulate

● Has a name, location, type, life, scope and qualifiers

● Variable declaration and definition: int a; //An uninitialized variable


has some undefined value. A variable can be assigned a value later
in the code

● Variable initialization: int a = 10;


PROBLEM SOLVING WITH C
Variables and Data Types

Keywords
● Are identifiers which have special meaning in C.

● Cannot be used as constants or variables

● Few here: auto, else, long, switch, break, enum, case, extern, return
char, float, for, void, sizeof, int, double …

● int auto = 10; // Error


PROBLEM SOLVING WITH C
Variables and Data Types

Data Types
● The amount of storage to be reserved for the specified variable.

● Significance of types: Memory allocation, Range of values allowed, Operations bound to


this type, Type of data to be stored

● Categories: Primary → int, float, double and char


Secondary → Derived(Arrays) and User defined(struct, enum, union and typedef)

● sizeof(short int)<=sizeof(int)<=sizeof(long int)<=sizeof(long long int)<=


sizeof(float)<=sizeof(double)<=sizeof(long double)

● Coding examples on Range of values using limits.h


THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Qualifiers in C
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Qualifiers in C

1. Introduction

2. Size Qualifiers

3. Sign Qualifiers

4. Type Qualifiers

5. Applicability of Qualifiers to Basic Types


PROBLEM SOLVING WITH C
Qualifiers in C

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

• Prefixed to modify the size of a data type allocated to a variable

• Supports two size qualifiers, short and long

• Rules Regarding size qualifier as per ANSI C standard

• 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

• Used to specify the signed nature of integer types

• It specifies whether a variable can hold a negative value or not

• Sign qualifiers are used with int and char types

• There are two types of Sign Qualifiers in C. Signed and Unsigned

• A signed qualifier specifies a variable which can hold both positive and negative integers

• An unsigned qualifier specifies a variable with only positive 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

• Type Qualifiers consists of two keywords


• const
• volatile.
PROBLEM SOLVING WITH C
Qualifiers in C

Type Qualifiers continued..


• const:
• Once defined, their values cannot be changed.
• Called as literals and their values are fixed.
• Syntax: const data_type variable_name
• volatile:
• Intended to prevent the compiler from applying any optimizations
• Their values can be changed by code outside the scope of current code at any time
• Also can be changed by any external device or hardware
• Syntax: volatile data_type variable_name
• Coding Examples
PROBLEM SOLVING WITH C
Qualifiers in C
Applicability of Qualifiers to Basic Types

No. Data Type Qualifier


1. char signed, unsigned

2. int short, long, signed, unsigned

3. float No qualifier

4. double long

5. void No qualifier
THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Simple Input/Output
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Simple Input/Output

1. Formatted output function

2. Formatted input function

3. Unformatted functions
PROBLEM SOLVING WITH C
Simple Input/Output

Formatted output function – printf()


● 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
● Coding examples
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).

● %d, %x, %o, %f, %c, %p, %lf, %s

● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output

Escape sequences
● Represented by two key strokes and represents one character

● \n, \t, \r, \a, \”, \’, \\, \b

● Coding examples
PROBLEM SOLVING WITH C
Simple Input/Output

Formatted input function – scanf()


● int scanf(const char *format, ...)
● Predefined function in stdio.h
● & : Address operator is compulsory in scanf for all primary types
● Reads formatted input using stdin. By default keyboard
● This function returns the following value
● >0 — The number of items converted and assigned successfully.
● 0 — No item was assigned.
● <0 — Read error encountered or end-of-file (EOF) reached before any
assignment was made
● 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

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Operators in C
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Operators in C

1. Operators and its Classification

2. Expression

3. Sequence point operation


PROBLEM SOLVING WITH C
Operators in C

Operator and its Classification


● Operator is a symbol used for calculations or evaluations
● Has rank, precedence and Associativity
● Classification: Based on the operation:
Arithmetic – Increment(++) & Decrement(--)
Relational - >, <, <=, >=, ==, !=
Logical(short circuit evaluation) - &&, ||, !
Bitwise - &, |, ~, ^, <<, >>
Address - &
Dereferencing Operator - *
Based on the operands: Unary, Binary, Ternary
PROBLEM SOLVING WITH C
Operators in C

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

Sequence point Operation


● Specifies points in the code beyond which all side effects will definitely be
complete

● Beyond this, any variable can be used with no ambiguity

● Coding examples with &&


THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Control Structures
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Control Structures

1. Selection structures

2. Looping structures

3. Nested Control 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>

▪ If – else if – else if – else ▪ Coding Examples


if (e1)

<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

Nested Control structures

▪ One loop may be inside another

▪ One if may be inside another: inner if is reached only if the Boolean condition of the outer if is
true

▪ Combination of above two

▪ Coding Examples
PROBLEM SOLVING WITH C
Control Structures

Practice Programs

▪ WAP to count the number of digits in a given integer.

▪ 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

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Single character Input Output
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Single character Input Output

Few points to discuss !!

 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

 Character refers to a single input - Occupies a single byte.


 English alphabets A as 65, B as 66, Z as 90, a as 97 and so on in a coding scheme called
ASCII.
 C treats all the devices as files. Following three files are automatically opened when a
program executes to provide access to the keyboard and screen.
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

 Approaches: Non-standard IO functions


 getch() and getche() - Reads a character from the keyboard and copies it into
memory area. getch() function, the typed character will not be echoed(displayed)
on the screen and in getche() function the typed character will be
echoed(displayed) on the screen.
 putch() - Outputs a character stored in the memory using a variable on the
output screen.
 Coding examples
THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]
Problem Solving With C - UE24CS151B
Language Specifications/Behaviors
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Language Specifications/Behaviors

1. Language Specification

2. Standards

3. Behaviors defined by C Standards

4. Undefined Behavior in detail


PROBLEM SOLVING WITH C
Language Specifications/Behaviors

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.

▪ Can take several forms:


An explicit definition of the syntax and semantics of the language.
A description of the behavior of a "translator” for the language
“Model implementation” is a program that implements all
requirements from a corresponding specification
PROBLEM SOLVING WITH C
Language Specifications/Behaviors

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

Behaviors defined by C Standards

• Locale-specific behavior - Not discussed here

• Unspecified behavior - Order of evaluation of arguments in printf function

• Implementation-defined behavior – Size of each type

• Undefined behavior in detail


PROBLEM SOLVING WITH C
Language Specifications/Behaviors

Undefined Behavior in detail


▪ The result of executing a program whose behavior is prescribed to be unpredictable
in the language specification to which the computer code adheres.

▪ It is the name of a list of conditions that the program must not meet.

▪ Examples: Memory access outside of array bounds, Signed integer overflow

▪ 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

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
C Standards and Guidelines
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
C Standards and Guidelines

Why Follow Standards and Guidelines to code in C?


• Ensures readability and maintainability of code.

• Reduces debugging and development time, especially when multiple developers are
working on the same code.

• Promotes consistency in code formatting.

• In certain cases, even improves the runtime and security of your code.
PROBLEM SOLVING WITH C
C Standards and Guidelines

Standards and Best Practices


• Consistent Formatting
• Naming Conventions
• Commenting and Documentation
• Header File Practices
• Avoidance of Undefined Behavior
• Error Handling
• Memory Management
• Maintain Modularity
• Security Practices
• Portability & Standards Compliance
• Static Analysis & Testing
• Established Guidelines/Standards
PROBLEM SOLVING WITH C
C Standards and Guidelines

Code Formatting Guidelines


• Use indentation: 2-4 spaces per level, no tabs1. Tabs are avoided as a standard practice
since different editors and IDEs can display/process tabs differently.
• Follow a uniform brace style
• Keep lines to a reasonable length for readability - Avoid long lines (greater than 80
characters)1.
Naming Conventions
• Use meaningful and descriptive names for variables and function names.
• Use consistent naming patterns (e.g., snake_case for functions/variables, UPPER_CASE for
macros)
1 - Source: https://google.github.io/styleguide/cppguide.html
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.

Header file Practices


• Use include guards (#ifndef, #define, #endif) to avoid multiple inclusions
• Separate declarations (in headers) from implementations (in source files)
PROBLEM SOLVING WITH C
C Standards and Guidelines

Avoidance of Undefined Behaviour


• Write code that avoids undefined behaviors (e.g., out-of-bounds access, null pointer
dereferences)
• Validate assumptions and inputs rigorously

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

Efficient Memory Management


• Always initialise pointers2.

• Do not dereference NULL pointers.


• Ensure every memory allocation (malloc(), calloc()) is paired with a corresponding free() =>
Avoid any memory leaks by always freeing dynamically allocated memory2.
• Employ cleanup techniques to avoid resource mismanagement
• Use static/global variables only if absolutely necessary. Use local variables wherever
possible.

2 - Sources: https://docs.microsoft.com/en-us/security/; https://wiki.sei.cmu.edu/confluence/display/c/SEI+CERT+C+Coding+Standard


PROBLEM SOLVING WITH C
C Standards and Guidelines

Maintain Modularity

• Decompose code into small, reusable functions


• Limit the scope of variables (using static for file-local scope) to reduce complexity
• Use functions to avoid redundant segments of code throughout the program.

• Keep all functions short, modular, and primarily focused on a single purpose3.

• Use short and informative comments without being redundant.

• Use ‘const’ and ‘#define’ for constant values being used4.

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.

Portability and Standards Compliance


• Adhere to a specific C standard (e.g., C99, C11) to maximize portability.
• Avoid platform-specific behavior; use conditional compilation when needed.
PROBLEM SOLVING WITH C
C Standards and Guidelines

Static Analysis and Testing

• Enable compiler warnings to catch potential issues early


• Use static analysis tools to identify bugs and security vulnerabilities
• Write unit tests for critical functions to ensure reliability

Following Established Standards


• Consider industry standards like MISRA C or the CERT C Secure Coding Standard for safety-
critical projects
• Adhere to project-specific coding guidelines for consistency and quality
THANK YOU
Department of Computer Science and Engineering

Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant – Advaith Sanil Kumar


Problem Solving With C - UE24CS151B
Arrays, Initialization and Traversal
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Arrays, Initialization and Traversal

1. What is an Array?

2. Properties of Arrays.

3. Classification of Arrays

4. Definition and Initialization

5. Representation of the Array

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.

 char c_array [10]; short s_array [20];


PROBLEM SOLVING WITH C
Arrays, Initialization and Traversal

Properties of Arrays

• Non-primary data type or secondary data type


• Memory allocation is contiguous in nature
• Elements need not be unique.
• Demands same /homogenous types of elements
• Random access of elements in array is possible
• Elements are accessed using index/subscript
• Index or subscript always start from 0
• Memory is allocated at compile time.
• Size of the array is fixed at compile time. Returns the number of bytes occupied by the array.
• Cannot change the size at runtime.
• Arrays are assignment incompatible.
• Accessing elements of the array outside the bound can have undefined behavior at runtime
PROBLEM SOLVING WITH C
Arrays, Initialization and Traversal

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

Definition and Initialization

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

Declaration and Initialization

Initialization

• After an array is declared, it must be initialized.


• An array can be initialized at either compile time or at runtime.

Compile time Initialization Runtime Initialization


• data-type array-name[size] = { list of values }; • Using a loop and input function in C
• Coding examples
• float area[5]={ 23.4, 6.8, 5.5 }; // Partial initialization
• int a[15] = {[2] = 29, [9] = 7, [14] = 48}; //C99’s designated initializers
• int a[15] = {0,0,29,0,0,0,0,0,0,7,0,0,0,0,48}; //C99’s designated initializers

• int arr[] = {2, 3, 4}; // sizeof arr is decided


• int marks[4]={ 67, 87, 56, 77, 59 }; // undefined behavior
• Coding Examples
PROBLEM SOLVING WITH C
Arrays, Initialization and Traversal

Representation of the Array

• int a[6]; Memory Location


• int a[6] = {20, 10, 50, 22, 75,16}; a 200 204 208 212 216 220
200 X X X X X X
• Address of the first element is called the Base address 0 1 2 3 4 5
of the array. Index

• Address of ith element of the array can be found


using formula: Memory Location
Address of ith element = Base address + (size of each a 200 204 208 212 216 220
element * i) 200
20 10 50 22 75 16

0 1 2 3 4 5
Index
PROBLEM SOLVING WITH C
Arrays, Initialization and Traversal

Traversal

• Accessing each element of the array

• 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

• Anytime accessing elements outside the array bound is an undefined behavior

• Coding examples
THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]
Dr. Saritha, CSE, PESU

Ack: Teaching Assistant - U Shivakumar


PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Multi-Dimensional Arrays

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Agenda

1. Introduction

2. Two-Dimensional Array: Declaration

3. Two Dimensional Array: Initialization

4. Internal Representation of a 2D Array

5. Pointer and 2D Array

6. Passing 2D array to a function

7. Three Dimensional (3D) Array


PROBLEM SOLVING WITH C
Multi-Dimensional Arrays

Introduction
• An array with more than one level or dimension.
• 2-Dimensional and 3-Dimensional and so on.

General form of declaring N-dimensional arrays:


Data_type Array_name[size1][size2][size3]..[sizeN];
PROBLEM SOLVING WITH C
Multi-Dimensional Arrays

Two – Dimensional Array

• Treated as an array of arrays.


• Every element of the array must be of same type as arrays are homogeneous
Declaration
Syntax: data_type array_name[size_1][size_2]; // size_1 and size_2 compulsory
int arr[4][2];
X is undefined value
arr
2000 2004 2008 2012 2016 2020 2024 2028

xx x x x xx x xx x
PROBLEM SOLVING WITH C
Multi-Dimensional Arrays

Two – Dimensional Array

Initialization

• data_type array_name[size_1][size_2] = {elements separated by comma};

• int arr[][] = {11,22,33,44,55,66}; // Error. Column size is compulsory


• int abc[3][2] ={{11,22},{33,44},{55,66}};//valid
• int arr[][2] = {11, 22, 33 ,44,55,66 } ;//valid. Allocates 6 contiguous memory locations and
assign the values
• int arr[][3] = {{11,22,33},{44,55},{66,77}}; // partial initialization
PROBLEM SOLVING WITH C
Multi-Dimensional Arrays

Internal Representation of a 2D Array


• 2D Array itself is an array, elements are stored in contiguous memory locations.
Consider, int arr[3][4] = {{11, 22, 33, 44}, {55, 66, 77, 88}, {99, 100, 111, 121}};
• Row major Ordering: All elements of one row are followed by all elements of the next row and
so on.

• Column Major Ordering: All elements of one column are followed by all elements of the next
column and so on.

• Generally, systems support Row Major Ordering.


PROBLEM SOLVING WITH C
Multi-Dimensional Arrays

Address of an Element in a 2D Array

• 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

• To read and display a 2D Array


PROBLEM SOLVING WITH C
Multi-Dimensional Arrays

Pointer and 2D Array

• Pointer expression for a[i][j] is *(*(a + i) + j)

• Array name is a pointer to a row.

• (a + i) points to ith 1-D array.

• *(a + i) points to the first element of ith 1D array

• Coding examples
PROBLEM SOLVING WITH C
Multi-Dimensional Arrays

Pointer and 2D Array continued..

• 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

Pointer and 2D Array continued..

• int *p = arr; // assigning the 2D array to a pointer results in warning

• Using p[5] results in 66. But p[1][1] results in error. p doesn’t know the size of the column.

• Solution is to create a pointer to an array of integers.

int (*p)[4] = arr; //subscript([ ]) have higher precedence than indirection(*)

• Think about the size of p and size of *p!!


PROBLEM SOLVING WITH C
Multi-Dimensional Arrays

Passing 2D array to a function

• Read and display 2D array using functions

• 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

Three Dimensional (3D) Array

• Accessing each element by using three subscripts

• 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.

2.Program to find the transpose of a given matrix.

3.Program to find the inverse of a given matrix.

4.Write a function to check whether the given matrix is identity matrix or not.

5. Write a program in C to find sum of right diagonals of a matrix.

6. Write a program in C to find sum of rows and columns of a matrix


THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
Problem Solving With C - UE24CS151B
Pointers
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Pointers

1. What is a Pointer?

2. Declaration and Initialization

3. Arithmetic operations on Pointer

4. Array Traversal using pointers

5. Array and Pointer


PROBLEM SOLVING WITH C
Pointers

What is a Pointer?
• A variable which contains the address. This address is the location of another object in the
memory

• Used to access and manipulate data stored in memory.

• Pointer of particular type can point to address of any value in that particular type.

• Size of pointer of any type is same/constant in that system

• Not all pointers actually contain an address


Example: NULL pointer // Value of NULL pointer is 0.

• Pointer can have three kinds of contents in it


• The address of an object, which can be dereferenced.
• A NULL pointer
• Undefined value // If p is a pointer to integer, then – int *p;
PROBLEM SOLVING WITH C
Pointers

Declaration and Initialization

Declaration Syntax: Data-type *name; Example code:


• int *p; int *p; // p can point to anything where integer is
• Compiler assumes that any address stored. int* is the type. Not just int.
that it holds points to an integer type. int a = 100;
• p= &sum; p=&a;
• Memory address of sum variable is printf("a is %d and *p is %d", a,*p);
stored into p.

2000 p a
2000 100
2000
sum p
PROBLEM SOLVING WITH C
Pointers

Pointer Arithmetic Operations

1. Add an int to a pointer

2. Subtract an int from a pointer

3. Difference of two pointers when they point to the same array.

Note: Integer is not same as pointer.

• Coding examples
PROBLEM SOLVING WITH C
Pointers

Pointer Arithmetic Operations continued..

Example Code: 0022FF69


int *p, x = 20; x 20 0022FF70 p
p = &x; 0022FF71
printf("p = %p\n", p);
0022FF72
printf("p+1 = %p\n", (int*)p+1);
printf("p+1 = %p\n", (char*)p+1); 0022FF73
printf("p+1 = %p\n", (float*)p+1);
0022FF74
printf("p+1 = %p\n", (double*)p+1);
Sample output: 0022FF75
p = 0022FF70 0022FF76
p+1 = 0022FF74 0022FF77
0022FF78
p+1 = 0022FF71
0022FF79
p+1 = 0022FF74
p+1 = 0022FF78 Memory
Address
PROBLEM SOLVING WITH C
Pointers

Array Traversal using Pointers

Consider int arr[] ={12,44,22,33,55}; int *p = arr; int i;

Coding examples to demo below points


• Array notation. Index operator can be applied on pointer.
• Pointer notation
• Using *p++
• Using *++p, Undefined behavior if you try to access outside bound
• Using (*p)++
• Using *p and then p++
PROBLEM SOLVING WITH C
Pointers

Array and Pointer

• An array during compile time is an actual array but degenerates to a constant


pointer during run time.

• 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

• An array is a constant pointer. It cannot point to anything in the world


PROBLEM SOLVING WITH C
Pointers

Array and Pointer continued..

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

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]
Dr. Saritha, CSE, PESU

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Array of Pointers
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Array of Pointers

• Introduction

• Demo of C Code
PROBLEM SOLVING WITH C
Array of Pointers

Introduction

• Is an indexed set of variables in which the variables are pointers


Syntax: int *var_name[array_size];
Example: int *p[100];
• The element of an array of a pointer can be initialized by assigning the address of other
element. Example : int a = 10; p[1] = &a; 5000 5004 5008 5012 -- - -- -- -- --
p X X7000 X X --
- -- -- -- -- --
0 1 2 3 -- -- -- - 99
10 -
a
7000
X-Undefined

• 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

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]
Problem Solving With C - UE24CS151B
Functions
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Functions

1. Introduction to functions

2. Types of Functions

3. Function Definition, Call and Declaration

4. Usage of return keyword

5. Parameter passing in C
PROBLEM SOLVING WITH C
Functions

Introduction

• A sub-program to carry out a specific task


• Functions break large computing tasks into smaller ones.
• Enable people to build on what others have done instead of starting from
scratch
• Benefits:
• Reduced Coding Time – Code Reusability
• Divide and Conquer - Manageable Program development
• Reduced Debugging time
• Treated as a black box - The inner details of operation are invisible to rest of the
program
PROBLEM SOLVING WITH C
Functions

Types of Functions

• Standard Library Functions


Must Include appropriate header files to use these functions.
Already declared and defined in C libraries
printf, scanf, etc..

• User Defined functions


Defined by the developer at the time of writing program
Developer can make changes in the implementation
PROBLEM SOLVING WITH C
Functions

Function Definition, Call and Declaration


Function Definition
• Provides actual body of the function

• Function definition format


return-type function-name( parameter-list )
{
declarations and statements
}

• Variables can be declared inside blocks

• Coding examples
PROBLEM SOLVING WITH C
Functions

Function Definition, Call and Declaration


Function Call
• Function can be called by using function name followed by list of arguments (if any) enclosed
in parentheses

• Function call format


function-name(list of arguments);

• The arguments must match the parameters in the function definition in it’s type, order and
number.

• Multiple arguments must be separated by comma. Arguments can be any expression in C

• Coding examples
PROBLEM SOLVING WITH C
Functions

Function Definition, Call and Declaration


Function Declaration/ Prototype
• All functions must be declared before they are invoked or called.
• Function can be declared by using function name followed by list of parameters (if any)
enclosed in parentheses
• Function declaration format
return_type function_name (parameters list);

• Use of identifiers in the declaration is optional.


• The parameter names do not need to be the same in declaration and the function definition.
• The types must match the type of parameters in the function definition in number and order.
• Coding examples
PROBLEM SOLVING WITH C
Functions

Usage of return keyword


• return statement provides the means of exiting from a function and resuming execution of the calling function at
the point from which the call occurred

• General form of return statement is


return expression;

• 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

• Parameter passing is always by value in C


• Argument is copied to the corresponding parameter.
• Argument is not affected if we change the parameter inside a function.
• The formal parameter is not copied back to the actual argument. Possible only if the
actual argument is l - value.
• Coding examples
THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Arrays and Functions
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Arrays and Functions

1. Passing an Array to a function

2. Array as a Formal parameter and actual parameter

3. Pointer as a Formal parameter and Array as an Actual parameter

4. Usage of const keyword

5. Passing individual array element to a function


PROBLEM SOLVING WITH C
Arrays and Functions

Passing an Array to a function

• When array is passed as an argument to a function, arguments are copied to


parameters of the function and parameters are always pointers.

• Array degenerates to a pointer at runtime.

• All the operations that are valid for pointer will be applicable for array too in the
body of the function.

• Function call happens always at run time.


PROBLEM SOLVING WITH C
Arrays and Functions

Array as a formal parameter and Actual parameter

• Array being formal parameter - Indicated using empty brackets in the


parameter list.
void myfun(int a[],int size);

• 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);

• Coding example to read and display the array elements


PROBLEM SOLVING WITH C
Arrays and Functions

Pointer as a formal parameter and Array as an Actual parameter

• Pointer being formal parameter - Indicated using empty brackets in


the parameter list.
void myfun(int *a,int size);

• 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);

• Coding example to read and display the array elements


PROBLEM SOLVING WITH C
Arrays and Functions

Usage of const keyword


• Array being the formal parameter allows a function to change the elements of the
array passed in the function call.

• 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

Passing individual Array elements to a function

• Indexed variables can be arguments to 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

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]
Dr. Saritha, CSE, PESU

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Storage classes in C
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Storage classes in C

• 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

• List of storage classes


• Automatic variables (auto)
• External variables (extern)
• Static variables(static)
• Register variables (register)
• Global Variables
PROBLEM SOLVING WITH C
Storage classes in C

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

Global variables- Additional Storage class

• The variables declared outside all function are called global variables. They are not

limited to any function.

• Any function can access and modify global variables

• Automatically initialized to 0 at the time of declaration

• Coding Examples
THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]
Prof. Jenny Jijo, CSE, PESU

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Callback in C
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Callback in C

1. Points to Discuss

2. Introduction

3. Function Pointer/ Pointer to function

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.

• A callback function has a specific action which is bound to a specific circumstance.

• A callback function is an important element of GUI in C programming

• In C, a callback function is a function that is called through a function pointer/pointer to a


function.
PROBLEM SOLVING WITH C
Callback in C

Function Pointer/ pointer to function.


● Points to a code, not data and it stores the start of the executable code

● Used in reducing the redundancy

● Think about the difference between below statements


int *a1(int, int, int); // a1 is a function which takes three int arguments and returns a pointer to int.
int (*p)(int, int, int); // p is a pointer to a function which takes three int as parameters and returns an int

● Coding Examples
PROBLEM SOLVING WITH C
Callback in C
Demo of C Callback

• Simple Coding example to demo Callback

• Mimic map, filter and reduce function of python in C using user defined function
THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Recursion
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Recursion

1. Introduction

2. Why Recursion?

3. Implementing Recursion – The Stack

4. Arguments and Return Values

5. Practice Programs
PROBLEM SOLVING WITH C
Recursion

Introduction

Recursive Function
• A function that calls itself Directly or indirectly

• Each recursive call is made with a new, independent set of arguments


• Previous calls are suspended

• Allows building simple solutions for complex problems


PROBLEM SOLVING WITH C
Recursion

Why Recursion?

• Used to solve various problems by dividing it into smaller problems

• Some problems are too hard to solve without recursion


• Most notably, the compiler!
• Most problems involving linked lists and trees
PROBLEM SOLVING WITH C
Recursion

Points to note while using Recursion


• The problem is broken down into smaller tasks

• Programmers need to be careful to define an exit condition from the function,


otherwise results in an infinite 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

How is a particular problem solved using recursion?

• Problem to be solved: To compute factorial of n.


• knowledge of factorial of (n-1) is required, which would form the recursive
relationship
• The base case for factorial would be n = 0
• return 1 when n == 0 or n == 1 // base case
• return n*(n-1)! when n!=0 // recursive relationship
• Demo of C code
PROBLEM SOLVING WITH C
Recursion

Implementing Recursion - The Stack

• Definition – The Stack


• A last-in, first-out data structure provided by the operating system for running
each program
• For temporary storage of automatic variables, arguments, function results, and
other information
• The storage for each function call.
• Every single time a function is called, an area of the stack is reserved for that
particular call.
• Known as activation record, similar to that in python
PROBLEM SOLVING WITH C
Recursion

Implementing Recursion - The Stack continued..

• Parameters, results, and automatic variables allocated on the stack.

• Allocated when function or compound statement is entered

• Released when function or compound statement is exited

• Values are not retained from one call to next (or among recursions)
PROBLEM SOLVING WITH C
Recursion

Arguments and Return values


1. Space for storing result is allocated by caller
• On The Stack
• Assigned by return statement of function
• For use by caller
2. Arguments are values calculated by caller of function
• Placed on The Stack by caller in locations set aside for the
corresponding parameters
• Function may assign new value to parameter
• caller never looks at parameter/argument values again!
3. Arguments are removed when callee returns
• Leaving only the result value for the caller
PROBLEM SOLVING WITH C
Recursion

Practice Programs based on Recursion


1. Separate Recursive functions to reverse a given number and reverse a
given string
2. Recursive function to print from 1 to n in reverse order
3. Find the addition, subtraction and multiplication of two numbers using
recursion. Write separate recursive functions to perform these.
4. Find all combinations of words formed from Mobile Keypad.
5. Find the given string is palindrome or not using Recursion.
6. Find all permutations of a given string using Recursion
THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Searching using C
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Searching

1. Points for Discussion

2. Introduction

3. Searching Algorithms

4. Linear Search

5. Binary Search - Pictorial Representation and Implementation


PROBLEM SOLVING WITH C
Searching

Points for Discussion!

• Have you spent a day without searching for something?

• Finding a particular item among many hundreds, thousands, millions or more.


• Scenario: Finding someone’s phone number in our phone

• 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

• Identifying or finding a particular record/item/element in a collection of records/items/elements


and knowing the place of it

• Collection/Group where searching must be done may be sorted or unsorted

• Search may be Successful search or Unsuccessful based on the availability of the


record/item/element in a collection
PROBLEM SOLVING WITH C
Searching

Searching Algorithms

● Random Search

● Sequential or Linear search

● Non - Sequential or Binary Search.


PROBLEM SOLVING WITH C
Searching

Linear Search
• Performs search on any kind of data

• Starts from 0th item till the end of the collection

• Coding Example
PROBLEM SOLVING WITH C
Searching algorithms

Binary Search

● Necessary condition: Collection of data should be sorted


● Begins comparison at the middle of the collection
● If matched, return the index of the middle element
● If not matched, check whether the element to be searched is lesser or greater than the
middle element
● If the element to be searched is greater than the middle element, pick the elements on the
right side of the middle element and repeat from the start
● If the element to be searched is lesser than the middle element, pick the elements on the left
side of the middle element and repeat from the start
PROBLEM SOLVING WITH C
Searching algorithms

Pictorial Representation of Binary Search


PROBLEM SOLVING WITH C
Searching

Binary Search Implementation


Given a sorted Array A of n elements and the target value is T

Iterative Algorithm Recursive Algorithm


1. Set L: 0 and R: n-1 BinarySearch(T, A)
2. If(L>R), Unsuccessful Search 1. Set L: 0 and R: n-1
3. Else Set m: (L+R)/2 // m: position of middle element 2. If(L>R), return -1 // Unsuccessful Search
4. If Am < T, set L to m+1 and go to step 2 3. Else Set m: (L+R)/2 // m: position of middle element
5. If Am > T, set R to m-1 and go to step 2 4. If Am is T, search done, return m
6. If Am is T, search done, return m 5. If Am < T, return BinarySearch(T, A0 to Am-1)
6. Else return BinarySearch(T, Am+1 to An-1)
THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Sorting
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Sorting

1. Why Sorting?

2. Sorting Algorithms

3. Selection Sort Algorithm

4. Demonstration of C Code
PROBLEM SOLVING WITH C
Sorting

Why Sorting ?

• To access the data in a very quick time

• 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

Selection Sort Algorithm

• The algorithm maintains two sub-arrays in a given array


The sub-array which is already sorted.
Remaining sub-array which is unsorted.

• 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

• Demo of Selection sort on Array of integers


THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Strings in C
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Strings in C

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.

• Example: “X” is a String constant


PROBLEM SOLVING WITH C
Strings in C

Declaration

Syntax: char variable_name[size]; //Size is compulsory

char a1[10]; // valid declaration


char a1[]; // invalid declaration
PROBLEM SOLVING WITH C
Strings in C

Initialization

Syntax: char variable_name[size] = {Elements separated by comma};

Version 1:
• char a1[] = {'a', 't', 'm', 'a', '\0' };
• Shorthand notation: char a1[] = ”atma”;

Version 2: char a2[] = {'a', 't', 'm', 'a' };

Version 3: Partial initialization


• char a3[10] = {'a','t','m','a'};
PROBLEM SOLVING WITH C
Strings in C

Initialization continued..

Version 4: Partial initialization


• char a4[10] = {'a','t','m','a', '\0'};
• char a4[10] = ”atma”;

Version 5: char a5[ ] = {'a', 't', 'm', 'a', '\0', 't', 'r', 'i', 's', 'h', 'a', '\0' };

Version 6: char a6[ ] = "atma\0" ;

Version 7: char a7[ ] = "atma\\0" ;

Version 8: char a8[ ] = "at\0ma" ;


PROBLEM SOLVING WITH C
Strings in C

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

String v/s Pointer

• 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

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]
Problem Solving With C - UE24CS151B
String manipulation Functions & Errors
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
String manipulation Functions & Errors

1. Builtin String manipulation functions


2. User defined string functions
3. Error demonstration
PROBLEM SOLVING WITH C
String manipulation Functions & Errors

Built-in String manipulation Functions


• Expect ‘\0’ and available in string.h
• In character array, if ‘\0’ is not available at the end, result is undefined when passed to
built-in string functions

• 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

User defined String functions

• Start with iterative solution


• Usage of pointer arithmetic operations
• Usage of recursion to get the solution for few of the below functions
1. my_strlen()
2. my_strcpy()
3. my_strcmp()
4. my_strchr()
5. my_strcat()
PROBLEM SOLVING WITH C
String manipulation Functions & Errors

Error Demonstration

1. char * name[10] ; // declaring an array of 10 pointer pointing each one to a char


char name[10];
2. name = “choco”; // Cannot assign a string by using the operator =
char name[10] = “choco“ OR use strcpy()
3. printf("%s\n", *name);
Provide only the address of the first element of the string
4. Coding examples to demo the error caused while applying built-in string functions on
strings without specifying ‘\0’ at the end of the string
THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Command Line Arguments
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Command Line Arguments

• Introduction

• Usage of argc and argv

• 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

Usage of Argument count(argc) and Argument vector(argv)


• To pass command line arguments, define main() with two arguments
int main (int argc , char *argv []) { … }
• argc: An integer which specifies the number of arguments passed in the command line
including the executable. The value of argc should be Non- Negative
Example: a.exe 18 27 (argc=3)
• char * argv[]: An array of character pointers which contains all the arguments passed in
the command line
Example: argv[0] is a.exe
argv[1] is 18
PROBLEM SOLVING WITH C
Command Line Arguments

Demo of C Code

• Find the sum of all numbers provided in the command line


THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]

Ack: Teaching Assistant - U Shivakumar


Problem Solving With C - UE24CS151B
Dynamic Memory Management
Prof. Sindhu R Pai
PSWC Theory Anchor, Feb-May, 2025
Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Dynamic Memory Management

1. Problem with the Arrays

2. Memory Allocation

3. Dynamic allocation

4. Use of malloc(), calloc(), realloc(), free()


PROBLEM SOLVING WITH C
Dynamic Memory Management

Problem with the Arrays

• Few situations while coding:


⁻ Amount of data cannot be predicted beforehand
⁻ Number of data items keeps changing during program execution

• In such cases, use of fixed size array might create problems:


⁻ Wastage of memory space (under utilization)
⁻ Insufficient memory space (over utilization)

• Example: A[1000] can be used but what if the user wants to run the code for only 50 elements
//memory wasted

Solution: Can be avoided by using the concept of Dynamic memory management


PROBLEM SOLVING WITH C
Dynamic Memory Management

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

• Process of allocating memory at runtime/execution


Heap
• Uses the Heap region of Memory segment

• No operator in C to support dynamic memory management

• Library functions are used to dynamically allocate/release memory Stack

• malloc()
• calloc()
• realloc() Code
• free() segment
• Available in stdlib.h
Memory space
PROBLEM SOLVING WITH C
Dynamic Memory Management

malloc() - memory allocation

• 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

calloc() - contiguous allocation

• 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

realloc() - reallocation of memory

• 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

realloc() continued.. HEAP


5000
5001
Example: 5002
0

int* ptr = (int*) calloc(3,sizeof(int)); 5003

ptr = (int *)realloc(ptr, 4); 5004


5005
0
5006
STACK 5007
5008
5009
ptr 5000 0 Size has to be
5010
increased from 3
5011
elements to 4
5012 X
5013 XX
5014 X
No initialization
5015 X
5016 X
5017 X
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

• On allocation of memory, the number of


bytes allocated is stored somewhere in the
memory. This is known as book keeping
information
THANK YOU
Department of Computer Science and Engineering

Dr. Shylaja S S, Director, CCBD & CDSAML, PESU


Prof. Sindhu R Pai - [email protected]
Dr. Shruti Jadon, CSE, PESU

Ack: Teaching Assistant - U Shivakumar


PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Structures in C

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
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.

• Helps to construct a complex data type which is more meaningful.

• Provides a single name to refer to a collection of related items of different types.

• Provides a way of storing many different values in variables of potentially different types
under the same name.

• Generally useful whenever a lot of data needs to be grouped together.

• Creating a new type decides the binary layout of the type


PROBLEM SOLVING WITH C
Structures in C

Characteristics/Properties

• Contains one or more components(homogeneous or heterogeneous) –


Generally known as data members. These are named ones.

• Order of fields and the total size of a variable of that type is decided when the
new type is created

• Size of a structure depends on implementation. Memory allocation would be at


least equal to the sum of the sizes of all the data members in a structure.
Offset is decided at compile time.

• Compatible structures may be assigned to each other.


PROBLEM SOLVING WITH C
Introduction

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

Note: No memory allocation for declaration/description of the structure.


PROBLEM SOLVING WITH C
Structures in C

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)

struct student* s2; // s2 is the instance variable of type struct


student*.
// s2 is pointer to structure

• 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

Accessing data members


• Operators used for accessing the members of a structure.
1. Dot operator (.)
2. Arrow operator (->)
• Any member of a structure can be accessed using the structure variable as:
structure_variable_name.member_name
Example: s1.roll_no
//where s1 is the structure variable name and roll_no member is data member of s1.

• 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.

• Size of data members is implementation specific.

• Coding Examples
PROBLEM SOLVING WITH C
Structures in C

Comparison of structures

• Comparing structures in C is not permitted to check or compare directly


with logical and relational operators.

• Only structure members can be compared with relational operator.

• Coding examples
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Array of Structures

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Array of Structures

1. Introduction

2. Structure Variable Declaration

3. Structure Variable Initialization

4. Pointer to an Array of Structures


PROBLEM SOLVING WITH C
Array of Structures

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

Declaration of Structure variable

• Can be done in two ways


- Along with structure declaration after closing } before semicolon (;) of structure
body.
struct student {
int roll_num; char name[100]; int marks;
}s[100];

- After structure declaration (either inside main or globally using struct keyword)
struct student s[100];

• Coding examples
PROBLEM SOLVING WITH C
Array of Structures

Initialization of structure variable

• Compile time initialization: Using a brace-enclosed initializer list

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};

• Run time initialization (using loops preferably)

• Coding examples
PROBLEM SOLVING WITH C
Array of Structures

Pointer to an 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

struct student *ptr = ST;

• Coding examples to print the array of


structures using pointer
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Sorting

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Sorting

1. Why Sorting?

2. Sorting Algorithms

3. Bubble Sort Algorithm

4. Demonstration of C Code
PROBLEM SOLVING WITH C
Sorting

Why Sorting ?

• To access the data in a very quick time

• 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

Bubble Sort Algorithm

• 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

• Demo of Bubble sort on structures


THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Bit fields in C

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Bit fields in C

• What is a Bit field?

• Bit field creation

• Few points on Bit fields


PROBLEM SOLVING WITH C
Bit fields in C

What is a Bit field ?


• Data structure that allows the programmer to allocate memory to structures and unions in
bits in order to utilize computer memory in an efficient manner.
• The variables defined with a predefined width and can hold more than a single bit
• Consists of a number of adjacent computer memory locations which have been allocated
to hold a sequence of bits.
• Great significance in C programming because of the following reasons
• Used to reduce memory consumption
• Easy to implement
• Provides flexibility to the code
PROBLEM SOLVING WITH C
Bit fields in C

Bit field Creation


• Syntax: struct [tag] { type [member_name] : width ; };
type - Determines how a bit-field's value is interpreted. May be int, signed int, or unsigned int
member_name - The name of the bit-field
width - Number of bits in the bit-field. The width must be less than or equal to the bit width of the specified
type. The largest value that can be stored for an unsigned int bit field is 2n -1, where n is the bit-length

• Example: struct Status {


unsigned int bin1:1; // 1 bit is allocated for bin1. only two digits can be stored 0 and 1
unsigned int bin2:1; // if it is signed int bin1:1 or int bin1:1, one bit is used to represent the sign
};
• Coding examples
PROBLEM SOLVING WITH C
Bit fields in C

Few points on Bit fields


• The first field always starts with the first bit of the word.
• Cannot extract the address of bit field
• Should be assigned values that are within the range of their size. It is implementation
defined to assign an out-of-range value to a bit field member
• Cannot have pointers to bit field members as they may not start at a byte boundary
• Array of bit fields not allowed
• Storage class cannot be used on bit fields
• Can use bit fields in union
• Unnamed bit fields results in forceful alignment of boundary
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Unions in C

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Unions in C

• What is Union?

• Accessing Union Members

• 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

Accessing the Union members


• Syntax:
union Tag // union keyword is used
{
data_type member1; data_type member2; … data_type member n;
}; // ; is compulsory

• To access any member using the variable of union type,


• use the Member Access operator (.)
• To access any member using the variable of pointer to union type,
• use the Arrow operator (->)
• Coding Examples
PROBLEM SOLVING WITH C
Unions in C

Union Vs Structure
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Enums(Enumerations) in C

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Enumerations

• Introduction

• Enum creation

• Points wrt Enums

• 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

• Provides a symbolic name to represent one state out of a list of states

• The names are symbols for integer constants, which won't be stored anywhere in
program's memory

• Used to replace #define chains


PROBLEM SOLVING WITH C
Enumerations

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

Points wrt Enums


• Enum names are automatically assigned values if no value specified

• 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.

• Only integer constants are allowed. Arithmetic operations allowed-> + , -, *, / and %

• 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

• Demo of Enum points discussed in the previous slide


THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Linked List

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Linked List

1. Introduction

2. Self Referential Structures

3. Characteristics

4. Operations on linked list

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

Self Referential Structures


● A structure which has a pointer to itself as a data member
struct node
a
100
{
int a; p
struct node *p;
} ; // defines a type struct node
// memory not allocated for type declaration
● Variable declaration to allocate memory and assigning values to data
members
struct node s; s.a = 100; s.p = &s;
PROBLEM SOLVING WITH C
Linked List

Characteristics

● A data structure which consists of zero or more nodes.


● Every node is composed of two fields: data/component field and a pointer field
● The pointer field of every node points to the next node in the sequence
● Accessing the the nodes is always one after the other. There is no way to access the node
directly as random access is not possible in linked list. Lists have sequential access
● Insertion and deletion in a list at a given position requires no shifting of element
PROBLEM SOLVING WITH C
Linked List

Operations on Linked List

● Insertion
● Deletion
● Search
● Display
● Merge
● Concatenate
PROBLEM SOLVING WITH C
Linked List

Pictorial Representation
s info link info link info link

• Structure definition of a node 100 200 300 NULL

Fig1: Linked list Representation


struct node {
int info; // component field
struct node *link; // pointer field
s info link info link info link
};
typedef struct node NODE_T; 100 200 300 NULL

p
Fig2: Displaying the Linked list
PROBLEM SOLVING WITH C
Linked List

Different Types

● Singly Linked List

● Doubly Linked List

● Circular Linked List


PROBLEM SOLVING WITH C
Linked List

Applications

● Implementation of Stacks & Queues


● Implementation of Graphs
● Maintaining dictionary
● Gaming
● Evaluation of Arithmetic Expression
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Priority Queue

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Priority Queue

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.

● In computer Science, a list of data items, commands, etc., stored so as to be retrievable in a

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.

● Follows the Principle of First In First Out (FIFO)

Deletion from Insertion from Rear End


front end
100 99 102 134 37

FRONT END REAR END


PROBLEM SOLVING WITH C
Priority Queue

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.

● Priority decides about the Deque operation.

● The Enque operation stores the item and the “Priority” information

● Types of Priority Queue:


Ascending Priority Queue: Smallest Number - Highest Priority
Descending Priority Queue: Highest Number - Highest Priority
PROBLEM SOLVING WITH C
Priority Queue

Applications of Priority Queue

1. Implementation of Heap Data structure.

2. Dijkstra’s Shortest Path Algorithm

3. Prim’s Algorithm

4. Data Compression

5. OS - Load Balance Algorithm.


THANK YOU

Prof Sindhu R Pai


Department of Computer Science and Engineering
[email protected]
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

File Handling in C

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
File Handling

1. Points to Discuss

2. Introduction

3. Need of Files

4. File Classification

5. Operations on Files

6. Read/Write Operations on Files


PROBLEM SOLVING WITH C
File Handling

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?

• How to generate same input several times?

• How to store the output produced for future references?

• Program stores the result what if one wants to store other data too?

• How to categorize and manage forms of data produced?


PROBLEM SOLVING WITH C
File Handling
Introduction

• Variables used in program will die at the end of execution

• To persist data even after the program execution is complete, use Files

• File represents a sequence of bytes and it is a source of storing information in sequence of


bytes on a disk

• The data in a file can be structured or unstructured

• A program in C can itself be the data file for the program

• 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

• Reading the contents of the file

• Writing the contents to the file

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

• Mode: Can be read only, write only, append or a combination of these.


PROBLEM SOLVING WITH C
File Handling

C Functions to perform Operations

• Creation of new file or open an existing file using fopen()

• Read operation on a file using fgetc(), getc(), fscanf() and fgets()

• Write operation on a file using fputc(),putc(), fprintf() and fputs()

• Moving to a specific location in a file using fseek(), ftell() and rewind()

• Closing a file using fclose()


PROBLEM SOLVING WITH C
File Handling

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.

● The reasons for failure in file opening:


● File might not be available
● File might not have permission to open it in the mode specified.

● 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

● Returns zero if the stream is successfully closed. On failure, EOF is returned

● All links to the file are broken

● Misuse of files is prevented

Syntax: fclose(file_pointer);

● File pointer can be reused

● 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

Character I/O operations on File

• 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

String I/O Operations on File(fgets() and fputs())

•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.

• Write a line of characters to a file.


• Syntax: int fputs(const char *s, FILE *stream)
• Return Value: A non-negative number on success, EOF on error.

• Coding examples
PROBLEM SOLVING WITH C
File Handling

Formatted Read/Write Operations on File(fscanf(),fprintf())

● 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.

● Writes the formatted data to a file instead of standard output.


● Syntax: int fprintf(FILE *fp, const char *format[,argument,….]);
● Return value: The number of characters written on success , EOF on failure.

● Coding Examples
PROBLEM SOLVING WITH C
File Handling

Block Read/Write Operations on a File

● Reads an entire block from a given file.


● Syntax: size_t fread(void *p, size_t size, size_t n, FILE *fp);
● Return Value: The number of values successfully read , error or zero for size <=0.

● Writes an entire block to the file.


● Syntax: size_t fwrite(const void *p, size_t size, size_t n, FILE *fp);
● Return Value: The number of values successfully written, error or zero for size <=0.
PROBLEM SOLVING WITH C
File Handling

Random access to a file

● Seeking the pointer position in the file at the specified byte.


● Syntax: fseek( FILE* pointer, long offset, int whence)
● Return Value: zero if successful, or else it returns a non-zero value.

● 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.

● The function is used to move the file pointer to the beginning


● Syntax: rewind(FILE* pointer) // Function does not return anything.
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
File handling in C

● 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.

● C provides a comprehensive set of functions through its standard library (specifically,


stdio.h) for opening, reading, writing, and closing files.

Opening a File

● The fopen() function is used to open a file.

● It requires two arguments: the name of the file and the mode in which to open it.

Syntax: FILE *fopen(const char *filename, const char *mode);

The modes include:

● 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.

● fprintf() writes a formatted string to a file


○ fprintf(fp, "Hello PES University N Section\n");

● fputc() writes a single character to a file.


○ fputc('A', fp);

● fwrite() writes multiple bytes at once, useful for binary files.


○ char data[100] = "N Section Data";
○ fwrite(data, sizeof(char), sizeof(data), fp);

Reading from a File

● For reading, fscanf(), fgetc(), and fread() are available.

● fscanf() reads formatted input from a file.


○ char NSectionData[100];
○ fscanf(fp, "%s", NSectionData);

● fgetc() reads a single character from a file.


○ char ch;
○ ch = fgetc(fp);

● fread() reads multiple bytes at once, suitable for binary files


○ char NSectionData[100];
○ fread(NSectionData, sizeof(char), 100, fp);

Positioning in a File

● fseek(), ftell(), and rewind() are used to manipulate the file pointer.

● fseek() moves the file pointer to a specified location.


○ fseek(fp, 0, SEEK_SET); // Moves to the beginning of the file

● ftell() returns the current file pointer position


○ long position = ftell(fp);

● rewind() resets the file pointer to the beginning of the file.


○ rewind(fp);

Nitin V Pujari 2
Error Handling

● ferror() checks for an error in file operations.


● clearerr() clears the error indicator of a file stream.
● feof() checks for the end-of-file marker.

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];

// Creating and opening a file for writing


fp = fopen("NSectionData.txt", "w");
if (fp == NULL) {
printf("Failed to create the file.\n");
return -1;
}
fprintf(fp, "%s", dTw);
fclose(fp);

// Opening file for reading


fp = fopen("NSectionData.txt", "r");
if (fp == NULL) {
printf("Failed to open the file for reading.\n");
return -1;
}
fscanf(fp, "%[^\n]", dTr);
printf("Data from the file: %s\n", dTr);
fclose(fp);

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);

● ptr: Pointer to the memory block where data will be stored.


● size: Size in bytes of each element to be read.
● nmemb: Number of elements to be read.
● stream: Pointer to a FILE object that specifies the input 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];

// Open the file in binary mode for reading


FilePointer = fopen("NSectionData.bin", "rb");
if (FilePointer == NULL) {
perror("Error opening file");
return 1;
}

// Read 5 integers from the file


fread(NSectionData, sizeof(int), 5, FilePointer);

// Close the file


fclose(FilePointer);

Nitin V Pujari 1
// Display the read integers
for (int i = 0; i < 5; i++) {
printf("%d ", data[i]);
}

return 0;
}

fwrite()

● fwrite() is used to write data to a binary file. Its syntax is:


○ size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

● ptr: Pointer to the data to be written.


● size: Size in bytes of each element to be written.
● nmemb: Number of elements to be written.
● stream: Pointer to a FILE object that specifies the output stream.

Suppose you want to write an array of integers to a binary file.

#include <stdio.h>

int main() {
FILE *FilePointer;
int NSectionData[5] = {10, 20, 30, 40, 50};

// Open the file in binary mode for writing


FilePointer = fopen("NSectionData.bin", "wb");
if (fp == NULL) {
perror("Error opening file");
return 1;
}

// Write the array to the file


fwrite(NSectionData, sizeof(int), 5, FilePointer);

// Close the file


fclose(FilePointer);

printf("Data has been written to the file successfully.\n");

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>

// Define a structure to hold information about a person


struct Person
{
char name[50];
int age;
};

int main() {
FILE *FilePointer;
struct Person person; // Declare a variable of type Person

// Open a binary file in write mode


FilePointer = fopen("persons.bin", "wb");
if (file == NULL) {
perror("Error opening file");
return 1;
}

// 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

// Write the structure to the file


fwrite(&person, sizeof(struct Person), 1, file);

// Close the file


fclose(file);

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;
}

// Read the structure from the file and print it out


printf("\nReading from file:\n");
fread(&person, sizeof(struct Person), 1, FilePointer);
printf("Name: %s\n", person.name);
printf("Age: %d\n", person.age);

// Close the file


fclose(file);

return 0;
}

Comments have been added to explain each part of the code:

● The Person structure is defined to hold a person's name and age.

● 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 closed.

● 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.

● Finally, the file is closed and the program exits.

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>

// Define a structure to represent a person


struct Person {
char name[50];
int age;
float height;
};

// Function to append a person record to a binary file


void appendPerson(const char *filename, struct Person *person) {
FILE *file = fopen(filename, "ab"); // Open file in append binary mode

if (file == NULL) {
printf("Error opening file!\n");
return;
}

fwrite(person, sizeof(struct Person), 1, file); // Write person structure to file


fclose(file); // Close file
}

// 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;
}

struct Person person;

// Read each person record until end of file


while (fread(&person, sizeof(struct Person), 1, file)) {
printf("Name: %s, Age: %d, Height: %.2f\n", person.name, person.age, person.height);
}

fclose(file); // Close file


}

Nitin V Pujari 6
int main() {
struct Person p1 = {"Alice", 25, 5.6}; // Sample person record

// Append p1 to the file


appendPerson("persons.bin", &p1);

// Sample person records to append


struct Person p2 = {"Tiwari", 30, 6.0};
struct Person p3 = {"Hegde", 35, 5.8};

// Append p2 and p3 to the file


appendPerson("persons.bin", &p2);
appendPerson("persons.bin", &p3);

// Read and print all person records from the file


printf("All Persons:\n");
readPersons("persons.bin");
return 0;
}

Explanation of the code:

● We define a structure Person to represent a person, containing fields for name, age, and
height.

● The appendPerson function takes a filename and a pointer to a Person structure as


arguments.

● It opens the file in append binary mode and writes the Person structure to the file using
fwrite. Then, it closes the file.

● The readPersons function takes a filename as an argument.


○ It opens the file in read binary mode and reads each Person structure from the file
using fread.
○ It prints the details of each person and continues until the end of the file.

○ 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.

Overview of CSV Parsing

In C, handling CSV files generally involves:

● 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

1. File Structure and Opening


First, include necessary headers and define any constants:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE_LENGTH 1024

2. Defining the Student Structure


Define a structure to hold student data:
typedef struct {
char name[50];
int age;
int score;
} Student;

3. Parsing Function
This function takes a string (a line from the CSV), parses it, and fills a Student struct with the data:

void parse_line(char* line, Student* student) {


char* token;
token = strtok(line, ",");
strcpy(student->name, token);

token = strtok(NULL, ",");


student->age = atoi(token);

token = strtok(NULL, ",");


student->score = atoi(token);
}

4. Reading and Processing the File

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;

// Skip header line


fgets(line, sizeof(line), fp);

// Read and process each line


while (fgets(line, sizeof(line), fp)) {
parse_line(line, &student);
totalScore += student.score;
count++;
}

if (count > 0) {
printf("Average Score: %.2f\n", (double)totalScore / count);
}

fclose(fp);
return EXIT_SUCCESS;
}

Compiling and Running


To compile the program, use gcc:
gcc csv_parser.c
./a.out

Note:
Conclusion and Further Considerations

● This example demonstrates basic CSV parsing in C without external libraries.

● 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

● The .csv file format is standard, with comma-separated values.

● Each line in the .csv file represents one record, and the first line contains column headers.

● The dataset is large enough that efficient memory use is crucial.

● Typical operations might include searching for records based on conditions, summarizing
data, and exporting results.

Sample CSV Structure

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
...

Steps for Processing the CSV File

● Reading the File:


○ Open the file using standard file I/O operations.
○ Handle possible I/O errors such as "file not found".

● Parsing the CSV:


○ Read the file line by line.
○ Use a robust method to split each line into tokens based on commas.
○ Consider special cases (e.g., commas within fields).

● 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

Function to parse a single line:

PatientRecord parse_csv_line(char *line)


{
PatientRecord record;
char *token = strtok(line, ",");
record.id = atoi(token);

token = strtok(NULL, ",");


strcpy(record.name, token);

token = strtok(NULL, ",");


record.age = atoi(token);

token = strtok(NULL, ",");


record.gender = token[0];

token = strtok(NULL, ",");


strcpy(record.diagnosis, token);

return record;
}

Main Processing Logic


Read and process the CSV file:

#define MAX_LINE_LENGTH 1024

void process_csv(const char *filename)


{
FILE *file = fopen(filename, "r");
if (!file) {
perror("Failed to open file");
return;
}

char line[MAX_LINE_LENGTH];
fgets(line, sizeof(line), file); // Skip header line

while (fgets(line, sizeof(line), file)) {


PatientRecord record = parse_csv_line(line);
// Process record, e.g., add to data structure, etc.

Nitin V Pujari 6
}

fclose(file);
}

int main(int argc, char **argv) {


if (argc < 2) {
fprintf(stderr, "Usage: %s <csv_file>\n", argv[0]);
return 1;
}

process_csv(argv[1]);
return 0;
}

Considerations for Large Datasets

● 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.

Header Files and Global Definitions


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 1024 // Adjust as necessary for optimal memory management

Struct Definition for Storing Parsed Data


typedef struct
{
char region[100];
int year;
char crop[50];
int area;
float yield;
} AgricultureRecord;

Nitin V Pujari 8
Helper Functions for Parsing

// Function to split a line and convert it into an AgricultureRecord


AgricultureRecord parse_csv_line(char *line)
{
AgricultureRecord record;
char *token;

token = strtok(line, ",");


strcpy(record.region, token);

token = strtok(NULL, ",");


record.year = atoi(token);

token = strtok(NULL, ",");


strcpy(record.crop, token);

token = strtok(NULL, ",");


record.area = atoi(token);

token = strtok(NULL, ",");


record.yield = atof(token);

return record;
}

// Function to read and process the CSV file

void process_csv(const char *filename)


{
char buffer[BUFFER_SIZE];
FILE *fp = fopen(filename, "r");
if (!fp) {
perror("File opening failed");
return;
}

// Skipping the header line


fgets(buffer, BUFFER_SIZE, fp);

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;
}

Compiling and Running the Program


To compile and run the program, use the following commands in your terminal:
gcc -o csv_parser.c
./a.out agriculture_data.csv

Memory and Performance Considerations

● 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.

● Scalability: For extremely large files, consider multi-threaded processing or processing in


chunks, where each chunk can be processed in parallel.

● 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.

● Data Transformation: Ability to apply transformations to the data, such as converting


coordinates from one format to another.

Sample Data Format


Consider a .csv file with the following columns:
id, latitude, longitude, description

Example content might look like:


1, 12.9351, 77.5360, "PES University RR Campus"
2, 12.8615, 77.6647, "PES University EC Campus"
...

Tools and Libraries

● Standard C libraries (stdio.h, stdlib.h, string.h)

● Optionally, a library for handling large numbers or geographic calculations if needed.

Step-by-Step Breakdown

● Step 1: Setup the Project Structure


○ File Structure
○ main.c: Contains the main logic for parsing and invoking processing functions.
○ csv_parser.c, csv_parser.h: Handles the CSV parsing logic.
○ data_processor.c, data_processor.h: Contains functions for data filtering and
transformation.
○ Compiling and Makefile
○ Use gcc for compiling the source files.
○ Create a Makefile for easy compilation.

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.

● Step 3: Data Processing


○ Filtering Function
○ Example: Filter out locations within a certain radius of a given point.
○ Transformation Function
○ Example: Convert GPS coordinates from degrees, minutes, seconds format to
decimal for easier computation.

● Step 4: Output Results


○ Write the processed data to a new .csv file or standard output for verification.

● Step 5: Error Handling


○ Implement error checking at each step (file opening, memory allocation, data
conversion).

Example Code Snippets


CSV Parsing Function
void parse_csv(FILE *fp)
{
char line[1024];
while (fgets(line, 1024, fp)) {
char *token = strtok(line, ",");
int id = atoi(token);
token = strtok(NULL, ",");
double latitude = atof(token);
token = strtok(NULL, ",");
double longitude = atof(token);
token = strtok(NULL, ",");
char *description = token;

// Now handle the parsed data


}
}

Nitin V Pujari 13
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: %s <csv_file>\n", argv[0]);
return 1;
}

FILE *file = fopen(argv[1], "r");


if (!file) {
perror("Error opening file");
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:

The CSV file might have the following columns:

● 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).

● Storing and Analyzing Data:


○ Use appropriate data structures (e.g., structs) to store the parsed data.
○ Implement functions to calculate statistics like average, minimum, and maximum.

● Error Handling: Properly manage potential errors in file handling and data parsing.

● Performance Considerations: Consider using multi-threading to parse different portions of


the file in parallel.

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>

#define BUFFER_SIZE 1024

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;
}

3. File Reading and Processing

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;

while (fgets(buffer, BUFFER_SIZE, file))


{
if (parse_csv_line(buffer, &data)) {
// Process data, e.g., update statistics
}
}

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;
}

Extensions and Considerations

● 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.

Step 1: Define the Problem and Requirements:


● Objective:
○ Create a C program to parse and process AR/VR interaction data stored in a .CSV
file. The dataset includes timestamps, types of interactions (like "grab", "move",
"rotate"), object IDs interacted with, and user IDs.

● 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
...

Step 3: Design the Data Structures


Use structs to manage the data:
typedef struct
{
char timestamp[20];
int user_id;
char interaction_type[10];
int object_id;
} Interaction;

Step 4: Implement CSV Parsing Functions


Implement a function to read and parse the CSV file line by line. Handle large files using buffered
reading.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 1024

// 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;
}

void parse_csv(const char* filename)


{
FILE *file = fopen(filename, "r");
if (!file) {
perror("Failed to open file");
exit(EXIT_FAILURE);
}

char buffer[BUFFER_SIZE];
fgets(buffer, BUFFER_SIZE, file); // Skip header line

while (fgets(buffer, BUFFER_SIZE, file)) {


process_line(buffer);
}

fclose(file);
}

void process_line(char* line) {


char* token;
Interaction interaction;

token = strtok(line, ",");


strcpy(interaction.timestamp, token);

token = strtok(NULL, ",");


interaction.user_id = atoi(token);

token = strtok(NULL, ",");


strcpy(interaction.interaction_type, token);

token = strtok(NULL, ",");


interaction.object_id = atoi(token);

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);
}

Step 5: Data Processing


Implement additional functions to accumulate and summarize data. For example, count
interactions per object type or identify peak usage times.

#define MAX_OBJECTS 1000

int interaction_counts[MAX_OBJECTS] = {0};

void accumulate_data(const Interaction* interaction)


{
interaction_counts[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]); } }}

Integrate these functions in process_line after parsing each line.

Step 6: Testing and Validation


Test the program with sample .CSV files of varying sizes and complexity to ensure accuracy and
efficiency. Address any potential memory or buffer overflow issues.

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.

Basics of Function Pointers:

● In C, like other pointers, function pointers hold the memory address of a function.

● They allow functions to be assigned to variables, passed as arguments to other functions,


and returned from functions.

● The syntax for declaring a function pointer is as follows:


return_type (*pointer_name)(parameter_list);

● 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>

// Function to add two numbers


int add(int a, int b)
{
return a + b;
}

// Function to subtract two numbers


int subtract(int a, int b)
{
return a - b;
}

int main()
{
int (*operation)(int, int); // Declare a function pointer

operation = add; // Point to the add function

printf("Addition result: %d\n", operation(15, 13)); // Call the add function

operation = subtract; // Point to the subtract function


printf("Subtraction result: %d\n", operation(15, 13)); // Call the subtract function

return 0;
}

Usage of Function Pointers:

● 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.

○ This is common in polymorphism and object-oriented programming in C.

● 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

fun_ptr_arr[0](); // Call function 1


fun_ptr_arr[1](); // Call function 2

return 0;
}

Note:
● Function pointers in C provide a flexible and powerful mechanism for dynamic function
calls and implementations.

● They are used extensively in various programming paradigms such as procedural,


functional, and object-oriented programming.

● 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.

● In C, callbacks are particularly powerful, enabling functions to accept other functions as


arguments.

Definition:

● A callback is a function that is passed as an argument to another function.

● The receiving function can then execute the callback function at a later time or under
certain conditions.

Purpose:

● Callbacks enable the implementation of event-driven programming, asynchronous


operations, and higher-order functions.

Function Pointers:
● In C, callbacks are typically implemented using function pointers

// Function pointer declaration


typedef void (*CallbackFunc)(int);

// Function taking a callback function as an argument


void process(CallbackFunc callback, int data) {
// Perform some processing
callback(data);
}

Usage:
● The process function can now accept any function that matches the specified signature
(void function(int)) as its callback.

Example: Using Callbacks in C

Scenario: Consider a program that performs various mathematical operations on a given number
using callbacks.

Nitin V Pujari 25
#include <stdio.h>

// Callback function prototypes


void square(int num);
void cube(int num);

// Function to perform an operation using a callback


void performOperation(int num, void (*callback)(int))
{
callback(num);
}

// Callback functions
void square(int num)
{
printf("Square of %d is %d\n", num, num * num);
}

void cube(int num)


{
printf("Cube of %d is %d\n", num, 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:

● Flexibility: Callbacks enable dynamic behavior by allowing functions to be passed as


arguments.

● Reusability: Callbacks promote code reuse by separating generic functionality from specific
implementation details.

● Asynchronous Operations: Callbacks facilitate asynchronous programming by executing


functions in response to events or conditions.

Limitations of Callbacks:

● Complexity: Callback-based code can be difficult to understand and maintain, especially


when dealing with multiple nested callbacks.

● Memory Management: Improper handling of callbacks can lead to memory leaks or


dangling references.

● 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.

● By allowing functions to be passed as arguments, callbacks facilitate the implementation of


event-driven systems, asynchronous operations, and higher-order functions.

● Understanding and effectively utilizing callbacks can significantly enhance the design and
functionality of C programs

Nitin V Pujari 27
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

File Handling in C continued..

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
File Handling

1. Common Programming Errors

2. Error Handling

3. Demo of Errors

4. Best Practices
PROBLEM SOLVING WITH C
File Handling

Common Programming Errors that occur during File I/O

● Open with invalid filename

● Operation on a file that has not been opened

● Operation not permitted by ‘fopen’

● Write to a write-protected file

● Read beyond end-of-file


PROBLEM SOLVING WITH C
File Handling

Error Handling

● Not supported by C directly and is accomplished by using errno.h

● 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

Error Handling continued..

• Two-status library functions are used to prevent performing any operation beyond EOF

• feof(): Used to test for an end of file condition


• Syntax: feof(FILE *file_pointer);
• Return Value: Non-zero if EOF, Else zero
• ferror(): Used to check for the error in the stream
• Syntax: int ferror (FILE *file_pointer);
• Return Value: Non-zero if error occurs, Else zero

• The error indication will last until the file is closed(fclose())or cleared by the clearerr() function.
PROBLEM SOLVING WITH C
File Handling

Demo of Error Handling

● C code demonstration of Error handling in File I/O


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

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Problem Solving: File Handling

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Problem Solving: File Handling

1. Data file Description

2. Problem Statements

3. Requirements to solve the Problem

4. Demo of C Solution
PROBLEM SOLVING WITH C
Problem Solving: File Handling

Data File Description

• Data file to be used: matches.csv


• Contains the information of cricket matches held between 2008 and 2016
• First row represents the column headers such as id, season, city, date, team1, team2,
toss_winner, toss_decission, result, dl_applied, winner, win_by_runs, win_by_wickets, player
of match, venue, umpire1, umpire2 and umpire3
• Contains around 577 rows. Every data is stored with a comma in between
PROBLEM SOLVING WITH C
Problem Solving: File Handling

Problem Statements

• Count the number of matches played in the year 2008 – Solution: 58


• Count the number of times the Toss winner is same as the Winner of the match
• Display the count of matches played between KKR and RCB
• Display the Winner of each match played in 2016
• Display the list of Player of the match when there was a match between RCB and CSK
in the year 2010
• The output of all the above can be written to a file to store the record of outputs in
one file
PROBLEM SOLVING WITH C
Problem Solving: File Handling

Requirements to solve the problem

• Reading the csv file – Two ways


Read character by character, count the number of commas, then extract the field after the
second comma till third comma.
Read the whole line using fgets and split the line based on comma using a function ‘strtok’
• Strtok: Function returns a pointer to the first token found in the string. A NULL pointer is returned
if there are no tokens left to retrieve.
Two arguments – A source string or NULL and the Delimiter string.
First time strtok is called, the string to be split is passed as the first argument. In subsequent calls,
NULL is passed to indicate that strtok should keep splitting the same string for the next token.
PROBLEM SOLVING WITH C
Problem Solving: File Handling

Demo of C Solution

• Demonstration of C Code
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Searching

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Searching

1. Points for Discussion

2. Introduction

3. Searching Algorithms

4. Linear Search

5. Binary Search - Pictorial Representation and Implementation


PROBLEM SOLVING WITH C
Searching

Points for Discussion!

• Have you spent a day without searching for something?

• Finding a particular item among many hundreds, thousands, millions or more.


• Scenario: Finding someone’s phone number in our phone

• 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

• Identifying or finding a particular record/item/element in a collection of records/items/elements


and knowing the place of it

• Collection/Group where searching must be done may be sorted or unsorted

• Search may be Successful search or Unsuccessful based on the availability of the


record/item/element in a collection
PROBLEM SOLVING WITH C
Searching

Searching Algorithms

● Random Search

● Sequential or Linear search

● Non - Sequential or Binary Search.


PROBLEM SOLVING WITH C
Searching

Linear Search
• Performs search on any kind of data

• Starts from 0th item till the end of the collection

• Coding Example
PROBLEM SOLVING WITH C
Searching algorithms

Binary Search

● Necessary condition: Collection of data should be sorted


● Begins comparison at the middle of the collection
● If matched, return the index of the middle element
● If not matched, check whether the element to be searched is lesser or greater than the
middle element
● If the element to be searched is greater than the middle element, pick the elements on the
right side of the middle element and repeat from the start
● If the element to be searched is lesser than the middle element, pick the elements on the left
side of the middle element and repeat from the start
PROBLEM SOLVING WITH C
Searching algorithms

Pictorial Representation of Binary Search


PROBLEM SOLVING WITH C
Searching algorithms

Binary Search Implementation


Given a sorted Array A of n elements and the target value is T

Iterative Algorithm Recursive Algorithm


1. Set L: 0 and R: n-1 BinarySearch(T, A)
2. If(L>R), Unsuccessful Search 1. Set L: 0 and R: n-1
3. Else Set m: (L+R)/2 // m: position of middle element 2. If(L>R), return -1 // Unsuccessful Search
4. If Am < T, set L to m+1 and go to step 2 3. Else Set m: (L+R)/2 // m: position of middle element
5. If Am > T, set R to m-1 and go to step 2 4. If Am is T, search done, return m
6. If Am is T, search done, return m 5. If Am < T, return BinarySearch(T, A0 to Am-1)
6. Else return BinarySearch(T, Am+1 to An-1)
PROBLEM SOLVING WITH C
Searching

Demo of Binary search on array of integers present in a file


THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Problem Solving: Sorting using Array of Pointers

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Problem Solving: Sorting using Array of Pointers

1. Data file Description

2. Problem Statement

3. Requirements to solve the Problem

4. Demo of C Solution
PROBLEM SOLVING WITH C
Problem Solving: Sorting using Array of Pointers

Data File Description

• Data file to be used: student.csv


o Contains the information of students in two columns only
o First row represents the column headers such as roll_no and name
o Contains around 55 rows. Every data is stored with a comma in between
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

Requirements to solve the problem

• 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

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Problem Solving: Callback

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Problem Solving: Callback

1. Problem Statement

2. Requirements to solve the problem

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

Requirements to solve the problem

• 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

• Demo of Bubble sort using callback


THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Qualifiers in C

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Qualifiers in C

1. Introduction

2. Size Qualifiers

3. Sign Qualifiers

4. Type Qualifiers

5. Applicability of Qualifiers to Basic Types


PROBLEM SOLVING WITH C
Qualifiers in C

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

• Prefixed to modify the size of a data type allocated to a variable

• Supports two size qualifiers, short and long

• Rules Regarding size qualifier as per ANSI C standard

• 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

• Used to specify the signed nature of integer types

• It specifies whether a variable can hold a negative value or not

• Sign qualifiers are used with int and char types

• There are two types of Sign Qualifiers in C. Signed and Unsigned

• A signed qualifier specifies a variable which can hold both positive and negative integers

• An unsigned qualifier specifies a variable with only positive 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

• Type Qualifiers consists of two keywords


• const
• volatile.
PROBLEM SOLVING WITH C
Qualifiers in C

Type Qualifiers continued..


• const:
• Once defined, their values cannot be changed.
• Called as literals and their values are fixed.
• Syntax: const data_type variable_name
• volatile:
• Intended to prevent the compiler from applying any optimizations
• Their values can be changed by code outside the scope of current code at any time
• Also can be changed by any external device or hardware
• Syntax: volatile data_type variable_name
• Coding Examples
PROBLEM SOLVING WITH C
Qualifiers in C
Applicability of Qualifiers to Basic Types

No. Data Type Qualifier


1. char signed, unsigned

2. int short, long, signed, unsigned

3. float No qualifier

4. double long

5. void No qualifier
THANK YOU

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Preprocessor Directives

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
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

• A text substitution tool and instructs the compiler to do required pre-processing


before the actual compilation

• All pre-processor commands begin with a hash symbol (#)

• 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

Types of Preprocessor Directives


• Types include:
• Macros

• 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

• A piece of code in a program which has been given a name

• During preprocessing, it substitutes the name with the piece of code

• #define directive is used to define a macro.

• Example: #define PI 3.14

• Coding Examples
PROBLEM SOLVING WITH C
Preprocessor Directives

Points to know about Macros

• Macro does not judge anything


• No memory Allocation for Macros
• Can define string using macros
• Can define macro with expression
• Can define macro with parameter
• Macro can be used in another macro
• Constants defined using #define cannot be changed using the assignment operator
• Redefining the macro with #define is allowed. But not advisable
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 is substituted at pre-processing stage and enum constants are not.

• 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.

• Adding user defined header files in the program


PROBLEM SOLVING WITH C
Preprocessor Directives

Conditional Compilation Directives

• 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

• #undef Directive: Used to undefine an existing macro

• Example: #undef LIMIT

• 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

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
UE23CS151B

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C

Portable Program Development

Prof. Sindhu R Pai


Department of Computer Science and Engineering
PROBLEM SOLVING WITH C
Portable Program Development

• 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

Prof. Sindhu R Pai


Department of Computer Science and Engineering

Common questions

Powered by AI

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 .

You might also like