0% found this document useful (0 votes)
32 views156 pages

LBC PPT All Unit

lbc

Uploaded by

sahastracasual
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)
32 views156 pages

LBC PPT All Unit

lbc

Uploaded by

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

St.

Vincent Pallotti College of Engineering & Technology


Department of Information Technology
Academic Session- 2024-25

Subject : Logic Building with C


Unit-1
Presented By-
Mr. Jagdish Pimple
(Asst.Prof., IT )
Basics of Programming Languages
 Data
 Information
 Language
 Programs
 Instructions
 Syntax
 Semantics
 Programming Language
 Errors & its types
Types of Computer Languages
• High level language- Known to the User (C, C++, Java etc.)
• Low Level /Machine/Binary Language- Known to the
Machine only (0’s and 1’s)
• Assembly Language- It is intended to communicate directly
with a computer’s hardware
What is C Programing?
• C is a general-purpose programming language created by
Dennis Ritchie at the Bell Laboratories in 1972.

• It is a very popular language, despite being old. The main


reason for its popularity is because it is a fundamental language
in the field of computer science.

• C is strongly associated with UNIX, as it was developed to write


the UNIX operating system
What are the Most Important Features of C
Language?
• Procedural Language
• Fast and Efficient
• Modularity
• Statically Type (Type of data type known at compile
time)
• General-Purpose Language
• Rich set of built-in Operators
• Libraries with Rich Functions
• Portability
• Easy to Extend
Statically Typed vs Dynamically Typed Languages
• In statically typed programming languages, type checking occurs
at compile time. At compile time, source code in a specific
programming language is converted to a machine-readable format.
This means that before source code is compiled, the type
associated with each and every single variable must be
known.Example C,C++, Java
• in dynamically typed languages, type checking takes place
at runtime or execution time. This means that variables are
checked against types only when the program is executing. Some
examples of programming languages that belong to this category
are Python, JavaScript, Lisp, PHP, Ruby, Perl, Lua, and Tcl.
Program Translator
It translate a program written in one programming language into another.
Language translators are also called language processors.
There are three types of language translators:
• Compilers- It translate the complete program into a machine language
at a time and at last give a list of errors and list of warnings.
• Interpreters-It translate the code into machine language line by line.
• Assemblers- It translate a program written in assembly language into
machine language.
Algorithm & Its Characteristics
• An algorithm is a finite set of instructions or logic, written in order, to
accomplish a certain predefined task. Algorithm is not the complete code or
program, it is just the core logic(solution) of a problem, which can be
expressed either as an informal high level description as pseudocode or
using a flowchart.
Every Algorithm must satisfy the following properties/ characteristics:

• Input- There should be 0 or more inputs supplied externally to the


algorithm.

• Output- There should be at least 1 output obtained.

• Definiteness- Every step of the algorithm should be clear and well defined.

• Finiteness- The algorithm should have finite number of steps.

• Correctness/Effectiveness- Every step of the algorithm must generate a


correct output.
Flowchart
A flowchart is a type of diagram that represents a workflow or process. A
flowchart can also be defined as a diagrammatic representation of an
algorithm, a step-by-step approach to solving a task.
Uses of Flowcharts in Computer
Programming/Algorithms

• It is a pictorial representation of an algorithm that increases


