Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Module 2

This document covers essential concepts in C programming, focusing on arrays, including single and two-dimensional arrays, their declaration, initialization, and manipulation. It also discusses strings as character arrays, their input/output methods, and string handling functions. Additionally, it includes exercises and examples related to array processing and sorting algorithms like bubble sort.

Uploaded by

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

Module 2

This document covers essential concepts in C programming, focusing on arrays, including single and two-dimensional arrays, their declaration, initialization, and manipulation. It also discusses strings as character arrays, their input/output methods, and string handling functions. Additionally, it includes exercises and examples related to array processing and sorting algorithms like bubble sort.

Uploaded by

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

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PROGRAMMING IN C

Prof. Sarju S
11 February 2025
Module 2

Page 2
Module 2

► Arrays - Single dimensional arrays, Defining an array, Array initialization, Accessing


array elements; Enumerated data type; Type Definition; Two- dimensional arrays –
Defining a two dimensional array; Programs for matrix processing; Programs for
sequential search; Bubble sort.

► Strings - Declaring a string variable, Reading and displaying strings, String related
library functions – Programs for string matching.

Page 3 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Arrays

Page 4
Arrays

► An array is a collection of elements of the same type that are


referenced by a common name.
► Compared to the basic data type (int, float & char) it is an aggregate
or derived data type.
► All the elements of an array occupy a set of contiguous memory
locations.
► Why need to use array type?
► Consider the following issue:
► "We have a list of 1000 students' marks of an integer type. If using the basic data
type (int), we will declare something like the following…"
► int studMark0, studMark1, studMark2, ..., studMark999;

Page 5 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Arrays

► Can you imagine how long we have to write the declaration part by using
normal variable declaration?
int main(void)
{
int studMark1, studMark2, studMark3, studMark4, …, …, studMark998,
stuMark999, studMark1000;


return 0;
}

Page 6 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Arrays
► By using an array, we just declare like this,
► int studMark[1000];
► This will reserve 1000 contiguous memory locations for storing the students’ marks.
► Graphically, this can be depicted as in the following figure.
Index/subscript
starting from 0
0 43 studMar[0] Instead of 1
1 50 studMar[1]
Stored data of type integer
2 62 studMar[2]
3 33 studMar[3]
. . …..
. . …..
Arrays name
. . ….
Memory Storage 999 110 studMar[999]

Page 7 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Arrays

► This absolutely has simplified our declaration of the variables.


► We can use index or subscript to identify each element or location in
the memory.
► Hence, if we have an index of jIndex, studMark[jIndex] would refer
to the jIndexth element in the array of studMark.
► For example, studMark[0] will refer to the first element of the array.
► Thus, by changing the value of jIndex, we could refer to any element in
the array.
► So, array has simplified our declaration and of course, manipulation of
the data.

Page 8 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Arrays - One Dimensional Array: Declaration

► Dimension refers to the array's size, which is how big the array is.
► A single or one-dimensional array declaration has the following form,
datatype arrayName[arraySize];

► Here, datatype define the base type of the array, which is the type of each element
in the array.
► arrayName is any valid C / C++ identifier name that obeys the same rule for the
identifier naming.
► arraySize defines how many elements the array will hold.

Page 9 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Arrays

► For example, to declare an array of 30 characters,


that construct a people name, we could declare,
0 43 cName[0]
char cName[30]; 1 50 cName[1]
► Which can be depicted as follows, 2 62 cName[2]
► In this statement, the array character can store up to 30 3 33 cName[3]
characters with the first character occupying location . . …..
cName[0] and the last character occupying cName[29].
. . …..
► Note that the index runs from 0 to 29. In C, an index
. . ….
always starts from 0 and ends with array's (size-1).
29 110 cName[29]
► So, take note the difference between the array size and
subscript/index terms.

Page 10 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Arrays

► Examples of the one-dimensional array declarations,


int xNum[20], yNum[50];
float fPrice[10], fYield;
char chLetter[70];
► The first example declares two arrays named xNum and yNum of type int. Array xNum
can store up to 20 integer numbers while yNum can store up to 50 numbers.
► The second line declares the array fPrice of type float. It can store up to 10
floating-point values.
► fYield is basic variable which shows array type can be declared together with basic
type provided the type is similar.
► The third line declares the array chLetter of type char. It can store a string up to 69
characters.
► Why 69 instead of 70? Remember, a string has a null terminating character (\0) at the end,
so we must reserve for it.

Page 11 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Arrays - Array Initialization

► An array may be initialized at the time of declaration.


► Giving initial values to an array.
► Initialization of an array may take the following form,
► datatype arrayName[size] = {a_list_of_values};

