Practical C Programming - B. M. Harwani - E-Book

Practical C Programming E-Book

B.M. Harwani

0,0
32,36 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

A comprehensive guide with practical instructions for learning data structures, low-level programming, high-performance computing, networking and IoT to help you understand the latest standards in C programming such as C11 and C18




Key Features



  • Tackle various challenges in C programming by making the most of its latest features


  • Understand the workings of arrays, strings, functions, pointers, advanced data structures, and algorithms


  • Become well-versed with process synchronization during multitasking and server-client process communication



Book Description



Used in everything from microcontrollers to operating systems, C is a popular programming language among developers because of its flexibility and versatility. This book helps you get hands-on with various tasks, covering the fundamental as well as complex C programming concepts that are essential for making real-life applications.






You'll start with recipes for arrays, strings, user-defined functions, and pre-processing directives. Once you're familiar with the basic features, you'll gradually move on to learning pointers, file handling, concurrency, networking, and inter-process communication (IPC). The book then illustrates how to carry out searching and arrange data using different sorting techniques, before demonstrating the implementation of data structures such as stacks and queues. Later, you'll learn interesting programming features such as using graphics for drawing and animation, and the application of general-purpose utilities. Finally, the book will take you through advanced concepts such as low-level programming, embedded software, IoT, and security in coding, as well as techniques for improving code performance.






By the end of this book, you'll have a clear understanding of C programming, and have the skills you need to develop robust apps.




What you will learn



  • Discover how to use arrays, functions, and strings to make large applications


  • Perform preprocessing and conditional compilation for efficient programming


  • Understand how to use pointers and memory optimally


  • Use general-purpose utilities and improve code performance


  • Implement multitasking using threads and process synchronization


  • Use low-level programming and the inline assembly language


  • Understand how to use graphics for animation


  • Get to grips with applying security while developing C programs



Who this book is for



This intermediate-level book is for developers who want to become better C programmers by learning its modern features and programming practices. Familiarity with C programming is assumed to get the most out of this book.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 653

Veröffentlichungsjahr: 2020

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Practical C Programming

 

 

 

 

 

 

 

 

 

 

 

 

 

Solutions for modern C developers to create efficient and well-structured programs

 

 

 

 

 

 

 

 

 

 

 

 

 

B. M. Harwani

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Practical C Programming

Copyright © 2020 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

Commissioning Editor:Richa TripathiAcquisition Editor:Alok DhuriContent Development Editor:Ruvika RaoSenior Editor: Afshaan KhanTechnical Editor:Pradeep SahuCopy Editor: Safis EditingProject Coordinator:Francy PuthiryProofreader: Safis EditingIndexer:Tejal Daruwale SoniProduction Designer:Arvindkumar Gupta

First published: February 2020

Production reference: 1140220

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-83864-110-8

www.packt.com

  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
To Guido van Rossum, the creator of the Python language. Python is not only very commonly used for making real-time applications, web applications, and smartphone applications, but is also used in AI, data learning, Internet of things (IoT), and much more.To my mom, Mrs Nita Harwani. She is next to God for me. Whatever I am today is because of the moral values she taught me.
                                                                                                                                              – Bintu Harwani 
 

Packt.com

Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Fully searchable for easy access to vital information

Copy and paste, print, and bookmark content

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. 

Contributors

About the author

B. M. Harwani is the founder of Microchip Computer Education, based in Ajmer, India, which provides computer literacy in programming and web development to learners of all ages. He further helps the community by sharing the knowledge and expertise he's gained over 20 years of teaching by writing books. His recent publications include jQuery Recipes, published by Apress, Introduction to Python Programming and Developing GUI Applications with PyQT, published by Cengage Learning, The Android Tablet Developer's Cookbook, published by Addison-Wesley Professional, UNIX and Shell Programming, published by Oxford University Press, and Qt5 Python GUI Programming Cookbook, published by Packt.

 

 

About the reviewer

Nibedit Dey is a software engineer turned serial entrepreneur with over 9 years of experience in building complex software-based products using C and C++. He has been involved in developing new medical devices, oscilloscopes, advanced showering systems, automotive dashboards, and infotainment systems. He is passionate about cutting-edge technologies. Before starting his entrepreneurial journey, he worked for L&T and Tektronix in different R&D roles. He has also reviewed several books on C and C++ programming for Packt. 

I would like to thank the online programming communities, bloggers, and my peers from earlier organizations, from whom I have learned a lot over the years.

 

 

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Practical C Programming

Dedication

About Packt

Why subscribe?

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Sections

How to do it…

How it works…

There's more…

See also