the readability of the program.
• Complex programs can be drawn in a simple way using a
flowchart.
• It helps team members get an insight into the process and use
this knowledge to collect data, detect problems, develop
software, etc.
• A flowchart is a basic step for designing a new process or
adding extra features.
• Communication with other people becomes easy by drawing
flowcharts and sharing them.
Problem-solving strategies
1. Top-Down approach
2. Bottom-Up Approach
In the top-down approach, a complex algorithm is broken down
into smaller fragments, better known as ‘modules.’ These
modules are then further broken down into smaller fragments
until they can no longer be fragmented. This process is called
‘modularization.’ Example-C, Fortran, Pascal
How the Top-Down Approach Works?
1. Identify the goal or problem
2. Break it down into sub-goals
3. Solve each sub-goal/sub-problem:
4. Repeat steps 2 and 3 until the overall goal/problems are
resolved
Bottom-up programming focuses on designing an algorithm by
beginning at the very basic level and building up as it goes. In this
approach, the modules are designed individually and are then
integrated together to form a complete algorithmic design. Example-
C++, Java etc.
How the Bottom-Up Approach Works?
1. Identify the components or tasks
2. Build the system or solution
3. Test
4. Repeat steps 2 and 3
C Pre-processor Directives
• Preprocessor programs provide preprocessor directives that tell the
compiler to preprocess the source code before compiling. All of
these preprocessor directives begin with a ‘#’ (hash) symbol.
• In almost every C program we come across, we see a few lines at
the top of the program preceded by a hash (#) sign. They are called
preprocessor directives and are preprocessed by the preprocessor
before actual compilation begins.
Types of C Preprocessors
There are 4 Main Types of Preprocessor Directives:
• Macros
• File Inclusion
• Conditional Compilation
• Other directives
1. Macros
In C, Macros are pieces of code in a program that is given some name. Whenever
this name is encountered by the compiler, the compiler replaces the name with the
actual piece of code. The ‘#define’ directive is used to define a macro.
#define token value
Example-1. #define PI 3.14159
2. #define SQUARE(x) ((x) * (x))
2. File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source
code program. The #include preprocessor directive is used to include the header
files in the C program.
#include <file_name>
3. Conditional Compilation
#if Directive
#ifdef Directive
#ifndef Directive
#else Directive
#elif Directive
#endif Directive
4. Other Directives
• #undef Directive- The #undef directive is used to undefine an
existing macro.
• #pragma Directive-This directive is a special purpose directive
and is used to turn on or off some features. These types of
directives are compiler-specific, i.e., they vary from compiler
to compiler.
Some of the #pragma directives are discussed below:
• #pragma startup: These directives help us to specify the
functions that are needed to run before program startup
(before the control passes to main()).
• #pragma exit: These directives help us to specify the
functions that are needed to run just before the program exit
(just before the control returns from main()).
C Comments
• A comment makes the program easier to read and
understand. These are the statements that are not executed
by the compiler or an interpreter.
Tokens in C
A token in C can be defined as the smallest individual element of
the C programming language that is meaningful to the compiler.
It is the basic component of a C program.
C - Variables
A variable in C is a memory location with some name that helps store some
form of data and retrieves it when required. We can store different types of
data in the variable and reuse the same variable for storing some other data
any number of times.
• Syntax for variable Declaration-
data_type variable_name; //Single variable
data_type variable_name1, variable_name2; // defining multiple variable
• Syntax for variable initialization-
data_type variable_name = value; // defining single variable
Here,
data_type: Type of data that a variable can store.
variable_name: Name of the variable given by the user.
value: value assigned to the variable by the user.
Example-
int var; // integer variable
char a; // character variable
float fff; // float variables
Rules for Naming Variables in C
You can assign any name to the variable as long as it follows the following
rules:
• A variable name must only contain alphabets, digits, and underscore.
• A variable name must start with an alphabet or an underscore only. It
cannot start with a digit.
• No whitespace is allowed within the variable name.
• A variable name must not be any reserved word or keyword.
C Variable Types

• A Local variable in C is a variable that is declared inside a


function or a block of code. Its scope is limited to the block or
function in which it is declared.

• A Global variable in C is a variable that is declared outside the


function or a block of code. Its scope is the whole program i.e.
we can access the global variable anywhere in the C program
after it is declared.
Data Types in C
Each variable in C has an associated data type. It specifies the type of data
that the variable can store like integer, character, floating, double, etc.
Each data type requires different amounts of memory and has some
specific operations which can be performed over it.
Boolean in C
• In C, the bool data type is not a built-in data type. However,
the C99 standard for C language supports bool variables.
Boolean can store values as true-false, 0-1, or can be yes-no.
It can be implemented in C using different methods as
mentioned below:
• Using header file “stdbool.h”
• Using Enumeration type
• Using define to declare boolean values
bool a = true;
bool b = false;
Escape Sequence in C
Basic Input and Output in C
• C language has standard libraries that allow input and output in a
program. The stdio.h or standard input output library in C that
has methods for input and output.
scanf()
• The scanf() method, in C, reads the value from the console as per
the type specified and store it in the given address.
Syntax:
scanf("%X", &variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler
what type of data is in a variable and & is the address operator in C,
which tells the compiler to change the real value of variableOfXType,
stored at this address in the memory.
printf()
• The printf() method, in C, prints the value passed as the
parameter to it, on the console screen.

Syntax: printf("%X", variableOfXType);

• where %X is the format specifier in C. It is a way to tell the


compiler what type of data is in a variable
and variableOfXType is the variable to be printed.
• Example-
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);
St. Vincent Pallotti College of Engineering & Technology
Department of Information Technology
Academic Session- 2024-25

Subject : Logic Building with C


Unit-2
Presented By-
Mr. Jagdish Pimple
(Asst.Prof., IT )
C Tokens
The smallest individual units in a program are called
tokens.
The ‘C’ tokens are classified as:
1. Character set
2. Keywords
3. Identifiers
4. Constants
5. Operators
Character set
Character set consists of
i) Alphabet from A-Z or a-z
ii) Digits from 0-9
iii) Special characters like (,), {,}, [,], , &, $, #, %, ^, !, ?, :, ;,
",', .
iv) White space character: blank space
v) Escape sequences:
Keywords in C
• Keywords are predefined or reserved words that have special
meanings to the compiler. These are part of the syntax and
cannot be used as identifiers in the program.
(Total 32 Keywords in C programming )
Identifiers
• Identifier refers to the names of the variables,
functions and arrays.
Rules to name
1. It must start with either alphabet or underscore.
2. Remaining letters may be alphabet, digit, underscore.
3. Identifier would not allow any special symbol except
underscore.
4. An identifier can be of any length while most compilers of ‘C’
language recognize only the first 8 characters.
5. Do not use keywords as an identifier.
Constants
• Constants refer to fixed values that do not change during the
execution of a program.
Constants are 2 types.
1. Numerical constants
• Integer constants - 23, -56 etc.
• Real constants - 99.36, -89.5
2. Non-numerical constants
• Character constants - ‘a’, ‘1’, ‘ ’, etc
• String or multiple character constants –”abc”, “pq1”
Syntax to Define Constant
const data_type var_name = value;
Properties of Constant in C
1. Initialization with Declaration
We can only initialize the constant variable in C at the
time of its declaration. Otherwise, it will store the
garbage value.
2. Immutability
The constant variables in c are immutable after its
definition, i.e., they can be initialized only once in the
whole program. After that, we cannot modify the value
stored inside that variable.
Defining Constant using #define
Preprocessor
• #define const_name value
C Booleans
In programming, you will need a data type that can only have one of two values,
like:
• YES / NO
• ON / OFF
• TRUE / FALSE
For this, C has a bool data type, which is known as booleans.
Booleans represent values that are either true or false.
import the #include <stdbool.h>
C Enumeration (enum)
• An enum is a special type that represents a group of constants
(unchangeable values).
• To create an enum, use the enum keyword, followed by the
name of the enum, and separate the enum items with a
comma:
Enum Example

