0% found this document useful (0 votes)
18 views

Unit 1-2

Uploaded by

tamilakm2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Unit 1-2

Uploaded by

tamilakm2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

C PROGRAMMING BASICS

1.1 HISTORY OF C LANGUAGE

Basic combined programming language (BCPL) called B was created at


1960’s at Cambridge University. B language has been recreated as C at Bell
Laboratories by Dennis Ritchie in 1972.

1.2 WHAT IS C LANGUAGE?

C is a general-purpose procedural, high level programming language used


in the development of computer software and application, system programming, games
and more.

1.3 STRUCTURE OF A C PROGRAMMING

For every programming language there is a specific structure to start and


write the program. Even our body part has a specific structure called body structure. In
same way there is a specific structure in C programming. Without a structure it
becomes difficult to analyze the problems and solution in the program.

1. Documentation section
2. Link section
3. Definition section
4. Global definition section
5. Main () function section
{
Declaration part
Execution part
}
6. Sub program section
{
Function-1
Function-2
….
…. User defined functions
….
Function-n
}

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 1


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

/*Program to find the area of circle*/ Documentation section


#include<stdio.h>
Link section
#include<conio.h>
#define pi 3.14 Definition section
float r=7
Global Declaration section
void area ();
void main (); Main function section
{
clrscr();
area(); Execution part
getch();
}
void area
{
float ar ;
ar = pi*r*r ; Sub program section
print(“ The area of the circle:%f ”,ar):
}

1.4 TOKENS

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.

Types of Tokens in C

The tokens of C language can be classified into six types based on the functions
they are used to perform. The types of C tokens are as follows
✓ Keywords
✓ Identifiers
✓ Constants
✓ Strings
✓ Special Symbols
✓ Operators

1.4.1 Keyword

➢ The keyword are pre-defined or reserved words in a programming language.


➢ Each keyword is meant to perform a specific function in a program.

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 2


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

➢ Since keywords are referred names for a compiler, they cannot be used as variable
names. C language supports 32 keywords which are given below

auto double struct int


break else switch long
case enum typedef register
char extern return union
const short float unsigned
continue for void signed
default sizeof goto volatile
do if static while

1.4.2 Identifiers

✓ Identifiers are used as the general terminology for the naming of variables,
functions, and arrays.
✓ Once declared, you can use the identifier in later program statements to refer to the
associated value.
Rules for Naming Identifiers

Certain rules should be followed while naming C identifiers which are as follows:

 They must begin with a letter or underscore (_).


 They must consist of only letters, digits, or underscore. No other special
character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are
significant.

Identifiers Valid / Invalid Reason for invalid


Num Valid -
_add Valid -
num-add Invalid Contains special character (-)
This is one of the keyword. Keyword
auto Invalid
cannot be used as identifier names.
Name must start begins with an
2myfile Invalid
alphabet or an underscore

Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different.

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 3


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

1.4.3 Constants

❖ The constants refer to the variables with fixed values.


❖ They are like normal variables but with the difference that their values cannot be
modified in the program once they are defined.
❖ Constants may belong to any of the data types.
Eg of Constants:
const int c_var = 20;

Integer Constant
Numeric
Constant
Real Constant
CONSTANT
Single Constant
Character
Constant
String Constant

The above flowchart explains the several types of Constants

INTEGER CONSTANT

An integer constant refers to a sequence of digits. There are three types of integer
namely;
 Decimal Integer Constant
 Octal Integer Constant
 Hexadecimal Integer Constant

A. Decimal Integer Constant

In C programming, a decimal integer constant is a sequence of digits that represents a


whole number in base 10 (decimal system). These constants are used to define fixed
values that don't change during the execution of a program.

Here are the main characteristics of decimal integer constants in C:

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 4


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

1. Digits: Decimal integer constants use digits from 0 to 9.