Get in touch

Reviews

Working with Arrays

Inserting an element in an array

How to do it…

How it works...

There's more...

Multiplying two matrices

How to do it…

How it works...

There’s more…

Finding the common elements in two arrays

How to do it…

How it works...

Finding the difference between two sets or arrays

How to do it…

How it works...

Finding the unique elements in an array

How to do it… 

How it works...

Finding whether a matrix is sparse

How to do it…

How it works...

There's more...

Merging two sorted arrays into a single array

How to do it…

How it works...

Managing Strings

Determining whether the string is a palindrome 

How to do it…

How it works...

Finding the occurrence of the first repetitive character in a string

How to do it…

How it works...

Displaying the count of each character in a string

How to do it…

How it works...

Counting vowels and consonants in a sentence

How to do it…

How it works...

Converting the vowels in a sentence to uppercase

How to do it…

How it works...

Exploring Functions

What is a stack?

Finding whether a number is an Armstrong number

How to do it…

How it works...

Returning maximum and minimum values in an array

How to do it…

How it works...

Finding the greatest common divisor using recursion

How to do it…

How it works...

Converting a binary number into a hexadecimal number

How to do it…

How it works...

Finding whether a number is a palindrome 

How to do it…

How it works...

Preprocessing and Compilation

Performing conditional compilation with directives

How to do it...

How it works...

Applying assertions for validation

How to do it...

How it works...

Using assertions to ensure a pointer is not pointing to NULL

How to do it…

How it works...

Catching errors early with compile-time assertions

How to do it...

How it works...

Applying stringize and token-pasting operators

How to do it...

How it works...

Deep Dive into Pointers

What is a pointer?

Reversing a string using pointers

How to do it…

How it works...

Finding the largest value in an array using pointers

How to do it…

How it works...

Sorting a singly linked list

How to do it…

How it works...

Creating a singly linked list

Sorting the singly linked list

The first iteration

The second iteration

The third and fourth iterations

Finding the transpose of a matrix using pointers

How to do it…

How it works...

Accessing a structure using a pointer

How to do it…

How it works...

File Handling

Functions used in file handling

Functions commonly used in sequential file handling

fopen()

fclose()

fgets()

fputs()

Functions commonly used in random files

fseek()

ftell()

rewind()

Reading a text file and converting all characters after the period into uppercase

How to do it…

How it works...

Displaying the contents of a random file in reverse order

How to do it…

How it works...

Counting the number of vowels in a file

How to do it…

How it works...

Replacing a word in a file with another word

How to do it…

How it works...

Encrypting a file

How to do it…

How it works...

See also

Implementing Concurrency

What are processes and threads?

Mutual exclusion

Performing a task with a single thread

How to do it…

How it works...

Performing multiple tasks with multiple threads

How to do it…

How it works...

Using mutex to share data between two threads

How to do it…

How it works...

Understanding how a deadlock is created

How to do it…

How it works...

Avoiding a deadlock

How to do it…

How it works...

Networking and Inter-Process Communication

Communicating between processes using pipes

Creating and to connecting processes

pipe()

mkfifo()

write()

read()

perror()

fork()

One process, both writing and reading from the pipe

How to do it…

How it works...

One process writing into the pipe and another process reading from the pipe

How to do it…

How it works...

Communicating between processes using FIFO

Writing data into a FIFO

How to do it…

How it works...

Reading data from a FIFO

How to do it…

How it works...

Communicating between the client and server using socket programming

Client-server model

struct sockaddr_in structure

socket()

memset()

htons()

bind()

listen()

accept()

send()

connect()

recv()

Sending data to the client

How to do it…

How it works...

Reading data that's been sent from the server

How to do it…

How it works...

Communicating between processes using a UDP socket

Using a UDP socket for server-client communication

bzero()

INADDR_ANY

sendto()

recvfrom()

Await a message from the client and sending a reply using a UDP socket

How to do it…

How it works...

Sending a message to the server and receiving the reply from the server using the UDP socket

How to do it…

How it works...

Running Cygserver

Passing a message from one process to another using the message queue

Functions used in IPC using shared memory and message queues

ftok()

shmget()

shmat()

shmdt()

shmctl()

msgget()

msgrcv()

msgsnd()

Writing a message into the message queue

How to do it…

How it works...

Reading a message from the message queue

How to do it…

How it works...

Communicating between processes using shared memory

Writing a message into shared memory

How to do it…

How it works...

Reading a message from shared memory

How to do it…

How it works...

Sorting and Searching

Searching for an item using binary search 

How to do it...

How it works...

Arranging numbers in ascending order using bubble sort