Page 12 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Arrays - Array Initialization

► For example:
int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};
► The first line declares an integer array idNum and it immediately assigns the values 1,
2, 3, ..., 7 to idNum[0], idNum[1], idNum[2],..., idNum[6] respectively.
► The second line assigns the values 5.6 to fFloatNum[0], 5.7 to fFloatNum[1], and
so on.
► Similarly, the third line assigns the characters 'a' to chVowel[0], 'e' to chVowel[1],
and so on.
► Note again, for characters we must use the single apostrophe/quote (') to enclose them.
► Also, the last character in chVowel is NULL character ('\0').

Page 13 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Arrays - Array Initialization

► int arr[5] = {1, 2, 3};


► Here the arr[4] and arr[5] will still remain garbage values, so you need to be careful!
► If you’re using an initializer list with all elements, you don’t need to
mention the size of the array.
// Valid. Size of the array is taken as the number of elements
// in the initializer list (5)
int arr[] = {1, 2, 3, 4, 5};

// Also valid. But here, size of a is 3


int a[] = {1, 2, 3};
► If you want to initialize all the elements to 0, there is a shortcut for this
(Only for 0). We can simply mention the index as 0.
int arr[5] = {0};

Page 14 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Arrays - Array Initialization

► Initialization of an array of type char for holding strings may take the following form,
► char arrayName[size] = "string_lateral_constant";
► For example, the array chVowel in the previous example could have been written more
compactly as follows,
► char chVowel[6] = "aeiou";

► When the value assigned to a character array is a string (which must be enclosed in
double quotes), the compiler automatically supplies the NULL character but we still
have to reserve one extra place for the NULL.

► For unsized array (variable sized), we can declare as follow,


► char chName[ ] = "Mr. Idicula";
► C compiler automatically creates an array which is big enough to hold all the initializer.

Page 15 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Exercises

► Write a C program to read n numbers into an array and find the sum of
all elements.
► Write a C program to find the largest and smallest elements in an array.
► Write a C program to count the number of even and odd numbers in an
array.
► Write a C program to search for a given number in an array and display
its position.

Page 16 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Bubble Sort

First Pass

Page 17 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Bubble Sort

Second Pass

Page 18 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Bubble Sort

Third Pass

Page 19 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Bubble Sort

Third Pass

Page 20 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Bubble Sort

Fourth Pass

Page 21 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Bubble Sort

Page 22 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Bubble sort program

Page 23 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Bubble sort program

Page 24 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Two-dimensional arrays in C

► An array of arrays is known as 2D array.


► The two-dimensional (2D) array in C programming is also known as
matrix.
► A matrix can be represented as a table of rows and columns.

Page 25 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Two-dimensional arrays in C

► A simple example to declare two dimensional array is given below.


► int twoDimArray[3][4];

Page 26 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Initializing two-dimensional a​rrays

► A two-dimensional array can be initialized during its declaration.


int my_array[5][3] = {
{1, 2, 3}, //row 1
{4, 5, 6}, //row 2
{7, 8, 9}, //row 3
{10, 11, 12}, //row 4
{13, 14, 15} //row 5
};
► The inside curly braces are optional, two-dimensional arrays can be
declared with or without them.

int my_array[5][3] = {1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15};

Page 27 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Accessing elements in two-dimensional arrays
#include <stdio.h>

int main()
{
// array declaration and initialization
int my_array[5][3] = {
{1, 2, 3}, //row 1
{4, 5, 6}, //row 2
{7, 8, 9}, //row 3
{10, 11, 12}, //row 4
{13, 14, 15} //row 5
};

// accessing and printing the elements


for ( int i = 0; i < 5; i++ ) {
// variable i traverses the rows
for ( int j = 0; j < 3; j++ ) {
// variable j traverses the columns
printf("my_array [%d][%d] = %d\n", i,j, my_array[i][j] );
}
}
return 0;
}

Page 28 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Strings

Page 4
String and Character Array

► String is a sequence of characters that are treated as a single data item


and terminated by a null character '\0'.

► Remember that the C language does not support strings as a data type.

► A string is actually a one-dimensional array of characters in C language.


These are often used to create meaningful and readable programs.

Page 5 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
String and Character Array

► For example: The string "home" contains 5 characters including the '\0'
character which is automatically added by the compiler at the end of the
string.

Page 6 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Declaring and Initializing a string variables

// valid
char name[13] = "StudyTonight";
char name[10] = {'c','o','d','e','\0'};

// Illegal
char ch[3] = "hello";
str = "hello";

Page 7 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
String Input and Output

► %s format specifier to read a string input


from the terminal.
char str[20];
► But scanf() function, terminates its input on printf("Enter a string");
the first white space it encounters. scanf("%[^\n]", &str);
printf("%s", str);
► edit set conversion code %[..] that can be
used to read a line containing a variety of
char text[20];
characters, including white spaces.
gets(text);
printf("%s", text);
► The gets() function can also be used to read
character string with white spaces

Page 8 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
String Input and Output

► puts()
► The function puts() is used to print the string on the output stream with the
additional new line character ‘\n’.
► It moves the cursor to the next line.
► Implementation of puts() is easier than printf().
► Here is the syntax of puts() in C language,
► puts(“string”);

Page 9 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
String Handling Functions

► C language supports a large number of string handling functions that


can be used to carry out many of the string manipulations.

► These functions are packaged in the string.h library.

► Hence, you must include string.h header file in your programs to use
these functions.

Page 10 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
String Handling Functions

► The following are the most commonly used string handling functions.

Method Description
strcat() It is used to concatenate(combine) two strings
strlen() It is used to show the length of a string
strrev() It is used to show the reverse of a string
strcpy() Copies one string into another
strcmp() It is used to compare two string

Page 11 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
strlen() – String Length

► Finds the length of a string (number of characters before the null


terminator \0).
► Syntax
size_t strlen(const char *str);

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

int main() {
char text[] = "Hello, C!";
printf("Length of string: %d\n", strlen(text));
return 0;
} Length of string: 9

Page 12 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
What is strcpy()?

► built-in function in C that copies a string from one location (source) to


another (destination).
► Syntax
char *strcpy(char *destination, const char *source);

► Parameters:
► destination – A pointer to the destination array where the source string will be
copied.
► source – A pointer to the source string that needs to be copied
► It copies the characters of the source string (including the null terminator \0) into the
destination string.
► The destination array should have enough space to store the copied string; otherwise, it
may lead to buffer overflow.
► Return Value: Returns a pointer to the destination string (destination).

Page 13 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
strcpy() - Example
#include<stdio.h>
#include<string.h>

int main() {
char source[] = "Hello, C!";
char destination[20]; // Make sure destination has enough space

strcpy(destination, source);

printf("Source String: %s\n", source);


printf("Copied String: %s\n", destination);

return 0;
} Source String: Hello, C!
Copied String: Hello, C!

Page 14 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
strncpy() – Safe String Copy

► Copies n characters from source to destination, preventing buffer


overflow.

char *strncpy(char *destination, const char *source, size_t n);

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

int main() {
char source[] = "Hello, C!";
char destination[6];
strncpy(destination, source, 5);
destination[5] = '\0'; // Ensure null termination
printf("Copied String: %s\n", destination);
return 0; Copied String: Hello
}
Page 15 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
strcat() – String Concatenation in C

► The strcat() function in C is used to concatenate (append) one string to


the end of another.
► It modifies the destination string by adding the source string at its end.

char *strcat(char *destination, const char *source);

► destination: The string to which source is appended. This should have enough
space to accommodate the additional characters.
► source: The string to be appended.
► Returns: A pointer to destination after concatenation.

Page 16 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Working of strcat()

► The function finds the null terminator (\0) of the destination string.
► It starts copying characters from source to destination from the null
position. It copies all characters, including the \0 terminator of source.
#include <stdio.h>
#include <string.h>

int main() {
char str1[30] = "Hello, ";
char str2[] = "World!";

strcat(str1, str2); // Appends str2 to str1

printf("Concatenated String: %s\n", str1);


return 0;
} Concatenated String: Hello, World!

Page 17 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Memory Considerations

► The destination string must have enough space to hold both the original
content and the appended source.
► If there isn't enough space, strcat() causes buffer overflow, leading to
unpredictable behavior or program crashes.

Page 18 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Safer Alternative: strncat()

► To prevent buffer overflow, use strncat(), which allows specifying the


maximum number of characters to append.
char *strncat(char *destination, const char *source, size_t n);

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

int main() {
char str1[12] = "Hello";
char str2[] = " World!";

strncat(str1, str2, 6); // Appends only first 6 characters


printf("Concatenated String: %s\n", str1);

return 0;
} Concatenated String: Hello Worl

Page 19 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
strcmp() and strncmp() in C – String Comparison Functions

► The strcmp() function compares two strings character by character and


determines their lexicographical (dictionary order) difference.

int strcmp(const char *str1, const char *str2);

► str1: First string.


► str2: Second string.
► Returns:
► 0 → if str1 and str2 are equal.
► < 0 → if str1 is less than str2 (comes before in lexicographical order).
► > 0 → if str1 is greater than str2 (comes after in lexicographical order).

Page 20 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
strcmp() -Example
#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Apple";
char str2[] = "Banana";

int result = strcmp(str1, str2);

if (result == 0)
printf("Both strings are equal.\n");
else if (result < 0)
printf("\"%s\" comes before \"%s\" in dictionary order.\n", str1, str2);
else
printf("\"%s\" comes after \"%s\" in dictionary order.\n", str1, str2);

return 0;
} "Apple" comes before "Banana" in dictionary order.