2. No Leading Zeros: They should not have leading zeros, as leading zeros indicate
an octal (base 8) constant.
3. Optional Sign: They can optionally be preceded by a plus (+) or minus (-) sign to
indicate positive or negative values.
4. Range: The range of values that a decimal integer constant can represent depends
on the type of the constant, which can be influenced by suffixes and the size of the
data type (e.g., int, long, unsigned).

Examples
• ‘123’ is a decimal integer constant representing the value 123.
• ‘-456’ is a decimal integer constant representing the value -456.
• ‘0’ is a decimal integer constant representing the value 0.
• ‘2147483647’ is the largest value a 32-bit signed integer constant can represent.

Suffixes
Suffixes can be added to decimal integer constants to specify their type explicitly:
• ‘U’ or ‘u’ for unsigned int (e.g., 123U).
• ‘L’ or ‘l’ for long int (e.g., 123L).
• ‘UL’, ‘Ul’, ‘uL’, ‘ul’, ‘LU’, ‘Lu’, ‘lU’, or ‘lu’ for unsigned long int (e.g., 123UL).

Examples with Suffixes


• 100U specifies an unsigned int with a value of 100.
• 123L specifies a long int with a value of 123.
• 456UL specifies an unsigned long int with a value of 456.

NOTE: Using decimal integer constants correctly ensures that the program behaves
as expected and avoids issues related to type conversions and overflows.

B. Octal Integer Constant

In C programming, an octal integer constant is a numerical value that is represented in


base-8 (octal) numbering system. Octal numbers use digits from 0 to 7. In C, an octal
constant is specified by prefixing the number with a 0 (zero).

Here are some examples of octal integer constants

• ‘012’ (which is 10 in decimal)


• ‘077’ (which is 63 in decimal)
• ‘01’ (which is 1 in decimal)

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 5


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

Rules for Octal Constants

1. Prefix with Zero: An octal constant must start with a 0.


2. Valid Digits: The digits must be between 0 and 7.

Usage in C

Octal constants are commonly used in scenarios like setting file permissions or working
with hardware registers.
OUTPUT:

In this example, the octal number 012 is assigned to the variable octalNumber, and when
printed, it shows the decimal equivalent, which is 10.

Note: Avoid using digits 8 and 9 in octal constants since they are not valid in base-8
and will result in a compile-time error.

C. Hexadecimal Integer Constant

In C programming, a hexadecimal integer constant is a way to represent integer


values using the base-16 numeral system, which includes digits from 0 to 9 and letters
from A to F (or a to f) to represent values 10 to 15. Hexadecimal constants are often used
because they are more compact and can represent large numbers more conveniently
compared to decimal or binary formats

Syntax:
A hexadecimal integer constant in C is prefixed with ‘0x’ or ‘0X’.

For example
 ‘0x1A3F’
 ‘0X7B’

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 6


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

Examples

Usage:
Hexadecimal constants are commonly used for:
 Representing memory addresses.
 Defining bit masks.
 Working with hardware registers.
 Representing colors in graphics programming.

Note on Suffixes
Just like decimal integer constants, hexadecimal integer constants can also have suffixes
to indicate their type:
 ‘U’ or ‘u’ for unsigned int  ‘UL’, ‘ul’, ‘LU’, or ‘lu’ for unsigned long int
 ‘L’or ‘l’ for long int  ‘LL’ or ‘ll’ for long long int

Examples with suffixes:

By using hexadecimal integer constants, you can make your code more readable and
concise, especially when dealing with low-level programming tasks.

REAL CONSTANTS

In C programming, real constants, also known as floating-point constants, represent real


numbers (numbers that have a fractional part). These constants are used to define values
of the float, double, and long double data types. Here are some key points about real
constants in C:

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 7


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

Syntax

 Real constants can be expressed in decimal form (e.g., 3.14, 0.001, -123.456).
 They can also be expressed in exponential (scientific) notation (e.g., 1.23e4,
6.022e23, -2.5e-3), where e or E denotes the exponent part.

Examples

Usage:

Real constants are used in mathematical computations, scientific calculations, and


anywhere fractional values are required.