How to do it…

How it works...

Arranging numbers in ascending order using insertion sort

How to do it...

How it works...

Arranging numbers in ascending order using quick sort

How to do it...

Quick sort

FindingPivot

How it works...

Arranging numbers in descending order using heap sort

How to do it...

Creating a max-heap

Deleting the max-heap

How it works...

See also

Working with Graphs

Types of graphs

Directed graphs

Undirected graphs

Creating an adjacency matrix representation of a directed graph

How to do it...

How it works...

Creating an adjacency matrix representation of an undirected graph

How to do it...

How it works...

Creating an adjacency list representation of a directed graph

How to do it...

How it works...

Carrying out the breadth-first traversal of a graph

How to do it...

How it works...

Carrying out the depth-first traversal of a graph

How to do it...

How it works...

Creating minimum spanning trees using Prim's algorithm

How to do it...

How it works...

Displaying the adjacency linked list

Creating the minimum spanning tree

Creating minimum spanning trees using Kruskal's algorithm

How to do it...

How it works...

Advanced Data Structures and Algorithms

Stack

Doubly linked lists (two-way linked lists)

Circular linked lists

Binary tree

Binary search trees

Traversing trees

Implementing a stack using a singly linked list

How to do it...

How it works...

Implementing a doubly or two-way linked list

How to do it...

How it works...

Implementing a circular linked list

How to do it...

How it works...

Creating a binary search tree and performing an inorder traversal on it recursively

How to do it... – binary tree

How to do it... – inorder traversal of the tree

How it works... – binary tree

How it works... – inorder traversal of the tree

Performing postorder traversal of a binary tree non-recursively

Getting started

How to do it...

How it works...

See also

Creativity with Graphics

List of OpenGL functions

Drawing four graphical shapes

How to do it...

How it works...

Drawing a circle

How to do it...

How it works...

Drawing a line between two mouse clicks

How to do it...

How it works...

Making a bar graph of the supplied values

How to do it...

How it works...

Making an animated bouncing ball

How to do it...

How it works...

Using MySQL Database

Functions in MySQL

mysql_init()

mysql_real_connect()

mysql_query()

mysql_use_result()

mysql_fetch_row()

mysql_num_fields()

mysql_free_result()

mysql_close()

Creating a MySQL database and tables

Create database

Create table

Displaying all the built-in tables in a default mysql database

How to do it...

How it works...

Storing information in MySQL database

How to do it…

How it works...

Searching for the desired information in the database

How to do it…

How it works...

Updating information in the database

How to do it…

How it works...

Deleting data from the database using C

How to do it…

How it works...

General-Purpose Utilities

Dynamic memory allocation

malloc()

calloc()

realloc()

free()

Registering a function that is called when a program exits

How to do it…

How it works...

There's more...

Measuring the clock ticks and CPU seconds required in the execution of a function

How to do it...

How it works...

Performing dynamic memory allocation

How to do it...

How it works...

Handling signals

Signals

signal()

How to do it...

How it works...

Improving the Performance of Your Code

Using the register keyword in C code for better efficiency

How to do it...

How it works...

Taking input faster in C

How to do it…

How it works...

Applying loop unrolling for faster results

How to do it…

How it works...

Low-Level Programming

Introduction to bitwise operators

& (binary AND)

| (binary OR)

^ (binary XOR)

~ (binary complement)

<< (binary shift left)

>> (binary shift right)

Converting a binary number into a decimal using a bitwise operator

How to do it…

How it works...

Converting a decimal into binary using a bitwise operator

How to do it…

How it works...

Converting a decimal number into binary using bit masking 

How to do it…

How it works...

Introduction to assembly coding

Multiplying two numbers using the inline assembly language in C

How to do it…

How it works...

Dividing two numbers using assembly code in C

How to do it…

How it works...

Embedded Software and IoT

Technical requirements

Introduction to embedded systems

Introduction to IoT

Introduction to Arduino

Toggling the port of a microcontroller in Embedded C (blinking LED)

How to do it…

How it works...

Incrementing the value of a port in Embedded C

How to do it…

How it works...

Toggle voltage in output pin using Arduino (blinking LED)

How to do it…

How it works...

Taking input from the serial port using Arduino

How to do it…

How it works...

Sensing the temperature using Arduino with the LM35 sensor

Getting ready...

How to do it...

How it works...

Applying Security in Coding

Buffer overflow

gets()

fgets()

fpurge(stdin)

sprintf()

snprintf()

strcpy()

strncpy( )

Understanding how a buffer overflow occurs

How to do it...

How it works...