Output- The value of w is 2


Typedef in C
• The typedef is a keyword used in C programming to provide
some meaningful names to the already existing variable in
the C program. It behaves similarly as we define the alias for
the commands. In short, we can say that this keyword is used
to redefine the name of an already existing variable.

Syntax of typedef- typedef <existing_name> <alias_name> ;

Example- typesdef int num;


num n1,n2;
Output-
Value of i is :10
Value of j is :20
Operators in C
• Operators are used to perform operations on variables
and values.
C divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Arithmetic operators
Comparison Operators
Logical Operators
Assignment Operators
C Logical Operators
Bitwise Operators
• In C, the bitwise NOT operator (~) inverts the bits of a
number. For positive integers, the result is calculated
as:
∼n=−(n+1)
Example : ~6=−(6+1)=−7
For negative integers, the result is calculated as:
∼(-n)=(n-1)
Example: -~(-6)=(6-1)=5
• Left-shifting an integer “a” with an integer “b”
denoted as ‘(a<<b)’ is equivalent to
multiplying a with 2^b (2 raised to power b).

• Right-shifting an integer “a” with an integer


“b” denoted as ‘(a>>b)‘ is equivalent to
dividing a with 2^b.
Types of Control Statements in C
• Decision-making control statements

Simple if Statement If-Else Statement Nested If-Else Statement


Else-if Ladder Statements
C Switch Statement
Looping Statement
While loop
Do_While loop
Print the table from 1 to 10
for loop
Program on Patterns
#include <stdio.h>
int main()
{
int i, j, r;
printf("Input the number of rows: ");
scanf("%d", &r);
for (i = 1; i <= r; i++)
{
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
}
return 0;
}
St. Vincent Pallotti College of Engineering & Technology
Department of Information Technology
Academic Session- 2024-25

Subject : Logic Building with C