SINGLE CHRACTER CONSTANTS

❖ A "character constant" is formed by enclosing a single character from the


representable character set within single quotation marks (' '). Character
constants are used to represent characters in the execution character set.
❖ The type of a single character constant in C is int, not char. This is because
character constants represent the corresponding integer value of the character in
the ASCII table (or the character set being used).
❖ Single character constants can include escape sequences to represent characters that
are not easily typed or visible, such as '\n' for newline, '\t' for tab, '\0' for null
character, and ‘'\'’ for a single quote.Here is a example

STRING CONSTANTS
 A string constant is a sequence of character enclosed in a double quotes. The
characters may be letters, numbers, special chracters and blank spaces.
 A character constant cannot be a string character.

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 8


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

 This type of constant represents a null-terminated array of characters, where the


compiler automatically appends a null character ('\0') at the end of the string to mark
its termination.
 String character constants can be used directly in functions that accept strings.
For example, printf("%s\n", "hello"); directly prints the string "hello".

Example:

This constant helps us to shows the output as what


we type.

1.4.4 OPERATORS
✓ Operators are special symbols that trigger an action when applied to C variables
and other objects.
✓ The data items on which operators act are called operands.
✓ Depending on the number of operands that an operator can act upon, operators can
be classified as follows:
 Unary operator
 Binary operator
 Ternary operator

1.4.4.1 Unary operator:


Those operators that require only a single operand to act upon are known as
unary operators. For Example: Increment and Decrement operators

Operator Operation Examples


++ Increament operator a = 2;
a++; //Now a=3
-- Decreament operator a = 2;
a--; // Now a=1

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 9


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

1.4.4.2 Binary operator

Those operators that require two operands to act upon are called binary
operators. Binary operators can further are classified into:
• Arithmetic operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Bitwise Operator

Arithmetic operator:
Arithmetic operators are the symbols that are used to perform mathematical
operations on operands.

Operator Operation Examples


+ Addition 5+5=10
- Subtraction 5-3=2
* Multiplication 5*2=10
/ Division 9/3=3
% Modulus 5%2=1

Relational operators
Relational operators are the symbols that are used for comparison between two
values to understand the type of relationship

Operator Operation Examples


> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
== Is equal to a == b
!= Not equal to a != b

Logical operator
Logical operators in C are used to combine multiple conditions/constraints.
Logical Operators returns either 0 or 1, it depends on whether the expression result is
true or false. In C programming for decision-making, we use logical operators.
Operator Operation Examples
The logical AND combines two different relational expressions
&& Logical AND in to one. It returns 1 (True), if both expression are true,
otherwise it returns 0 (false).

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 10


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

The logical OR combines two different relational expressions in


|| Logical OR to one. It returns 1 (True), if either one of the expression is true.
It returns 0 (false), if both the expressions are false.

NOT works on a single expression / operand. It simply negates


! Logical NOT or inverts the truth value. i.e., if an operand / expression is 1
(true) then this operator returns 0 (false) and vice versa

Assignment operator
Assignment operators are used for assigning value to a variable. The left side
operand of the assignment operator is a variable and right side operand of the
assignment operator is a value. The value on the right side must be of the same data-
type of the variable on the left side otherwise the compiler will raise an error.

Operator Name of Operator Example


+= Addition Assignment a = 10;
c = a += 5;(ie, a = a + 5)
c = 15
−= Subtraction Assignment a = 10;
c = a -= 5;(ie. a = a – 5)
c=5
*= Multiplication Assignment a = 10;
c = a *= 5;(ie. a = a * 5)
c = 50
/= Division Assignment a = 10;
c = a /= 5;(ie. a = a / 5)
c=2
%= Modulus Assignment
a = 10;
c = a %= 5; (ie. a = a % 5)
c=0