Learning how to avoid a buffer overflow 

How to do it...

How it works...

Understanding how a vulnerability occurs while copying strings

How to do it...

How it works...

Learning how to write secure code while copying strings

How to do it...

How it works...

Understanding the errors that occur while formatting strings

How to do it...

How it works...

Learning how to avoid errors while formatting strings

How to do it...

How it works...

Understanding how vulnerabilities occur while accessing files in C

How to do it...

How it works...

Learning how to avoid vulnerabilities while writing a file in C

How to do it...

How it works...

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

This book is on the C programming language and explores all the important elements of C, such as strings, arrays (including one-dimensional and two-dimensional arrays), functions, pointers, file handling, threads, inter-process communication, database handling, advanced data structures, graphs, and graphics. As this book takes the cookbook approach, the reader will find independent solutions to different problems that they usually come across while making applications. By the end of the book, the reader will have sufficient knowledge to use high- as well as low-level features of the C language and will be able to apply this knowledge to making real-time applications.

Who this book is for

This book is meant for intermediate to advanced programmers and developers who want to make complex and real-time applications in C programming. This book will be of great use for trainers, teachers, and software developers who get stuck while making applications with arrays, pointers, functions, structures, files, databases, inter-process communication, advanced data structures, graphs, and graphics, and wish to see a walkthrough example to find the way out of a given problem.

What this book covers

Chapter 1, Working with Arrays, covers some complex but essential operations with arrays. You will learn how to insert an element into an array, multiply two matrices, find the common elements in two arrays, and also how to find the difference between two sets or arrays. Also, you will learn how to find the unique elements in an array and will encounter a technique to help you find out whether a given matrix is a sparse matrix or not. Lastly, we'll look at the procedure to merge two sorted arrays into one array.

Chapter 2, Managing Strings, teaches you how to manipulate strings to the extent of characters. You will learn how to find out whether a given string is a palindrome or not, how to find a given occurrence of the first repetitive character in a string, and how to count each character in a string. You will also learn how to count vowels and consonants in a string and the procedure for converting the vowels in a sentence into uppercase.

Chapter 3, Exploring Functions, explores the major role played by functions in breaking down a big application into small, independent, and manageable modules. In this chapter, you will learn to make a function that finds whether the supplied argument is an Armstrong number or not. You will also learn how a function returns an array and will make a function that finds the greatest common divisor (gcd) of two numbers using recursion. You will also learn to make functions that convert a binary number into hexadecimal. Lastly, you will learn to make a function that determines whether the supplied number is a palindrome or not.

Chapter 4, Preprocessing and Compilation, covers a range of topics, including performing preprocessing and compilation, performing conditional compilation with directives, applying assertions for validation, catching errors early with compile-time assertions, applying stringize, and how to use token-pasting operators.

Chapter 5, Deep Dive into Pointers, shows you how to use pointers to access content from specific memory locations. You will learn how to reverse a string using pointers, how to find the largest value in an array using pointers, and the procedure to sort a singly linked list. Besides this, the chapter explains how to find the transpose of a matrix using pointers and how to access a structure using pointers.

Chapter 6, File Handling, looks at how, when storing data for future use, file handling is very important. In this chapter, you will learn to learn to read a text file and convert all the characters after a period into uppercase. Also, you will learn how to display the content of a random file in reverse order and how to count the number of vowels in a text file. The chapter will also show you how to replace a word in a given text file with another word, and how to keep your file secure from unauthorized access. You will also learn how a file is encrypted.

Chapter 7, Implementing Concurrency, covers how concurrency is implemented in order to increase the efficiency of CPU operations. In this chapter, you will learn to do a task using a single thread. You will also learn to do multiple tasks with multiple threads and examine the technique of sharing data between two threads using mutex. Besides this, you will become familiar with situations where deadlock can be created and how such deadlock situations can be avoided.

Chapter 8, Networking and Inter-Process Communication, focuses on how to establish communication among processes. You will learn how to communicate between processes using pipes, how to establish communication among processes using FIFO, and how communication is established between the client and server using socket programming. You will also learn to do inter-process communication using the UDP socket, how a message is passed from one process to another using the message queue, and how the two processes communicate using shared memory.

Chapter 9, Sorting and Searching, covers searching using binary search, sorting numbers using bubble sort, and the use of insertion sort, quick sort, heap sort, selection sort, merge sort, shell sort, and radix sort.

Chapter 10, Working with Graphs, examines implementing stacks, two-way linked lists, circular linked lists, queues, circular queues, and the dequeue function. You'll also look at performing inorder traversal of a binary search tree recursively, followed by performing postorder traversal of a binary tree non-recursively.