Page 21 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
strncmp() – Comparing Limited Characters

► The strncmp() function compares only the first n characters of two


strings.
int strncmp(const char *str1, const char *str2, size_t n);

► str1: First string.


► str2: Second string.
► n: Number of characters to compare.
► Returns: Same as strcmp()

Page 22 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
strncmp() – Comparing Limited Characters

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

int main() {
char str1[] = "HelloWorld";
char str2[] = "HelloThere";

int result = strncmp(str1, str2, 5); // Compare first 5 characters

if (result == 0)
printf("First 5 characters are equal.\n");
else
printf("First 5 characters are different.\n");

return 0;
}
First 5 characters are equal.

Page 23 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
When to Use Which?

► Use strcmp() when you want to compare two full strings.


► Use strncmp() when you only need to check a specific portion of the
string (e.g., checking prefixes, validating partial inputs).

Page 24 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
typedef

Page 4
What is typedef in C?

► typedef (type definition) is a keyword in C that allows the creation of


new names (aliases) for existing data types.
► It improves code readability, portability, and maintainability.
► Syntax

typedef existing_type new_type;

► existing_type: The original data type.


► new_type: The new alias name for the existing type.

Page 5 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Why Use typedef?

► Improves Readability: Complex data types Instead of writing:


become easier to understand. unsigned int myVar;
► Reduces Typing Effort: Shortens long or
repetitive type names.
We can define an alias for unsigned int using
► Increases Maintainability: Changes to a typedef:
type only need to be made in one place.
#include <stdio.h>