Bitwise operator
Bitwise operators also known as bit operators as they work at the bit-level. They
are used to perform bitwise operations in C.
➢ The & (bitwise AND) in C takes two numbers as operands and does AND on
every bit of two numbers. The result of AND is 1 only if both bits are 1.
➢ The | (bitwise OR) in C takes two numbers as operands and does OR on every
bit of two numbers. The result of OR is 1 if any of the two bits is 1.
➢ The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on
every bit of two numbers. The result of XOR is 1 if the two bits are different.

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 11


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

➢ The << (left shift) in C takes two numbers, the left shifts the bits of the first
operand, and the second operand decides the number of places to shift.
➢ The >> (right shift) in C takes two numbers, right shifts the bits of the first
operand, and the second operand decides the number of places to shift.
➢ The ~ (bitwise NOT) in C takes one number and inverts all bits of it.

1.4.4.3 Ternary operator

 The operator that requires three operands to act upon is called the ternary
operator.
 The conditional operator in C is kind of similar to the if-else statement as it
follows the same algorithm as of if else statement but the conditional operator
takes less space and helps to write the if-else statements in the shortest way
possible.

Syntax :
The conditional operator can be in any on of the following form
variable = Expression1 ? Expression2 : Expression3;
variable = (condition) ? Expression2 : Expression3;
(condition) ? (variable = Expression2) : (variable = Expression3);

1.4.5 Special Symbols

The following special symbols are used in C having some special meaning and thus,
cannot be used for some other purpose. Some of these are listed below:
 Brackets []: Opening and closing brackets are used as array element
references. These indicate single and multidimensional subscripts.
 Parentheses (): These special symbols are used to indicate function calls and
function parameters.
 Braces {}: These opening and ending curly braces mark the start and end of a
block of code containing more than one executable statement.
 Comma (,): It is used to separate more than one statement like for separating
parameters in function calls.
 Colon (:): It is an operator that essentially invokes something called an
initialization list.
 Semicolon (;): It is known as a statement terminator. It indicates the end of
one logical entity. That is why each individual statement must be ended with
a semicolon.
 Asterisk (*): It is used to create a pointer variable and for the multiplication
of variables.
 Assignment operator (=): It is used to assign values and for logical
operation validation.

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 12


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

 Pre-processor (#): The preprocessor is a macro processor that is used


automatically by the compiler to transform your program before actual
compilation.
 Period (.): Used to access members of a structure or union.
 Tilde (~): Bitwise One’s Complement Operator.

1.5 DIFFERENCE BETWEEN VARIABLES AND CONSTANTS

 Constants are fixed values that do not  Variables are storage locations that
change during the execution of a hold data values which can change
program.In mathematics, they during program execution. In
represent a value that remains the same mathematics, variables represent
throughout a given context. quantities that can vary within a given
problem or equation.
 Constants are used when a value is  Variables are used to store information
known ahead of time and is not that can change as the program runs,
supposed to be altered. such as user inputs, counters, or
intermediate results of computations.
 Constants are immutable (cannot  Variables are mutable (can change value
change once defined). throughout the program).

 Constants are used for fixed values  Variables are used for values that need to
that provide consistency and clarity in change and be manipulated as the program
the code. executes.

Understanding the difference between constants and variables is crucial for writing clear,
maintainable, and efficient code.
1.6 MANAGING INPUT AND OUTPUT OPERATIONS

Managing input and output (I/O) operations is crucial in programming to interact


with users, read data from external sources, and output results. In C programming, I/O
operations are typically handled using functions from the <stdio.h> library. Here’s an
explanation of how input and output operations are managed in C

Input Operations

1. Standard Input (stdin):


 Input from the keyboard or other standard input devices is read using
functions like scanf() and fgets().

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 13


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num); // Reads an integer from standard input
printf("You entered: %d\n", num);
return 0;
}

 scanf() reads formatted input based on the specified format string. It stops reading when
encountering whitespace (space, tab, newline)
char name[50];
printf("Enter your name: ");
scanf("%s", name); // Reads a string (stops at whitespace)

 fgets() reads a line of text, including spaces, from stdin:

char sentence[100];
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin); // Reads a line of text

2. File Input:
 Files can be opened using fopen() and read using fscanf() or fgets():

#include <stdio.h>
int main() {
FILE *fp;
char str[100];
fp = fopen("file.txt", "r"); // Open file for reading
if (fp == NULL) {
perror("Error opening file");
return -1;
}
fscanf(fp, "%s", str); // Read a word from the file
printf("Read from file: %s\n", str);
fclose(fp); // Close the file
return 0;
}

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 14


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

Output Operations
1. Standard Output (stdout):
 Output to the console is done using printf():

#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}

printf() formats and prints output based on the format specifier.


int num = 10;
printf("The value of num is: %d\n", num);

2. File Output:
 Files can be opened using fopen() for writing ("w") or appending ("a"), and
data is written using fprintf() or fputs():

#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("output.txt", "w"); // Open file for writing
if (fp == NULL) {
perror("Error opening file");
return -1;
}
fprintf(fp, "This is written to the file.\n");
fclose(fp); // Close the file
return 0;
}

1.7 DECISION MAKING AND BRANCHING STATEMENTS

In C programming, decision-making and branching are fundamental


concepts that allow a program to take different paths based on conditions. These
concepts are primarily implemented using control flow statements. Here’s a
detailed overview:

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 15


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

Decision-Making in C
Decision-making in C involves evaluating conditions (usually Boolean
expressions) and executing code blocks based on whether the condition is true or false.
The main decision-making statements in C are:
 if Statement
 if-else Statement
 else-if Ladder
 switch Statement

 if Statement
The if statement evaluates a condition. If the condition is true, it executes the
block of code inside the if statement.

Syntax:
if (condition) {
// Code to execute if condition is true
}

Example of if statement:

#include<iostream.h>
int a=18;
void main() {
if (a>=18){
printf(“You are eligible for voting”); }
}

 if-else Statement
The if-else statement provides an alternative block of code that executes if the
condition is false.

Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 16


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

Example of if-else Statement


#include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("The number is positive.\n");
} else {
printf("The number is not positive.\n");
}
return 0;
}

 else-if Ladder
The else-if ladder allows for multiple conditions to be checked in sequence. The
first condition that evaluates to true will have its corresponding block executed.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (condition3) {
// Code to execute if condition3 is true
} else {
// Code to execute if all conditions are false
}

Example of else-if ladder:


#include <stdio.h>
int main()
{
int n = 0;
if (n > 0){ // all Positive numbers will make this condition
true
printf("Positive");
}
else if (n < 0) { // all Negative numbers will make this
condition true
printf("Negative");
}
else{ // if a number is neither Positive nor Negative
printf("Zero");
}
return 0;
}

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 17


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

 switch Statement
The switch statement is used for selecting one of many code blocks to execute. It
is particularly useful when you have a variable that can take on multiple discrete values.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More cases
default:
// Code to execute if expression does not match any case
}

Example of switch Statement

#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 18


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

Branching in C

Branching allows the program to jump to different parts of the code based on
certain conditions. The primary statements used for branching are goto, break, and
continue.

➢ goto Statement

The goto statement is used to transfer control to the labeled statement. It can make
the program logic hard to follow, so it is generally avoided in structured programming.

Syntax:

goto label;
// Some code
label:
// Code to execute after goto

Examples of goto statement:

#include<iostream.h>
void checkEvenOrNot(int num)
{
if (num % 2 == 0)
goto even; // jump to even
else
goto odd; // jump to odd
even:
printf("%d is even", num);
return; // return if even
odd:
printf("%d is odd", num);
}
int main()
{
int num = 26;
checkEvenOrNot(num);
return 0;
}

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 19


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

➢ break Statement
The break statement is used to exit from loops or switch statements prematurely.
Syntax:
break;

Example of break Statement in a Loop


#include <stdio.h>
int main()
{
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exit loop when i is 5
}
printf("%d\n", i);
}
return 0;
}