Chapter 11, Advanced Data Structures and Algorithms, looks at representing graphs using an adjacency matrix and adjacency list, how to do breadth-first and depth-first traversal of graphs, and creating minimum spanning trees using Prim's and Kruskal's algorithms.

Chapter 12, Creativity with Graphics, covers making different graphical shapes, drawing a line between two mouse clicks, making a bar graph, and animating a bouncing ball.

Chapter 13, Using MySQL Database, considers how no real-time application is possible without storing information in a database. The information in a database needs to be managed as and when required. In this chapter, you will learn to display all the built-in tables in a default MySQL database. You will see how to store information in a MySQL database and search for the desired information in the database tables. Not only this; you will also learn to update information in the database tables and the procedure of deleting data from the database when no longer required anymore.

Chapter 14, General-Purpose Utilities, teaches you how to register a function that is called when a program exits, along with examinations of measuring clock ticks in the executing of a function, dynamic memory allocation, and handling signals.

Chapter 15, Improving the Performance of Your Code, focuses on using the register keyword, taking input faster, and applying loop unrolling for faster results.

Chapter 16, Low-Level Programming, looks at converting a binary number to decimal, multiplying and dividing two numbers using inline assembly language, and converting decimal values into binary using the bitwise operator and by masking certain bits of a register.

Chapter 17, Embedded Software and IoT, shows you how to toggle a port of a microcontroller in Embedded C, increment the value of a port, toggle voltage in Arduino, take input from the serial port, and how to detect and record temperatures using Arduino.

Chapter 18, Applying Security in Coding, demonstrates how to avoid buffer overflow, along with how to write secure code, avoid errors while string formatting, and avoid vulnerabilities while accessing files in C.

To get the most out of this book

You need to have some preliminary knowledge of C programming. You need to have basic knowledge of arrays, strings, functions, file handling, threads, and inter-process communication. Also, to handle databases, you will need to have basic knowledge of basic SQL commands.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

Support

tab.

Click on

Code Downloads

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Practical-C-Programming. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781838641108_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, path names, dummy URLs, user input, and Twitter handles. Here is an example: "In the figure, 1000 represents the memory address of the i variable."

A block of code is set as follows:

for(i=0;i<2;i++) { for(j=0;j<4;j++) { matR[i][j]=0; for(k=0;k<3;k++) { matR[i][j]=matR[i][j]+matA[i][k]*matB[k][j]; } } }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

printf("How many elements are there? ");

scanf("%d", &n);

Any command-line input or output is written as follows:

D:\CBook>reversestring

Enter a string: manish

Reverse string is hsinam

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Simply click the Next button to continue."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Sections

In this book, you will find several headings that appear frequently (How to do it and How it works).

To receive clear instructions on how to complete a recipe, use these sections as follows:

 

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section consists of a detailed explanation of the steps followed in the previous section.

There's more…

This section, when present, consists of additional information about the recipe in order to enhance your knowledge about the recipe.

See also

This section, when present, provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, select your book, click on the Errata Submission Form link, and enter the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Working with Arrays

Arrays are an important construct of any programming language. To keep data of a similar type together, we need arrays. Arrays are heavily used in applications where elements have to be accessed at random. Arrays are also a prime choice when you need to sort elements, look for desired data in a collection, and find common or unique data between two sets. Arrays are assigned contiguous memory locations and are a very popular structure for sorting and searching data collections because any element of an array can be accessed by simply specifying its subscript or index location. This chapter will cover recipes that include operations commonly applied to arrays.

In this chapter, we will learn how to make the following recipes using arrays:

Inserting an element into a one-dimensional array

Multiplying two matrices

Finding the common elements in two arrays

Finding the difference between two sets or arrays

Finding the unique elements in an array

Finding whether a matrix is sparse

Merging two sorted arrays into one

Let's begin with the first recipe!

Inserting an element in an array

In this recipe, we will learn how to insert an element in-between an array. You can define the length of the array and also specify the location where you want the new value to be inserted. The program will display the array after the value has been inserted.

How it works...

Because we want to specify the length of the array, we will first define a macro called max and initialize it to a value of 100. I have defined the value of max as 100 because I assume that I will not need to enter more than 100 values in an array, but it can be any value as desired. An array, p, is defined of size max elements. You will be prompted to specify the length of the array. Let's specify the length of the array as 5. We will assign the value 5 to the variable n. Using a for loop, you will be asked to enter the elements of the array.

Let's say you enter the values in the array, as shown in Figure 1.1 given earlier:

In the preceding diagram, the numbers, 0, 1, 2, and so on are known as index or subscript and are used for assigning and retrieving values from an array. Next, you will be asked to specify the position in the array where the new value has to be inserted. Suppose, you enter 3, which is assigned to the variable k. This means that you want to insert a new value at location 3 in the array.

Because the arrays in C are zero-based, position 3 means that you want to insert a new value at index location 2, which is p[2]. Hence, the position entered in k is decremented by 1.

To create space for the new element at index location p[2], all the elements are shifted one position down. This means that the element at p[4] is moved to index location p[5], the one at p[3] is moved to p[4], and the element at p[2] is moved to p[3], as follows:

Figure 1.3

Once the element from the target index location is safely copied to the next location, you will be asked to enter the new value. Suppose you enter the new value as 99; that value will be inserted at index location p[2], as shown in Figure 1.2, given earlier:

Let’s use GCC to compile the insertintoarray.c program, as shown in this statement:

D:\CBook>gcc insertintoarray.c -o insertintoarray

Now, let’s run the generated executable file, insertintoarray.exe, to see the program output:

D:\CBook>./insertintoarray

Enter length of array:5

Enter 5 elements of array

10

20

30

40

50

The array is:

10

20

30

40

50

Enter target position to insert:3

Enter the value to insert:99

Array after insertion of element:

10

20

99

30

40

50

Voilà! We've successfully inserted an element in an array. 

There's more...

What if we want to delete an element from an array? The procedure is simply the reverse; in other words, all the elements from the bottom of the array will be copied one place up to replace the element that was deleted.

Let's assume array p has the following five elements (Figure 1.1):

Suppose, we want to delete the third element, in other words, the one at p[2], from this array. To do so, the element at p[3] will be copied to p[2], the element at p[4] will be copied to p[3], and the last element, which here is at p[4], will stay as it is:

Figure 1.4

The deletefromarray.c program for deleting the array is as follows:

#include<stdio.h>void main(){ int p[100],i,n,a; printf("Enter the length of the array: "); scanf("%d",&n); printf("Enter %d elements of the array \n",n); for(i=0;i<=n-1;i++) scanf("%d",&p[i]); printf("\nThe array is:\n");\ for(i=0;i<=n-1;i++) printf("%d\n",p[i]); printf("Enter the position/location to delete: "); scanf("%d",&a); a--; for(i=a;i<=n-2;i++) { p[i]=p[i+1]; /* All values from the bottom of the array are shifted up till the location of the element to be deleted */ } p[n-1]=0; /* The vacant position created at the bottom of the array is set to 0 */ printf("Array after deleting the element is\n"); for(i=0;i<= n-2;i++) printf("%d\n",p[i]);}

Now, let's move on to the next recipe!

Multiplying two matrices

A prerequisite for multiplying two matrices is that the number of columns in the first matrix must be equal to the number of rows in the second matrix.

How to do it…

Create two matrices of orders

2 x 3

and

3 x 4

each. 

Before we make the matrix multiplication program, we need to understand how matrix multiplication is performed manually. To do so, let's assume that the two matrices to be multiplied have the following elements:

Figure 1.5

The resultant matrix will be of the order

2 x 4

, that is, the resultant matrix will have the same number of rows as the first matrix and the same number of columns as the second matrix:

Figure 1.6

Essentially, the resultant matrix of the order 2 x 4 will have the following elements:

Figure 1.7

The element

first row, first column

in the resultant matrix is computed using the following formula:

SUM(first element of the first row of the first matrix × first element of the first column of the second matrix), (second element of the first row... × second element of the first column...), (and so on...)

For example, let's assume the elements of the two matrices are as shown in Figure 1.5.  The elements in the first row and the first column of the resultant matrix will be computed as follows:

Figure 1.8

Hence, the element in

first row, first column

in the resultant matrix will be as follows:

(3×6)+(9×3)+(7×5)=18 + 27 + 35=80

Figure 1.9 explains how the rest of the elements are computed in the resultant matrix:

Figure 1.9

The matrixmulti.c program for multiplying the two matrices is as follows:

#include <stdio.h>int main(){ int matA[2][3], matB[3][4], matR[2][4]; int i,j,k; printf("Enter elements of the first matrix of order 2 x 3 \n"); for(i=0;i<2;i++) { for(j=0;j<3;j++) { scanf("%d",&matA[i][j]); } } printf("Enter elements of the second matrix of order 3 x 4 \n"); for(i=0;i<3;i++) { for(j=0;j<4;j++) { scanf("%d",&matB[i][j]); } } for(i=0;i<2;i++) { for(j=0;j<4;j++) { matR[i][j]=0; for(k=0;k<3;k++) { matR[i][j]=matR[i][j]+matA[i][k]*matB[k][j]; } } } printf("\nFirst Matrix is \n"); for(i=0;i<2;i++) { for(j=0;j<3;j++) { printf("%d\t",matA[i][j]); } printf("\n"); } printf("\nSecond Matrix is \n"); for(i=0;i<3;i++) { for(j=0;j<4;j++) { printf("%d\t",matB[i][j]); } printf("\n"); } printf("\nMatrix multiplication is \n"); for(i=0;i<2;i++) { for(j=0;j<4;j++) { printf("%d\t",matR[i][j]); } printf("\n"); } return 0;}

Now, let's go behind the scenes to understand the code better.

How it works...

The two matrices are defined matA and matB of the orders 2 x 3 and 3 x 4, respectively, using the following statement:

int matA[2][3], matB[3][4]

You will be asked to enter the elements of the two matrices using the nested for loops. The elements in the matrix are entered in row-major order, in other words, all the elements of the first row are entered first, followed by all the elements of the second row, and so on.

In the nested loops, for i and for j, the outer loop, for i, represents the row and the inner loop, and for j represents the column.

While entering the elements of matrices matA and matB, the values entered in the two matrices will be assigned to the respective index locations of the two-dimensional arrays as follows:

Figure 1.10

The nested loops that actually compute the matrix multiplication are as follows:

for(i=0;i<2;i++) { for(j=0;j<4;j++) { matR[i][j]=0; for(k=0;k<3;k++) { matR[i][j]=matR[i][j]+matA[i][k]*matB[k][j]; } } }

The variable i represents the row of the resultant matrix, j represents the column of the resultant matrix, and k represents the common factor. The common factor here means the column of the first matrix and the row of the second matrix.

Recall that the prerequisite for matrix multiplication is that the column of the first matrix should have the same number of rows as the second matrix. Because the respective elements have to be added after multiplication, the element has to be initialized to 0 before addition.

The following statement initializes the elements of the resultant matrix:

matR[i][j]=0;

The for k loop inside the nested loops helps in selecting the elements in the rows of the first matrix and multiplying them by elements of the column of the second matrix:

matR[i][j]=matR[i][j]+matA[i][k]*matB[k][j];

Let's use GCC to compile the matrixmulti.c program as follows:

D:\CBook>gcc matrixmulti.c -o matrixmulti

Let's run the generated executable file, matrixmulti.exe, to see the output of the program:

D:\CBook\Chapters\1Arrays>./matrixmulti

Enter elements of the first matrix of order 2 x 3

3

9

7

1

5

4

Enter elements of the second matrix of order 3 x 4

6 2 8 1

3 9 4 0

5 3 1 3

First Matrix is

3 9 7

1 5 4

Second Matrix is

6 2 8 1

3 9 4 0

5 3 1 3

Matrix multiplication is

80 108 67 24

41 59 32 13

Voilà! We've successfully multiplied two matrices.

There’s more…

One thing that you might notice while entering the elements of the matrix is that there are two ways of doing it.

The first method is that you press

Enter

after inputting each element as

follows

:

3

9

7

1

5

4

The values will be automatically assigned to the matrix in row-major order, in other words, 3 will be assigned to matA[0][0], 9 will be assigned to matA[0][1], and so on.

The second method of entering elements in the matrix is as

follows

:

6 2 8 1

3 9 4 0

5 3 1 3

Here, 6 will be assigned to matB[0][0], 2 will be assigned to matB[0][1], and so on.

Now, let's move on to the next recipe!

Finding the common elements in two arrays

Finding the common elements in two arrays is akin to finding the intersection of two sets. Let's learn how to do it.

How it works...

A macro, max, is defined of size 100. A function, ifexists(), is defined that simply returns true (1) or false (0). The function returns true if the supplied value exists in the specified array, and false if it doesn't.

Two arrays are defined, called p and q, of size max (in other words, 100 elements). You will be prompted to specify the length of the array, p, and then asked to enter the elements in that array. After that, you will be asked to specify the length of array q, followed by entering the elements in array q.

Thereafter, p[0], the first element in array p , is picked up, and by using the for loop, p[0] is compared with all the elements of array q. If p[0] is found in array q, then p[0] is added to the resulting array, r.

After a comparison of p[0], the second element in array p, p[1], is picked up and compared with all the elements of array q. The procedure is repeated until all the elements of array p are compared with all the elements of array q.

