Arrays allow storing and manipulating a collection of related data elements. They can hold groups of integers, characters, or other data types. Declaring individual variables becomes difficult when storing many elements, so arrays provide an efficient solution. Arrays are declared with a datatype and size, and elements can be initialized, accessed, inserted, deleted, and manipulated using their index positions. Common array operations include displaying values, finding maximum/minimum values, calculating sums, and passing arrays to functions. Multi-dimensional arrays extend the concept to store elements in a table structure accessed by row and column indexes.
Arrays allow storing multiple values of the same type. Arrays in C can be declared with the array name, element type, and size. Values can be initialized during or after declaration. Common operations on arrays include sorting, searching, and calculating statistics. Bubble sort iteratively compares and swaps adjacent elements to sort an array in ascending order. Linear search compares each element to a search key, while binary search divides the sorted array in half on each step. Binary search has lower computational complexity of O(log n) compared to O(n) for linear search.
Arrays are collections of related data items of the same data type. An array stores elements of the same data type in contiguous memory locations that are accessed using an index. The index is used to access individual elements, with the first element having an index of 0. Arrays can be initialized by assigning values to each element or by prompting for input during runtime using a for loop. Operations on arrays include insertion, deletion, and searching of elements. Searching can be done using linear search, which sequentially compares each element to the search key, or binary search, which divides the array in half and recursively searches within the narrowed range.
Using Arrays with Sorting and Searching Algorithms1) This program .pdff3apparelsonline
Using Arrays with Sorting and Searching Algorithms
1) This program has six required outputs and involves searching and sorting an array of integers.
Write a java application that initializes an array with the following numbers, in this order: 23, 17,
5, 90, 12, 44, 38, 84, 77, 3, 66, 55, 1, 19, 37, 88, 8, 97, 25, 50, 75, 61, and 49. Then display the
unsorted values. This is required output #1 of 6 for this program.
2) Using a sequential search of the unsorted array, determine and report the relative (i.e. 0,1, 2, 3,
4, etc.) positions of the following numbers in the array (or -1 if not found), and the number of
searches required to locate the numbers: 25, 30, 50, 75, and 92. This is required output #2 of 6.
3) Then display the total number of searches for all five numbers. This is required output #3 of 6.
4) Sort the numbers using a recursive quicksort and then display the sorted array. This is required
output #4 of 6.
5) Using a binary search of the sorted array, determine and report the 1-relative positions of the
following numbers in the array (or -1 if not found), and 2-the number of searches required to
locate the numbers: 25, 30, 50, 75, and 92. This is required output #5 of 6.
6) Finally, display the total number of searches for all five numbers. This is required output #6 of
6.
(There are six required sets of output as numbered in the above paragraphs.)
Create an object-oriented solution for this assignment. Create a class called SArray (Search
Array) that accepts the initial array through the constructor. The class should have a recursive
quick sort sorting method that will sort the array. The class should have two methods for
searching. One that does a sequential search that accepts as input the integer value that is to be
searched for and returns the index in array where the search value is if found, and -1 if not found.
The other search method should be a binary search of a sorted array that accepts as input the
integer value that is to be searched for and returns the index in the array where the search value
is if found, and -1 if not found. Create a toString method to display the contents of the array. The
driver/main class could not only pass in the initial array values but call various methods to
perform the searches, sorting, and array contents display thus enabling you to display the
information in the six items above.
Include additional comments as necessary and maintain consistent indentation
Make sure you upload your java source code and a screen snapshot of all of your program\'s
outputs to blackboard
Solution
import java.util.*;
//Class SArray definition
class SArray
{
//Array declaration
int arr[];
//Parameterized Constructor to assign array value
SArray(int a[])
{
arr = a;
}
//Display array
void toString(int a[])
{
for(int x = 0; x < arr.length; x++)
System.out.print(arr[x] + \" \");
}
//Sequential Search
int sequentialSearch(int a[], int s)
{
//Initially position is set to -1
int pos = -1;
//Loops till end of the arr.
A one-dimensional array stores elements linearly such that they can be accessed using an index, the document provides an example of finding the address of an element in a 1D array and taking user input to store in an array and display all elements, and abstract data types provide only the interface of a data structure without implementation details.
1. The document discusses various data structures concepts including arrays, dynamic arrays, operations on arrays like traversing, insertion, deletion, sorting, and searching.
2. It provides examples of declaring and initializing arrays, as well as dynamic array allocation using pointers and new/delete operators.
3. Searching techniques like linear search and binary search are explained, with linear search comparing each element sequentially while binary search eliminates half the elements at each step for sorted arrays.
The document discusses arrays and string operations in C programming. It defines arrays as structures that hold related data items of the same type. It covers one-dimensional and two-dimensional arrays, including declaring, initializing, accessing, and manipulating array elements. It also defines strings as sequences of characters stored as character arrays terminated with a null character. It discusses string declaration, input/output, and standard library functions for determining string length and manipulating strings.
This document provides an introduction and overview of arrays in C++. It defines what an array is, how to declare and initialize arrays, and how to access, insert, search, sort, and merge array elements. Key points covered include:
- An array is a sequenced collection of elements of the same data type. Elements are referenced using a subscript index.
- Arrays can be declared with a fixed or variable length. Elements are initialized sequentially in memory.
- Common array operations like accessing, inserting, searching, sorting and merging are demonstrated using for loops and examples. Searching techniques include sequential and binary search. Sorting techniques include selection, bubble and insertion sort.
- Arrays are passed
The document discusses linear data structures using sequential organization. It begins by defining sequential access and linear data structures. Linear data structures traverse elements sequentially, with direct access to only one element. Examples given are arrays and linked lists. The document then focuses on arrays, providing definitions and discussing array representation in memory, basic array operations like traversal and searching, and multi-dimensional arrays. Two-dimensional and three-dimensional arrays are explained with examples.
This document discusses arrays in C#, including declaring and creating arrays, accessing array elements, input and output of arrays, iterating over arrays using for and foreach loops, dynamic arrays using List<T>, and copying arrays. It provides examples of declaring, initializing, accessing, reversing, and printing arrays. It also covers reading arrays from console input, checking for symmetry, and processing arrays using for and foreach loops. Lists are introduced as a resizable alternative to arrays. The document concludes with exercises for practicing various array techniques.
Here are the steps to solve this problem:
1. Declare and initialize a 2D array to store roll numbers and marks of 5 students in 5 subjects.
2. Write a loop to input roll numbers and marks from the user.
3. Calculate the average of each student by summing marks of all subjects and dividing by total subjects.
4. Write if conditions to check averages above 80 and below 40 and print appropriate roll numbers and averages.
5. Calculate overall average by summing averages of all students and dividing by total students.
6. Print the overall average.
The document discusses various operations that can be performed on arrays, including traversing, inserting, searching, deleting, merging, and sorting elements. It provides examples and algorithms for traversing an array, inserting and deleting elements, and merging two arrays. It also discusses two-dimensional arrays and how to store user input data in a 2D array. Limitations of arrays include their fixed size and issues with insertion/deletion due to shifting elements.
Bucket sort is a distribution sorting algorithm that works by distributing elements of an array into buckets. It then sorts the elements within each bucket using a simpler sorting algorithm like insertion sort. The sorted buckets are then concatenated together to produce the final sorted array. Radix sort is a multiple pass sorting algorithm that distributes elements into buckets based on the value of each digit of the key. It processes keys digit-by-digit until the array is fully sorted. Address calculation sort uses a hash function to distribute elements into buckets (subfiles) based on the result of the hash function applied to each key. Elements are inserted into the buckets and sorted within using another sorting algorithm like insertion sort before concatenating the buckets to get the final sorted list
An array is a contiguous block of memory that stores elements of the same data type. Arrays allow storing and accessing related data collectively under a single name. An array is declared with a data type, name, and size. Elements are accessed via indexes that range from 0 to size-1. Common array operations include initialization, accessing elements using loops, input/output, and finding highest/lowest values. Arrays can be single-dimensional or multi-dimensional. Multi-dimensional arrays represent matrices and elements are accessed using multiple indexes. Common array applications include storing student marks, employee salaries, and matrix operations.
The document discusses algorithms and their use for solving problems expressed as a sequence of steps. It provides examples of common algorithms like sorting and searching arrays, and analyzing their time and space complexity. Specific sorting algorithms like bubble sort, insertion sort, and quick sort are explained with pseudocode examples. Permutations, combinations and variations as examples of combinatorial algorithms are also covered briefly.
The document discusses arrays and functions in C programming. It defines arrays as collections of similar data items stored under a common name. It describes one-dimensional and two-dimensional arrays, and how they are declared and initialized. It also discusses strings as arrays of characters. The document then defines functions as sets of instructions to perform tasks. It differentiates between user-defined and built-in functions, and describes the elements of functions including declaration, definition, and calling.
This document provides an overview of a course on data structures and applications. The course covers fundamental data structures like arrays, stacks, queues, linked lists, trees, graphs, and hashing. It aims to teach how to represent data structures linearly, design solutions to problems using various data structures, and apply hashing techniques. The modules cover introduction to data structures and arrays, stacks and queues, linked lists, trees, and graphs and hashing.
In this chapter we will learn about arrays as a way to work with sequences of elements of the same type. We will explain what arrays are, how we declare, create, instantiate and use them. We will examine one-dimensional and multidimensional arrays. We will learn different ways to iterate through the array, read from the standard input and write to the standard output. We will give many example exercises, which can be solved using arrays and we will show how useful they really are.
This document provides information on arrays in Java. It begins by defining an array as a collection of similar data types that can store values of a homogeneous type. Arrays must specify their size at declaration and use zero-based indexing. The document then discusses single dimensional arrays, how to declare and initialize them, and how to set and access array elements. It also covers multi-dimensional arrays, providing syntax for declaration and initialization. Examples are given for creating, initializing, accessing, and printing array elements. The document concludes with examples of searching arrays and performing operations on two-dimensional arrays like matrix addition and multiplication.
Here is the program to copy elements of an array into another array in reverse order:
#include <iostream>
using namespace std;
int main() {
int arr1[10], arr2[10];
cout << "Enter 10 integer inputs: ";
for(int i=0; i<10; i++) {
cin >> arr1[i];
}
for(int i=0, j=9; i<10; i++, j--) {
arr2[j] = arr1[i];
}
cout << "Array 1: ";
for(int i=0; i<10; i++) {
cout << arr1[i
The document discusses two searching algorithms - linear search and binary search. Linear search sequentially compares the target element to each element in the array, while binary search uses a divide and conquer approach to quickly hone in on the target element in a sorted array. Both algorithms are demonstrated with pseudocode and examples.
Multi-currency in odoo accounting and Update exchange rates automatically in ...Celine George
Most business transactions use the currencies of several countries for financial operations. For global transactions, multi-currency management is essential for enabling international trade.
The ever evoilving world of science /7th class science curiosity /samyans aca...Sandeep Swamy
The Ever-Evolving World of
Science
Welcome to Grade 7 Science4not just a textbook with facts, but an invitation to
question, experiment, and explore the beautiful world we live in. From tiny cells
inside a leaf to the movement of celestial bodies, from household materials to
underground water flows, this journey will challenge your thinking and expand
your knowledge.
Notice something special about this book? The page numbers follow the playful
flight of a butterfly and a soaring paper plane! Just as these objects take flight,
learning soars when curiosity leads the way. Simple observations, like paper
planes, have inspired scientific explorations throughout history.
Ad
More Related Content
Similar to CP PPT_Unit IV computer programming in c.pdf (20)
The document discusses arrays and string operations in C programming. It defines arrays as structures that hold related data items of the same type. It covers one-dimensional and two-dimensional arrays, including declaring, initializing, accessing, and manipulating array elements. It also defines strings as sequences of characters stored as character arrays terminated with a null character. It discusses string declaration, input/output, and standard library functions for determining string length and manipulating strings.
This document provides an introduction and overview of arrays in C++. It defines what an array is, how to declare and initialize arrays, and how to access, insert, search, sort, and merge array elements. Key points covered include:
- An array is a sequenced collection of elements of the same data type. Elements are referenced using a subscript index.
- Arrays can be declared with a fixed or variable length. Elements are initialized sequentially in memory.
- Common array operations like accessing, inserting, searching, sorting and merging are demonstrated using for loops and examples. Searching techniques include sequential and binary search. Sorting techniques include selection, bubble and insertion sort.
- Arrays are passed
The document discusses linear data structures using sequential organization. It begins by defining sequential access and linear data structures. Linear data structures traverse elements sequentially, with direct access to only one element. Examples given are arrays and linked lists. The document then focuses on arrays, providing definitions and discussing array representation in memory, basic array operations like traversal and searching, and multi-dimensional arrays. Two-dimensional and three-dimensional arrays are explained with examples.
This document discusses arrays in C#, including declaring and creating arrays, accessing array elements, input and output of arrays, iterating over arrays using for and foreach loops, dynamic arrays using List<T>, and copying arrays. It provides examples of declaring, initializing, accessing, reversing, and printing arrays. It also covers reading arrays from console input, checking for symmetry, and processing arrays using for and foreach loops. Lists are introduced as a resizable alternative to arrays. The document concludes with exercises for practicing various array techniques.
Here are the steps to solve this problem:
1. Declare and initialize a 2D array to store roll numbers and marks of 5 students in 5 subjects.
2. Write a loop to input roll numbers and marks from the user.
3. Calculate the average of each student by summing marks of all subjects and dividing by total subjects.
4. Write if conditions to check averages above 80 and below 40 and print appropriate roll numbers and averages.
5. Calculate overall average by summing averages of all students and dividing by total students.
6. Print the overall average.
The document discusses various operations that can be performed on arrays, including traversing, inserting, searching, deleting, merging, and sorting elements. It provides examples and algorithms for traversing an array, inserting and deleting elements, and merging two arrays. It also discusses two-dimensional arrays and how to store user input data in a 2D array. Limitations of arrays include their fixed size and issues with insertion/deletion due to shifting elements.
Bucket sort is a distribution sorting algorithm that works by distributing elements of an array into buckets. It then sorts the elements within each bucket using a simpler sorting algorithm like insertion sort. The sorted buckets are then concatenated together to produce the final sorted array. Radix sort is a multiple pass sorting algorithm that distributes elements into buckets based on the value of each digit of the key. It processes keys digit-by-digit until the array is fully sorted. Address calculation sort uses a hash function to distribute elements into buckets (subfiles) based on the result of the hash function applied to each key. Elements are inserted into the buckets and sorted within using another sorting algorithm like insertion sort before concatenating the buckets to get the final sorted list
An array is a contiguous block of memory that stores elements of the same data type. Arrays allow storing and accessing related data collectively under a single name. An array is declared with a data type, name, and size. Elements are accessed via indexes that range from 0 to size-1. Common array operations include initialization, accessing elements using loops, input/output, and finding highest/lowest values. Arrays can be single-dimensional or multi-dimensional. Multi-dimensional arrays represent matrices and elements are accessed using multiple indexes. Common array applications include storing student marks, employee salaries, and matrix operations.
The document discusses algorithms and their use for solving problems expressed as a sequence of steps. It provides examples of common algorithms like sorting and searching arrays, and analyzing their time and space complexity. Specific sorting algorithms like bubble sort, insertion sort, and quick sort are explained with pseudocode examples. Permutations, combinations and variations as examples of combinatorial algorithms are also covered briefly.
The document discusses arrays and functions in C programming. It defines arrays as collections of similar data items stored under a common name. It describes one-dimensional and two-dimensional arrays, and how they are declared and initialized. It also discusses strings as arrays of characters. The document then defines functions as sets of instructions to perform tasks. It differentiates between user-defined and built-in functions, and describes the elements of functions including declaration, definition, and calling.
This document provides an overview of a course on data structures and applications. The course covers fundamental data structures like arrays, stacks, queues, linked lists, trees, graphs, and hashing. It aims to teach how to represent data structures linearly, design solutions to problems using various data structures, and apply hashing techniques. The modules cover introduction to data structures and arrays, stacks and queues, linked lists, trees, and graphs and hashing.
In this chapter we will learn about arrays as a way to work with sequences of elements of the same type. We will explain what arrays are, how we declare, create, instantiate and use them. We will examine one-dimensional and multidimensional arrays. We will learn different ways to iterate through the array, read from the standard input and write to the standard output. We will give many example exercises, which can be solved using arrays and we will show how useful they really are.
This document provides information on arrays in Java. It begins by defining an array as a collection of similar data types that can store values of a homogeneous type. Arrays must specify their size at declaration and use zero-based indexing. The document then discusses single dimensional arrays, how to declare and initialize them, and how to set and access array elements. It also covers multi-dimensional arrays, providing syntax for declaration and initialization. Examples are given for creating, initializing, accessing, and printing array elements. The document concludes with examples of searching arrays and performing operations on two-dimensional arrays like matrix addition and multiplication.
Here is the program to copy elements of an array into another array in reverse order:
#include <iostream>
using namespace std;
int main() {
int arr1[10], arr2[10];
cout << "Enter 10 integer inputs: ";
for(int i=0; i<10; i++) {
cin >> arr1[i];
}
for(int i=0, j=9; i<10; i++, j--) {
arr2[j] = arr1[i];
}
cout << "Array 1: ";
for(int i=0; i<10; i++) {
cout << arr1[i
The document discusses two searching algorithms - linear search and binary search. Linear search sequentially compares the target element to each element in the array, while binary search uses a divide and conquer approach to quickly hone in on the target element in a sorted array. Both algorithms are demonstrated with pseudocode and examples.
Multi-currency in odoo accounting and Update exchange rates automatically in ...Celine George
Most business transactions use the currencies of several countries for financial operations. For global transactions, multi-currency management is essential for enabling international trade.
The ever evoilving world of science /7th class science curiosity /samyans aca...Sandeep Swamy
The Ever-Evolving World of
Science
Welcome to Grade 7 Science4not just a textbook with facts, but an invitation to
question, experiment, and explore the beautiful world we live in. From tiny cells
inside a leaf to the movement of celestial bodies, from household materials to
underground water flows, this journey will challenge your thinking and expand
your knowledge.
Notice something special about this book? The page numbers follow the playful
flight of a butterfly and a soaring paper plane! Just as these objects take flight,
learning soars when curiosity leads the way. Simple observations, like paper
planes, have inspired scientific explorations throughout history.
Geography Sem II Unit 1C Correlation of Geography with other school subjectsProfDrShaikhImran
The correlation of school subjects refers to the interconnectedness and mutual reinforcement between different academic disciplines. This concept highlights how knowledge and skills in one subject can support, enhance, or overlap with learning in another. Recognizing these correlations helps in creating a more holistic and meaningful educational experience.
Odoo Inventory Rules and Routes v17 - Odoo SlidesCeline George
Odoo's inventory management system is highly flexible and powerful, allowing businesses to efficiently manage their stock operations through the use of Rules and Routes.
How to Manage Opening & Closing Controls in Odoo 17 POSCeline George
In Odoo 17 Point of Sale, the opening and closing controls are key for cash management. At the start of a shift, cashiers log in and enter the starting cash amount, marking the beginning of financial tracking. Throughout the shift, every transaction is recorded, creating an audit trail.
How to Subscribe Newsletter From Odoo 18 WebsiteCeline George
Newsletter is a powerful tool that effectively manage the email marketing . It allows us to send professional looking HTML formatted emails. Under the Mailing Lists in Email Marketing we can find all the Newsletter.
The *nervous system of insects* is a complex network of nerve cells (neurons) and supporting cells that process and transmit information. Here's an overview:
Structure
1. *Brain*: The insect brain is a complex structure that processes sensory information, controls behavior, and integrates information.
2. *Ventral nerve cord*: A chain of ganglia (nerve clusters) that runs along the insect's body, controlling movement and sensory processing.
3. *Peripheral nervous system*: Nerves that connect the central nervous system to sensory organs and muscles.
Functions
1. *Sensory processing*: Insects can detect and respond to various stimuli, such as light, sound, touch, taste, and smell.
2. *Motor control*: The nervous system controls movement, including walking, flying, and feeding.
3. *Behavioral responThe *nervous system of insects* is a complex network of nerve cells (neurons) and supporting cells that process and transmit information. Here's an overview:
Structure
1. *Brain*: The insect brain is a complex structure that processes sensory information, controls behavior, and integrates information.
2. *Ventral nerve cord*: A chain of ganglia (nerve clusters) that runs along the insect's body, controlling movement and sensory processing.
3. *Peripheral nervous system*: Nerves that connect the central nervous system to sensory organs and muscles.
Functions
1. *Sensory processing*: Insects can detect and respond to various stimuli, such as light, sound, touch, taste, and smell.
2. *Motor control*: The nervous system controls movement, including walking, flying, and feeding.
3. *Behavioral responses*: Insects can exhibit complex behaviors, such as mating, foraging, and social interactions.
Characteristics
1. *Decentralized*: Insect nervous systems have some autonomy in different body parts.
2. *Specialized*: Different parts of the nervous system are specialized for specific functions.
3. *Efficient*: Insect nervous systems are highly efficient, allowing for rapid processing and response to stimuli.
The insect nervous system is a remarkable example of evolutionary adaptation, enabling insects to thrive in diverse environments.
The insect nervous system is a remarkable example of evolutionary adaptation, enabling insects to thrive
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schoolsdogden2
Algebra 1 is often described as a “gateway” class, a pivotal moment that can shape the rest of a student’s K–12 education. Early access is key: successfully completing Algebra 1 in middle school allows students to complete advanced math and science coursework in high school, which research shows lead to higher wages and lower rates of unemployment in adulthood.
Learn how The Atlanta Public Schools is using their data to create a more equitable enrollment in middle school Algebra classes.
INTRO TO STATISTICS
INTRO TO SPSS INTERFACE
CLEANING MULTIPLE CHOICE RESPONSE DATA WITH EXCEL
ANALYZING MULTIPLE CHOICE RESPONSE DATA
INTERPRETATION
Q & A SESSION
PRACTICAL HANDS-ON ACTIVITY
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingCeline George
The Accounting module in Odoo 17 is a complete tool designed to manage all financial aspects of a business. Odoo offers a comprehensive set of tools for generating financial and tax reports, which are crucial for managing a company's finances and ensuring compliance with tax regulations.
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...Celine George
Analytic accounts are used to track and manage financial transactions related to specific projects, departments, or business units. They provide detailed insights into costs and revenues at a granular level, independent of the main accounting system. This helps to better understand profitability, performance, and resource allocation, making it easier to make informed financial decisions and strategic planning.
A measles outbreak originating in West Texas has been linked to confirmed cases in New Mexico, with additional cases reported in Oklahoma and Kansas. The current case count is 795 from Texas, New Mexico, Oklahoma, and Kansas. 95 individuals have required hospitalization, and 3 deaths, 2 children in Texas and one adult in New Mexico. These fatalities mark the first measles-related deaths in the United States since 2015 and the first pediatric measles death since 2003.
The YSPH Virtual Medical Operations Center Briefs (VMOC) were created as a service-learning project by faculty and graduate students at the Yale School of Public Health in response to the 2010 Haiti Earthquake. Each year, the VMOC Briefs are produced by students enrolled in Environmental Health Science Course 581 - Public Health Emergencies: Disaster Planning and Response. These briefs compile diverse information sources – including status reports, maps, news articles, and web content– into a single, easily digestible document that can be widely shared and used interactively. Key features of this report include:
- Comprehensive Overview: Provides situation updates, maps, relevant news, and web resources.
- Accessibility: Designed for easy reading, wide distribution, and interactive use.
- Collaboration: The “unlocked" format enables other responders to share, copy, and adapt seamlessly. The students learn by doing, quickly discovering how and where to find critical information and presenting it in an easily understood manner.
2. ARRAY in C
• An array is a set of elements of the same data type that are referred
to by the same name.
• An array in C programming language can be defined as “number of
memory locations, each of which can store the same data type and
which can be referred by the same variable name”.
• All arrays consist of continuous memory locations.
• The lowest memory address corresponds to the first element and
the highest address to the last element.
3. Types of Arrays
Single dimensional Array/ Matrix
Linear Array
Single subscript Two subscripts Multiple subscripts
4. ARRAYS in C
• Array is a collection of homogenous data stored under unique name.
• The values in an array are called as “Elements of an Array”.
• These elements are accessed by numbers called as “subscripts or
index numbers”.
• Arrays may be of any variable type.
• An Array is declared as
data_type array_name [size]
e.g. int sample[10]
6. Initializing a Character Array
• Strings are one-
dimensional array of
characters terminated by a
null character ‘0’
• To hold the null character
at the end of an array, the
size of the character array
containing the string is one
more than the number of
characters in the word.
•
10. Single Dimensional Array
• A list of items can be given one variable name using only one subscript.
Such a variable is called as single dimensional array or single
subscripted variable.
• An array which is having either a single row or a single column is
termed as one dimensional array. One dimensional array have the
subscripts in a linear manner.
11. Program to input 10 numbers from user
and find total of them
• • Output:
Enter any ten numbers: 1
2
3
4
5
6
7
8
9
10
Total is: 55
12. #include<stdio.h>
int main( )
{
int a[25], n, i ;
float , ;
printf("Enter the number of terms:") ;
scanf("%d", &n) ;
printf("n Enter the Numbers:n") ;
for (i = 0 ; i < n ; i++)
{
scanf("%d", &a[i]) ;
}
12
for (i = 0 ; i < n ; i++)
{
sum = sum + a[i] ;
avg = sum / n ;
}
printf("n Mean of entered
Numbers are : %f ", mean) ;
return ( 0 ) ;
}
Write a Program in c to find the mean of n
numbers using array
13. • Write a Program in C to find the mean of n numbers using array
13
#include < stdio.h >
int main( )
{
int a[25], n, i ;
float mean = 0, sum = 0 ;
printf(" Enter the Numbers of
terms: ") ;
scanf("%d ",& n) ;
printf("n Enter the Numbers :
n") ;
for ( i = 0 ; i < =n ; i++)
{
scanf("%d ",& a[i]) ;
}
for ( i = 0 ; i < n ; i++)
{
sum = sum + a[i] ;
avg = sum / n ;
}
printf("n Mean of
entered Numbers are :
%f ",mean) ;
return ( 0 ) ;
}
14. C Program to Copy All the
Elements of One Array to
Another Array
14
#include <stdio.h>
int main()
{
int a[5] = { 3, 6, 9, 2, 5 }, n = 5;
int b[n], i;
printf("The first array is :");
for (i = 0; i < n; i++)
{
printf("%d", a[i]);
}
// copying elements from one array to another
for (i = 0; i < n; i++)
{
b[i] = a[i];
}
// displaying array after copying the
//elements from one array to other
printf("nThe second array is :");
for (i = 0; i < n; i++) {
printf("%d ", b[i]);
}
return 0;
}
15. Program to find the smallest and largest number from an array.
•
17. Program to search an element in the array
• Output:
Enter elements of an array:
10 9 8 7 6 5 4 3 2 1
Enter item to search: 6
Item found at location: 5
18. 18
Reversing Arrays in C
#include<stdio.h>
int main()
{
int i, n, arr[n], i;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements: ");
for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int rev[n], j = 0;
for(j = n-1; j >= 0; j--)
{
rev[j] = arr[i];
}
printf("The Reversed array: ");
for(j = 0; j < n; j++)
{
printf("%d ", rev[j]);
} }
19. 2D Array (Two Dimensional Array)
• The two-dimensional array can be defined as an array of arrays.
• The 2D array is organized as matrices which can be represented as
the collection of rows and columns.
19
Declaration of two dimensional Array in C
The syntax to declare the 2D array is given below.
data_type array_name [rows] [columns];
Consider the following example.
int twodimen[4][3];
21. Multi Dimensional Array
• C language allows array of 3 or more dimensions is called as multi-
dimensional array.
• The syntax to declare the multi-dimentional array is given below.
• data_type array_name [S1] [S2] [S3] …. [Sn]
• Consider the following example.
• int sample1 [4] [5] [5];
• float sample2 [10] [20] [30];
21
24. C Program to add 2 Matrices
• Output:
Enter the number of rows and columns of matrix
2 2
Enter the elements of first matrix
1 2
3 4
Enter the elements of second matrix
5 6
2 1
Sum of entered matrices
6 8
5 5
27. Sorting:
27
What is Sorting?
A Sorting Algorithm is used to rearrange a given array or list of elements according to a
comparison operator on the elements. The comparison operator is used to decide the
new order of elements in the respective data structure.
29. Linear Searching :
• Linear search is the simplest method for searching. In Linear search technique of searching;
the element to be found in searching the elements to be found is searched sequentially in
the list.
• This method can be performed on a sorted or an unsorted list
In case of a sorted list searching starts from 0th element and continues until the element is
found from the list or the element whose value is greater than (assuming the list is sorted
in
ascending order), the value being searched is reached.
29
30. Linear Search Algorithm
• Step 1: First, read the search element (Target element) in the array.
Step 2: In the second step compare the search element with the first
element in the array.
Step 3: If both are matched, display “Target element is found” and
terminate the Linear Search function.
Step 4: If both are not matched, compare the search element with the
next element in the array.
Step 5: In this step, repeat steps 3 and 4 until the search (Target)
element is compared with the last element of the array.
Step 6 :– If the last element in the list does not match, the Linear Search
Function will be terminated, and the message “Element is not found”
will be displayed.
30
32. Bubble Sort Algorithm
• Bubble Sort is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in the wrong order.
32
Input: arr[] = {5, 1, 4, 2, 8}
First Pass:
Bubble sort starts with very first two elements, comparing them to check which one is
greater.
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps
since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5),
algorithm does not swap them.
33. Bubble Sort Algorithm
33
Second Pass:
Now, during second iteration it should look like this:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Third Pass:
Now, the array is already sorted, but our algorithm does not know if it is completed.
The algorithm needs one whole pass without any swap to know it is sorted.
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
34. Program for sorting an array in ascending order
#include<stdio.h>
int main()
{
int array[50], n, i, j, temp;
printf("Enter the number of elements:n");
scanf("%d",&n);
printf("Enter the %d integers:n",n);
for(i=0;i<n;++i)
{
scanf("%d",&array[i]);
}
35. Program for sorting an array in ascending order (Continued )
//Ascending Order
for(i=0; i<n; i++)
for(j=i+1; j<n; j++)
{
if(array[i]>array[j])
{
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
printf("Sorted list in
ascending order:n");
for(i=0;i<n;i++)
printf("%dn",array[i]);
return 0;
}
36. 36
Arrays in C: Bubble Sort in Ascending order
for(i=0; i<n; i++)
for(j=i+1; j<n; j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
for(i=0; i<n; i++)
{
printf("%dt",a[i]);
}
}
#include<stdio.h>
int main(void)
{
int a[100], i, j, temp, n;
printf("n Enter the max no.of Elements
to Sort: n");
scanf("%d",&n);
printf("n Enter the Elements : n");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
37. • Given an array arr[] of N elements, the task is to write a function to
search a given element x in arr[].
• Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170}, x = 110;
Output: 6
Explanation: Element x is present at index 6
• Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170}, x = 175;
Output: -1
Explanation: Element x is not present in arr[].
37
38. Insertion Sort Algorithm
• Insertion sort algorithm sorts the dataset by transferring
one element at a time to the partially sorted array. Thus,
this sorting algorithm has a low overhead.
38
Consider the following example:
40 30 10 70 50 20 60
We consider 40 as the partially sorted array. When we consider 30, it is less than 40. So we swap
them. Then, we consider 30 and 40 are in the partially sorted array.
30 40 10 70 50 20 60
Now, we consider 10. 10 is less than 30. So, we place the elements as below. 10, 30 and 40 are in
the partially sorted array.
10 30 40 70 50 20 60
39. Insertion Sort Algorithm
39
Now, we consider 70. It is greater than 40, so there is no need for any
movement. 10, 30, 40, 70 are in the partially sorted array.
Now, consider 50. It is less than 70 but greater than 40. We can place them in
the correct position. 10,30, 40, 50,70 are now in the partially sorted array.
10 30 40 50 70 20 60
Now, consider 20. It is greater than 10 but less than 30. We can place it in the
correct position. 10,20,30,40,50, 70 are in the partially sorted array.
10 20 30 40 50 70 60
Consider 60. It is less than 70 but greater than 50. We can place it in the
correct position.
10 20 30 40 50 60 70
Now, we can see that all the elements are sorted. Here, the number of swaps
in insertion sort is minimized but the number of comparisons is still high.
40. Insertion Sort Algorithm
• Before going through the program, lets see the steps
of insertion sort with the help of an example.
Input elements: 89 17 8 12 0
•
Step 1: 89 17 8 12 0 (the bold elements are sorted
list and non-bold unsorted list)
•
Step 2: 17 89 8 12 0 (each element will be
removed from unsorted list and placed at the right
position in the sorted list)
Step 3: 8 17 89 12 0
Step 4: 8 12 17 89 0
Step 5: 0 8 12 17 89 40
41. Insertion Sort Algorithm
41
#include<stdio.h>
int main()
{
int i, j, count, temp, Array[25];
printf("How many numbers u are going
to enter?:");
scanf("%d",&count);
printf("Enter %d elements: ", count);
// This loop would store the input
numbers in array
for(i=0; i<count; i++)
scanf("%d", &Array[i]);
// Implementation of insertion sort algorithm
for(i=1; i<count; i++)
{
temp=Array[i];
j=i-1;
while((temp<Array[j]) && (j>=0))
{
Array[j+1]=Array[j];
j=j-1;
}
Array[j+1]=temp;
}
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf("%d", Array[i]);
return 0;
}
OUTPUT:
42. 2D Array (Two Dimensional Array)
• The two-dimensional array can be defined as an array of arrays. The
2D array is organized as matrices which can be represented as the
collection of rows and columns.
42
Declaration of two dimensional Array in C
The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];
Consider the following example.
int twodimen[4][3];
43. 43
C program to Insert an element in an Array
First get the element to be inserted, say x
Then get the position at which this element is to be inserted, say pos
Then shift the array elements from this position to one position forward(towards right),
and do this for all the other elements next to pos.
Insert the element x now at the position pos, as this is now empty.