➢ continue Statement
The continue statement skips the remaining code in the current iteration of a loop
and proceeds to the next iteration.
Syntax:
continue;
Example of continue Statement in a Loop
#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip the even numbers
}
printf("%d\n", i);
}
return 0;
}

These constructs are essential for controlling the flow of a program and making decisions
based on different conditions

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 20


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

1.8 ARRAY AND ITS TYPES

In C programming, an array is a collection of elements of the same data type


stored in contiguous memory locations. Arrays are used to store multiple values of the
same type efficiently, and they can be accessed using an index.
TYPES OF ARRAYS IN C

 One-Dimensional Arrays

 Two-Dimensional Arrays

 Multi-Dimensional Array

 One-Dimensional Arrays:
✓ A one-dimensional array, also known as a linear array, is the simplest
form of an array in C.
✓ It is a list of elements that can be accessed sequentially using an index.
Syntax:
data_type array_name[array_size];

Examples:
int numbers[5] = {1, 2, 3, 4, 5};

 Two-Dimensional Arrays:
✓ Two-dimensional arrays can be thought of as an array of arrays, forming a
matrix or a table-like structure.
✓ They are commonly used for representing mathematical matrices or tables
of data.
Syntax:
data_type array_name[rows][columns];

Examples:
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8},{9, 10, 11, 12}};

 Multi-Dimensional Arrays:
✓ Arrays with more than two dimensions are called multi-dimensional
arrays.
✓ They are an extension of two-dimensional arrays and can be used to
represent data in multiple dimensions.

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 21


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

Syntax:
data_type array_name[size1][size2][size3]...[sizeN];

Examples:
int threeD[2][3][4]; // 3D array with dimensions 2x3x4

ACCESSING ARRAY ELEMENTS


 Indexing: Array elements are accessed using an index, which starts from 0. For
example, in a one-dimensional array numbers, numbers[0] accesses the first
element, numbers[1] accesses the second, and so on.
 Bounds: The size of the array defines the number of elements it can hold.
Accessing an element outside this range (out-of-bounds access) leads to undefined
behavior in C.

USES OF ARRAY
 The size of an array must be specified at compile time, and it cannot be changed
dynamically.
 Arrays in C are zero-indexed, meaning the first element is at index 0.
 The name of an array acts as a pointer to the first element of the array.
 Multi-dimensional arrays are stored in row-major order in memory, meaning the
last index changes the fastest.

1.9 STRING AND ITS OPERATIONS

String operations in C involve working with arrays of characters, as C does


not have a built-in string type like some other high-level languages. Here are some
common string operations in C:

 String Length

 Function: strlen()
 Definition: Returns the length of a string (excluding the null
terminator).
 Example
#include <string.h>
int len = strlen(str1); // len is 5

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 22


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

 String Copy

 Function: strcpy()
 Definition: Copies one string into another.
 Example
#include <string.h>
char dest[10];
strcpy(dest, str1); // dest contains "Hello"

 String Concatenation

 Function: strcat()
 Definition: Appends one string to the end of another.
 Example
#include <string.h>
char str3[20] = "Hello";
strcat(str3, " World"); // str3 contains "Hello World"

 String Tokenization

 Function: strtok()
 Definition: Splits a string into tokens based on a delimiter.
 Example
#include <stdio.h>
#include <string.h>
char str[] = "Hello,World";
char *token = strtok(str, ",");
while (token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, ",");
}
// Output:
// Hello
// World

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 23


SUBJECT CODE: 23U1CSC1 TITLE: C AND DATA STRUCTURE

 String Comparison

 Function: strcmp()
 Definition: Compares two strings lexicographically.
 Example
#include <string.h>
int result = strcmp(str1, str2); // result is 0 if str1 and str2 are equal

These operations provide basic functionality for manipulating strings in


C, but they require careful handling of memory and null terminators to avoid
common pitfalls like buffer overflows and segmentation faults.

CREATED BY MAHESWARAN, B.SC., (CS) PAGE 24

You might also like