If any elements of array p are found in array q, then before adding that element to the resulting array, r, it is run through the ifexists() function to ensure that the element does not already exist in array r. This is because we don't want repetitive elements in array r.

Finally, all the elements in array r, which are the common elements of the two arrays, are displayed on the screen.

Let's use GCC to compile the commoninarray.c program as follows:

D:\CBook>gcc commoninarray.c -o commoninarray

Now, let's run the generated executable file, commoninarray.exe, to see the output of the program:

D:\CBook>./commoninarray

Enter the length of the first array:5

Enter 5 elements in the first array

1

2

3

4

5

Enter the length of the second array:4

Enter 4 elements in the second array

7

8

9

0

There are no common elements in the two arrays

Because there were no common elements between the two arrays entered previously, we can't quite say that we've truly tested the program. Let's run the program again, and this time, we will enter the array elements such that they have something in common.

D:\CBook>./commoninarray

Enter the length of the first array:4

Enter 4 elements in the first array

1

2

3

4

Enter the length of the second array:4

Enter 4 elements in the second array

1

4

1

2

The common elements in the two arrays are:

1

2

4

Voilà! We've successfully identified the common elements between two arrays.

Finding the difference between two sets or arrays

When we talk about the difference between two sets or arrays, we are referring to all the elements of the first array that don't appear in the second array. In essence, all the elements in the first array that are not common to the second array are referred to as the difference between the two sets. The difference in sets p and q, for example, will be denoted by p – q.

If array p, for example, has the elements {1, 2, 3, 4}, and array q has the elements {2, 4, 5, 6}, then the difference between the two arrays, p - q, will be  {1,3}.  Let's find out how this is done.

How it works...

We defined two arrays called p and q. We don't want to fix the length of these arrays, so we should define a macro called max of value 100 and set the two arrays, p and q, to the size of max.

Thereafter, you will be prompted to specify the size of the first array and enter the elements in the first array, p. Similarly, you will be asked to specify the length of the second array, q, followed by entering the elements in the second array.

Let's assume you have specified the length of both arrays as 4 and have entered the following elements:

Figure 1.14

We need to pick up one element at a time from the first array and compare it with all the elements of the second array. If an element in array p does not appear in array q, it will be assigned to the third array we created, array r.

Array r will be used for storing the elements that define the difference between two arrays. As shown in Figure 1.15, the first element of array p, in other words, at p[0], is compared with all the elements of array q, in other words, with q[0], q[1], q[2], and q[3].

Because the element at p[0], which is 1, does not appear in array q, it will be added to the array r, indicating the first element representing the difference between the two arrays:

Figure 1.15

Because the element at p[1], which is 2, appears in array q, it is discarded, and the next element in array p, in other words, p[2], is picked up and compared with all the elements in array q.

As the element at p[2] does not appear in array q, it is added to array r at the next available location, which is r[1] (see Figure 1.16 as follows):

Figure 1.16

Continue the procedure until all the elements of array p are compared with all the elements of array q. Finally, we will have array r, with the elements showing the difference between our two arrays, p and q.

Let's use GCC to compile our program, differencearray.c, as follows:

D:\CBook>gcc differencearray.c -o differencearray

Now, let's run the generated executable file, differencearray, to see the output of the program:

D:\CBook>./differencearray

Enter length of first array:4

Enter 4 elements of first array

1

2

3

4

Enter length of second array:4

Enter 4 elements of second array

2

4

5

6

The difference of the two array is:

1

3

Voilà! We've successfully found the difference between two arrays. Now, let's move on to the next recipe!

Finding the unique elements in an array

In this recipe, we will learn how to find the unique elements in an array, such that the repetitive elements in the array will be displayed only once.

How it works...

We will define a macro called max of size 100. Two arrays, p and q, are defined of size max. Array p will contain the original elements, and array q will contain the unique elements of array p. You will be prompted to enter the length of the array and, thereafter, using the for loop, the elements of the array will be accepted and assigned to array p.

The following statement will assign the first element of array p to the first index location of our blank array, which we will name array q:

q[0]=p[0]

A for loop is again used to access the rest of the elements of array p, one by one. First, the foremost element of array p, which is at p[0], is copied to array q at q[0].

Next, the second array p element, p[1], is compared with all the existing elements of array q. That is, p[1] is checked against array q to confirm whether it is already present there.

Because there is only a single element in array q,  p[1] is compared with q[0]. Because p[1] does not exist in array q, it is copied at q[1].

This procedure is repeated for all elements in array p. Each of the accessed elements of array p is run through the ifexists() function to check whether any of them already exist in array q. 

The function returns 1 if an element in array p already exists in array q