Unit-3
Presented By-
Mr. Jagdish Pimple
(Asst.Prof., IT )
Arrays
An array in C is a fixed-size collection of similar data items stored in
contiguous memory locations. It can be used to store the collection
of primitive data types such as int, char, float, etc., and also derived
and user-defined data types such as pointers, structures, etc.
C Array Declaration-
data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];
C Array Initialization-
Initialization in C is the process to assign some initial value to the
variable. When the array is declared or allocated memory, the
elements of the array contain some garbage value. So, we need
to initialize the array to some meaningful value. There are
multiple ways in which we can initialize an array in C.
• Array Initialization with Declaration
data_type array_name [size] = {value1, value2, ...
valueN};
Array Initialization with Declaration without Size
If we initialize an array using an initializer list, we can skip
declaring the size of the array as the compiler can automatically
deduce the size of the array in these cases.
data_type array_name[] = {1,2,3,4,5};
Access Array Elements-We can access any element of an array in
C using the array subscript operator [ ] and the index value i of
the element.
array_name [index];
Update Array Element-
We can update the value of an element at the given index i in a
similar way to accessing an element by using the array subscript
operator [ ] and assignment operator =.
array_name[i] = new_value;

There are two types of arrays based on the number of


dimensions it has. They are as follows:
• One Dimensional Arrays (1D Array)
array_name [size];
Basic Operations in Arrays

• Traverse − print all the array elements one by one.


• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the
value.
• Update − Updates an element at the given index.
• Display − Displays the contents of the array.
Array - Search Operation (Linear Search)

Searching an element in the array using a key. The key


element sequentially compares every value in the array
to check if the key is present in the array or not.
Array Sorting
Sorting an array means arranging the elements of the array in a
certain order. Generally sorting in an array is done to arrange the
elements in increasing or decreasing order.
Bubble Sort-
Two-Dimensional Array in C
A Two-Dimensional array or 2D array in C is an array that has exactly two
dimensions. They can be visualized in the form of rows and columns
organized in a two-dimensional plane.
array_name[size1] [size2];
Here,
• size1: Row Size of the first dimension.
• size2: Column Size of the second dimension.
int arr[3][3];
Initializing Arrays
• We have two different methods in initializing the values in C.
The methods only differ syntactically.

Another way of initializing is as follows:


Inserting & Display Elements of 2-D Arrays
St. Vincent Pallotti College of Engineering & Technology
Department of Information Technology
Academic Session- 2024-25

Subject : Logic Building with C


Unit-4
Presented By-
Mr. Jagdish Pimple
(Asst.Prof., IT )
Pointers in C
A pointer is a variable that stores the memory address of
another variable as its value.
Declaring a pointer
The pointer in C language can be declared using * (asterisk
symbol). It is also known as indirection pointer used to
dereference a pointer.
– int *a; //pointer to int
– char *c; //pointer to char

int *p;
int number=50;
p=&number
Functions in C
• In c, we can divide a large program into the basic building blocks
known as function. The function contains the set of
programming statements enclosed by {}. A function can be
called multiple times to provide reusability and modularity to
the C program. In other words, we can say that the collection of
functions creates a program.
• A function is a block of code which only runs when it is called.
Types of Function-
• Predefined function (Built-in Function/Library functions)- The
function which is already defined in system. (e.g.
gets(),puts(),printf() scanf() etc.)
• User-defined functions- The function which is created by the
user as per his requirement.
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
• Function Declaration- In a function declaration, we must provide the
function name, its return type, and the number and type of its
parameters. A function declaration tells the compiler that there is a
function with the given name defined somewhere else in the program.
Syntax-
return_type Name_of_the_function (parameter_1, parameter_2);
Example-
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
Function Definition
The function definition consists of actual statements which are
executed when the function is called (i.e. when the program control
comes to the function).
return_type function_name (para1_type para1_name, para2_type
para2_name)
{
// body of the function
}
Function Call
• A function call is a statement that instructs the compiler to
execute the function. We use the function name and
parameters in the function call.
Passing Parameters to Functions
The data passed when the function is
being invoked is known as the Actual
parameters.
We can pass arguments to the C
function in two ways:
• Pass by Value
• Pass by Reference

Pass by Value-Parameter passing in this