typedef unsigned int UINT; // Defining an alias

int main() {
UINT myVar = 100;
printf("Value: %u\n", myVar);
return 0;
}

Page 6 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Using typedef with Arrays

typedef int Marks[5]; // Alias for an array of 5 integers

int main() {
Marks student1 = {90, 85, 88, 92, 80};
return 0;
}

Page 7 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Enumerated Data Types in C (enum)

Page 8
What is an Enumerated Data Type?

► enum is a user-defined data type that consists of a set of named integer


constants.
► It helps improve code readability and maintainability by assigning
meaningful names to integral values.

enum enum_name { constant1, constant2, constant3, ... };


► enum is the keyword used to define an enumeration.
► enum_name is the name of the enumeration type.
► constant1, constant2, constant3, ... are enumeration constants that represent
integer values (starting from 0 by default and increasing by 1).

Page 9 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Example 1: Basic Enum Usage

#include <stdio.h>

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main() {
enum Days today;
today = Wednesday;

printf("The numerical value of Wednesday is: %d\n", today);


return 0;
}

Output: The numerical value of Wednesday is: 3

How Enums Work Internally


By default, the first enumerator gets the value 0, the next gets 1, and so on. You can manually assign values

Page 10 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Example 2: Assigning Custom Values

#include <stdio.h>

enum StatusCode { SUCCESS = 1, FAILURE = -1, PENDING = 0 };

int main() {
printf("SUCCESS = %d\n", SUCCESS);
printf("FAILURE = %d\n", FAILURE);
printf("PENDING = %d\n", PENDING);
return 0;
}
Output:
SUCCESS = 1
FAILURE = -1
PENDING = 0

Page 11 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Using Enum in a Switch Statement
#include <stdio.h>

enum TrafficLight { RED, YELLOW, GREEN };

int main() {
enum TrafficLight signal = YELLOW;

switch(signal) {
case RED:
printf("Stop!\n");
break;
case YELLOW:
printf("Get Ready!\n");
break;
case GREEN:
printf("Go!\n");
break;
default:
printf("Invalid Signal\n");
}

return 0;
}

Page 12 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Enum with Typedef
#include <stdio.h>

typedef enum { OFF, ON } Switch;

int main() {
Switch light = ON;
if (light == ON) {
printf("The light is ON.\n");
} else {
printf("The light is OFF.\n");
}
return 0;
}

Page 13 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Thank You

Prof. Sarju S
Department of Computer Science and Engineering
St. Joseph’s College of Engineering and Technology, Palai (Autonomous)
sarju.s@sjcetpalai.ac.in

Page 14 Disclaimer - This document contains images/texts from various internet sources. Copyright belongs to the respective content creators.
Document is compiled exclusively for study purpose and shall not be used for commercial purpose.

You might also like