method copies values from actual
parameters into formal function
parameters. As a result, any changes
made inside the functions do not reflect
in the caller’s parameters.
Pass by Reference- The caller’s actual parameters and the function’s actual
parameters refer to the same locations, so any changes made inside the function
are reflected in the caller’s actual parameters.
Advantages of Functions in C
• Functions in C is a highly useful feature of C with many advantages as
mentioned below:
• The function can reduce the repetition of the same statements in the
program.
• The function makes code readable by providing modularity to our
program.
• There is no fixed number of calling functions it can be called as many
times as you want.
• The function reduces the size of the program.
• Once the function is declared you can just use it without thinking
about the internal working of the function.
Disadvantages of Functions in C
• The following are the major disadvantages of functions in C:
• Cannot return multiple values.
• Memory and time overhead due to stack frame allocation and transfer
of program control.
Recursion in C
Recursion is the process of a function calling itself repeatedly till
the given condition is satisfied. A function that calls itself directly
or indirectly is called a recursive function and such kind of
function calls are called recursive calls.
Basic Structure of Recursive Functions-
C Structure
• Structure in c is a user-defined data type that enables us to
store the collection of different data types. Each element of a
structure is called a member. Structures ca; simulate the use of
classes and templates as it can store various information.
struct structure_name
{ struct employee
data_type member1; { int id;
data_type member2; char name[20];
. float salary;
. };
data_type memeberN;
};
Structure Variable Declaration with Structure Template
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

Structure Variable Declaration after Structure Template


struct structure_name variable1, variable2, .......;

Access Structure Members


structure_name.member1;
strcuture_name.member2;

Initialize Structure Members-Structure members cannot be initialized with the


declaration. struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
Array of Structures in C
An array of structres in C can be defined as the collection of multiple structures
variables where each variable contains information about different entities. The
array of structures in C are used to store information about multiple entities of
different data types. The array of structures is also known as the collection of
structures.
Structure Pointer in C
• A structure pointer is defined as the pointer which points to
the address of the memory block that stores
a structure known as the structure pointer.
Accessing the Structure Member with the Help
of Pointers
There are two ways to access the members of the structure with
the help of a structure pointer:
• With the help of (*) asterisk or indirection operator and (.) dot
operator.
• With the help of ( -> ) Arrow operator.
Union in C
Union can be defined as a user-defined data type which is a
collection of different variables of different data types in the
same memory location. The union can also be defined as many
members, but only one member can contain a value at a
particular point in time.
Defining a Union-
St. Vincent Pallotti College of Engineering & Technology
Department of Information Technology
Academic Session- 2024-25

Subject : Logic Building with C


Unit-5
Presented By-
Mr. Jagdish Pimple
(Asst.Prof., IT )
File Handling in C
File handling in C is the process of handling file operations such as
creating, opening, writing data, reading data, renaming, and
deleting using the C language functions. With the help of these
functions, we can perform file operations to store and retrieve the
data in/from the file in our program.
Need of File Handling in C-
If we perform input and output operations using the C program,
the data exists as long as the program is running, when the
program is terminated, we cannot use that data again. File
handling is required to work with files stored in the external
memory i.e., to store and access the information to/from the
computer's external memory. You can keep the data permanently
using file handling.
Types of Files
A file represents a sequence of bytes. There are two types of
files: text files and binary files −
• Text file − A text file contains data in the form of ASCII
characters and is generally used to store a stream of
characters. Each line in a text file ends with a new line
character ("\n"), and generally has a ".txt" extension.
• Binary file − A binary file contains data in raw bits (0 and 1).
Different application programs have different ways to
represent bits and bytes and use different file formats. The
image files (.png, .jpg), the executable files (.exe, .com), etc.
are the examples of binary files.
Process of File handling
File Operations
The following operations can be performed on a file.
• Creation of the new file
• Opening an existing file
• Reading from the file
• Writing to the file
• Deleting the file
FILE Pointer (File*)- While working with file handling, you need
a file pointer to store the reference of the FILE structure returned
by the fopen() function. The file pointer is required for all file-
handling operations.
Declaring a File Pointer (FILE*)
FILE* file_pointer;
FILE is basically a data type, and we need to create a pointer
variable to work with it (fptr)
Various pre-defined functions for handling files
Opening File: fopen()
We must open a file before it can be read, write, or update. The
fopen() function is used to open a file. The syntax of the fopen()
is given below.
FILE *fptr;
fptr = fopen(filename, mode);

• file_name: name of the file when present in the same


directory as the source file. Otherwise, full path.
• access_mode: Specifies for what operation the file is being
opened.
File opening modes in C
Create a File
Opening a File in Read Mode
Closing a File
Each file must be closed after performing operations on it.
The fclose() function closes an opened file.

Syntax-
fclose(FILE *fp);

• The fclose() function returns zero on success, or EOF if there


is an error in closing the file.
• The fclose() function actually flushes any data still pending in
the buffer to the file, closes the file, and releases any memory
used for the file. The EOF is a constant defined in the header
file stdio.h.
Writing to a Text File
The following library functions are provided to write data in a file
opened in writeable mode −
• fputc() : Writes a single character to a file.
• fputs(): Writes a string to a file.
• fprintf(): Writes a formatted string (data) to a file.
Use of fputc()
Writing String to a File
The fputs() function writes the string "s" to the output stream referenced by
"fp". It returns a non-negative value on success, else EOF is returned in case
of any error.
Writing Formatted String to a File
• The fprintf() function sends a formatted stream of data to the disk file
represented by the FILE pointer.
Reading from a Text File

The following library functions are provided to read data from a


file that is opened in
• fgetc(): Reads a single character from a file.
• fgets(): Reads a string from a file.
• fscanf(): Reads a formatted string from a file.
Reading Single Character from a File fgetc()
fgets() function
• The fgets() function reads a line of characters from file. It gets
string from a stream.
Syntax: char* fgets(char *s, int n, FILE *stream)
Reading File : fscanf() function
• The fscanf() function is used to read set of characters from
file. It reads a word from the file and returns EOF at the end of
file.
Getw() and Putw() function in C
• putw() is used for writing a number into file.
The syntax − putw (int num, FILE *fp);

• getw( ) function is used for reading a number from a file.


Syntax- int getw (FILE *fp);
ftell function in file handling
In C programming, ftell and fseek are standard functions used in file
handling to manipulate and track the position of the file pointer. These
functions are part of the <stdio.h> library.
ftell() Function- The ftell function is used to get the current position of the
file pointer in a stream.
long ftell(FILE *stream);
fseek() Function
fseek() Function- The fseek() function is used to set the file
pointer to the specified offset. It is used to write data into file at
desired location.
fseek(FILE *filePointer, long offset, int origin);
• filePointer: The file pointer we want to modify.
• offset: The number of bytes to move the file pointer that can
be positive or negative.
• origin: The starting point from where the offset is calculated.
It can take one of the following values:
– SEEK_SET: Beginning of the file.
– SEEK_CUR: Current position of the file pointer.
– SEEK_END: End of the file.
Program to copy content of one file into another
Command Line Arguments in C
• The arguments passed from command line are called
command line arguments. These arguments are handled by
main() function.
• To support command line argument, you need to change the
structure of main() function as given below.
int main(int argc, char *argv[] )
• Here, argc counts the number of arguments. It counts the file
name as the first argument.
• The argv[] contains the total number of arguments. The first
argument is the file name always.
Dynamic memory allocation in C

The concept of dynamic memory allocation in c language enables


the C programmer to allocate memory at runtime. Dynamic
memory allocation in c language is possible by 4 functions of
stdlib.h header file.
• malloc()
• calloc()
• realloc()
• free()
malloc() method
The “malloc” or “memory allocation” method in C is used to
dynamically allocate a single large block of memory with the
specified size.
Syntax- ptr = (cast-type*) malloc(byte-size)
calloc() function in C
The calloc() function allocates multiple block of requested
memory.
• It initially initialize all bytes to zero.
• It returns NULL if memory is not sufficient.
The syntax of calloc() function is given below:
ptr=(cast-type*)calloc(number, byte-size)
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can
reallocate the memory by realloc() function. In short, it changes the
memory size.
Syntax- ptr=realloc(ptr, new-size)
free() method
“free” method in C is used to dynamically de-allocate the memory.
The memory allocated using functions malloc() and calloc() is not de-
allocated on their own.
Syntax- free(ptr);
C Programming Strings
A string in C is a one-dimensional array of char type, with the last
character in the array being a "null character" represented by '\0'.
Thus, a string in C can be defined as a null-terminated sequence of
char type values.
char greetings[] = "Hello World!";

char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
Access Strings-

Modify Strings-
Standard Library String Functions:
String Length

we used sizeof to get the size of a string/array. Note


that sizeof and strlen behaves differently,
as sizeof also includes the \0 character when counting:
Concatenate Strings
To concatenate (combine) two strings, you can use
the strcat() function:
Copy Strings
To copy the value of one string to another, you can use
the strcpy() function:
Compare Strings
• To compare two strings, you can use the strcmp() function.
• It returns 0 if the two strings are equal, otherwise a value that
is not 0:

You might also like