Loading...

Messages

Proposals

Stuck in your homework and missing deadline? Get urgent help in $10/Page with 24 hours deadline

Get Urgent Writing Help In Your Essays, Assignments, Homeworks, Dissertation, Thesis Or Coursework & Achieve A+ Grades.

Privacy Guaranteed - 100% Plagiarism Free Writing - Free Turnitin Report - Professional And Experienced Writers - 24/7 Online Support

Computer science a structured programming approach using c answers

27/10/2021 Client: muhammad11 Deadline: 2 Day

Programming Applications For Engineers

2

Objectives

❏ To understand the basic concepts and uses of arrays

❏ To be able to define C arrays

❏ To be able to pass arrays and array elements to functions

❏ To understand the sequential search algorithm

❏ To write programs that search arrays

Chapter 8 Arrays

3

8-1 Concepts

• Imagine we have a problem that requires us to read, process, and print a large number of integers. We must also keep the integers in memory for the duration of the program.

• To process large amounts of data we need a powerful data structure, the array.

• An array is a collection of elements of the same data type. • Since an array is a sequenced collection, we can refer to the elements in

the array as the first element, the second element, and so forth until we get to the last element.

4

FIGURE 8-2 Ten Variables

5

FIGURE 8-3 Process 10 variables

6

FIGURE 8-4 An Array of Scores

7

FIGURE 8-5 Loop for 10 Scores

8

8-2 Using Arrays in C

In this section, we first show how to declare and define arrays. Then we present several typical applications using arrays including reading values into arrays, accessing and exchanging elements in arrays, and printing arrays.

Declaration and Definition Accessing Elements in Arrays Storing Values in Arrays Index Range Checking

Topics discussed in this section:

9

FIGURE 8-6 The Scores Array

10

FIGURE 8-7 Declaring and Defining Arrays

11

Only fixed-length arrays can be initialized when they are defined. Variable length arrays must be initialized by inputting or assigning the values.

Note

12

FIGURE 8-8 Initializing Arrays

13

One array cannot be copied to another using assignment.

Note

Exercise 1 • Write a C program that:

• Declare a constant value SIZE= 10

• Declare two arrays A and B with 10 elements

• Read 10 elements in an array A of integer.

• Copy the elements of array A into another array B.

• Change the values in the array B to 100 if they are greater than 100.

• Change the values in the array B to 10 if they are less or equal to 0.

• Print the values of the original array A and the new array B as below:

14

Exercise 1 - Solution

• Write a C program that: • Declare a constant value SIZE= 10

#define SIZE 10

• Declare two arrays A and B with 10 elements

int A[SIZE], B[SIZE];

• Read 10 elements in an array A of integer.

printf("Input %d elements in the array :\n", SIZE);

for (i = 0;i

{

printf("element - %d : ", i);

scanf("%d", &A[i]);

}

15

Exercise 1 - Solution

• Copy the elements of array A into another array B.

• Change the values in the array B to 100 if they are greater than 100.

• Change the values in the array B to 10 if they are less or equal to 0.

for (i = 0; i

{

B[i] = A[i];

if (B[i] > 100)

B[i] = 100;

else if (B[i] <= 0)

B[i] = 10;

}

16

Exercise 1 - - Solution

• Print the values of the original array A and the new array B as below:

printf("\nOrigin array A :\n");

for (i = 0; i

printf("% 5d", A[i]);

printf("\n\nNew array B :\n");

for (i = 0; i

printf("% 5d", B[i]);

printf("\n\n");

17

Computer Science: A Structured Programming Approach Using C

18

FIGURE 8-9 Exchanging Scores—the Wrong Way

19

FIGURE 8-10 Exchanging Scores with Temporary Variable

Exercise 2 • Write a C program that:

• Declare a constant value SIZE= 12

• Declare an array A with 12 elements

• Print 5 Numbers per Line as below.

20

21

#include #include #define SIZE 12 int main() { int A[SIZE], i, linecount=0; printf("Input %d elements in the array :\n", SIZE); for (i = 0;i

printf("element - %d : ", i);scanf("%d", &A[i]); } for (i = 0; i < SIZE; i++) {

printf("% 5d", A[i]); linecount++; if (linecount % 5 == 0)

printf("\n"); } printf("\n\n"); system("pause"); return 0; }

Exercise 2 - Solution

22

PROGRAM 8-2 Squares Array

Computer Science: A Structured Programming Approach Using C

23

PROGRAM 8-3 Print Input Reversed

Computer Science: A Structured Programming Approach Using C

24

PROGRAM 8-2 Print Input Reversed

Computer Science: A Structured Programming Approach Using C

25

PROGRAM 8-2 Print Input Reversed

Computer Science: A Structured Programming Approach Using C

26

8-3 Inter-function Communication

To process arrays in a large program, we have to be able to pass them to functions. We can pass arrays in two ways: pass individual elements or pass the whole array. In this section we discuss first how to pass individual elements and then how to pass the whole array.

Passing Individual Elements Passing the Whole Array

Topics discussed in this section:

Computer Science: A Structured Programming Approach Using C

27

FIGURE 8-11 Passing Array Elements

Computer Science: A Structured Programming Approach Using C

28

PROGRAM 8-4 Calculate Array Average

Computer Science: A Structured Programming Approach Using C

29

PROGRAM 8-4 Calculate Array Average

Computer Science: A Structured Programming Approach Using C

30

PROGRAM 8-6 Change Values in an Array

Computer Science: A Structured Programming Approach Using C

31

PROGRAM 8-6 Change Values in an Array

Exercise 3: Find the output of the following code

32

#include #include #define SIZE 10 int f1(int a[]); int main() {

int A[SIZE] = {5,2,1,2,3,6,1,8,9,6,}, i, r; for (i = 0; i < SIZE; i++)

printf("%4d", A[i]); printf("\n"); r = f1(A); for (i = 0; i < SIZE; i++)

printf("%4d", A[i]); printf(“\nSum = %d \n",r); return 0;

} int f1(int a[]) {

int i,s = 2; for (i = 0;i < SIZE; i = i + 2) {

s = s + a[i]; a[i] = 0;

} return(s + 10);

}

Exercise 3: Find the output of the following code

33

#include #include #define SIZE 10 int f1(int a[]); int main() {

int A[SIZE] = {5,2,1,2,3,6,1,8,9,6,}, i, r; for (i = 0; i < SIZE; i++)

printf("%4d", A[i]); printf("\n"); r = f1(A); for (i = 0; i < SIZE; i++)

printf("%4d", A[i]); printf(“\nSum = %d \n",r); return 0;

} int f1(int a[]) {

int i,s = 2; for (i = 0;i < SIZE; i = i + 2) {

s = s + a[i]; a[i] = 0;

} return(s + 10);

}

34

Chapter 8 Problems 16, 28, 29

Computer Science: A Structured Programming Approach Using C

35

8-6 Searching

Another common operation in computer science is searching, which is the process used to find the location of a target among a list of objects. In the case of an array, searching means that given a value, we want to find the location (index) of the first element in the array that contains that value.

Sequential Search

Topics discussed in this section:

Computer Science: A Structured Programming Approach Using C

36

FIGURE 8-27 Search Concept

Computer Science: A Structured Programming Approach Using C

37

FIGURE 8-28 Locating Data in Unordered List

Computer Science: A Structured Programming Approach Using C

38

FIGURE 8-29 Unsuccessful Search in Unordered List

Sequential Search • Compares each element of an array with a search key

• Just as likely that the value will be found in the first element as the last • On average, program must compare the search key with half the elements of the array

• To determine that value is not in array, program must compare the search key to every element in the array

• Works well for small or unsorted arrays

39

EXERCICE 4

40

• Define a function linearSearch for searching a target within an array. The function should return the position of the target if it is found in the array, otherwise the function should return -1.

Function prototype: int linearSearch(int a[], int size, int target);

• Write a main function to ask user to enter 10 values and find the position of the target 15 in the array.

Expected output:

Exercise 4 – Solution (Sequential Search)

int linearSearch(int a[], int size, int target) { // Return the position of target if it is found in the array // Return -1 if the target is not found in the array int i; for (i = 0;i

return i;

return -1; }

#include #include #define SIZE 10 int linearSearch(int a[], int size, int target); int main() {

int t[SIZE], search, i, a; int target = 15; printf("Enter %d integer(s)\n", SIZE); for (i = 0; i < SIZE; i++)

scanf("%d", &t[i]); a = linearSearch(t, SIZE, target); printf("position = %d \n", a); if (a != -1)

printf("%d is found in the array at position %d\n", target,a); else

printf("%d is not found in the array.\n\n", target); system("pause"); return 0;

}

42

Chapter 8 Problem 36

Computer Science: A Structured Programming Approach Using C

43

8-7 Two-Dimensional Arrays

The arrays we have discussed so far are known as one-dimensional arrays because the data are organized linearly in only one direction. Many applications require that data be stored in more than one dimension. One common example is a table, which is an array that consists of rows and columns.

Declaration Passing A Two-Dimensional Array

Topics discussed in this section:

Computer Science: A Structured Programming Approach Using C

44

FIGURE 8-34 Two-dimensional Array

Computer Science: A Structured Programming Approach Using C

45

FIGURE 8-35 Array Of Arrays

Computer Science: A Structured Programming Approach Using C

46

FIGURE 8-36 Memory Layout

Computer Science: A Structured Programming Approach Using C

47

FIGURE 8-37 Passing a Row

Exercise 5

• Write a program that sums the elements of a given 2D array.

Computer Science: A Structured Programming Approach Using C

48

Exercise 6

• How will you calculate the average of integers in this 2-D array?

Computer Science: A Structured Programming Approach Using C

49

Computer Science: A Structured Programming Approach Using C

50

PROGRAM 8-16 Convert Table to One-dimensional Array

Computer Science: A Structured Programming Approach Using C

51

PROGRAM 8-16 Convert Table to One-dimensional Array

Square Matrix no. of rows = no. of columns

(e.g. 6 x 6 Matrix)

Computer Science: A Structured Programming Approach Using C

52

FIGURE 8-39 Example of Filled Matrix

Computer Science: A Structured Programming Approach Using C

53

PROGRAM 8-17 Fill Matrix

Computer Science: A Structured Programming Approach Using C

54

PROGRAM 8-17 Fill Matrix

Exercise

• Write a function sum2D that takes a 2D array of integers and its number of rows as arguments, and returns their sum.

• Write a function sumRows that takes a 2D array of integers, an empty array, and its size, as arguments, and returns the sum of each row in the empty array.

Computer Science: A Structured Programming Approach Using C

Homework is Completed By:

Writer Writer Name Amount Client Comments & Rating
Instant Homework Helper

ONLINE

Instant Homework Helper

$36

She helped me in last minute in a very reasonable price. She is a lifesaver, I got A+ grade in my homework, I will surely hire her again for my next assignments, Thumbs Up!

Order & Get This Solution Within 3 Hours in $25/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 3 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 6 Hours in $20/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 6 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 12 Hours in $15/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 12 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

6 writers have sent their proposals to do this homework:

Homework Guru
Isabella K.
Quick Finance Master
Top Class Engineers
Chartered Accountant
Assignment Solver
Writer Writer Name Offer Chat
Homework Guru

ONLINE

Homework Guru

I will be delighted to work on your project. As an experienced writer, I can provide you top quality, well researched, concise and error-free work within your provided deadline at very reasonable prices.

$19 Chat With Writer
Isabella K.

ONLINE

Isabella K.

I have worked on wide variety of research papers including; Analytical research paper, Argumentative research paper, Interpretative research, experimental research etc.

$38 Chat With Writer
Quick Finance Master

ONLINE

Quick Finance Master

I have worked on wide variety of research papers including; Analytical research paper, Argumentative research paper, Interpretative research, experimental research etc.

$38 Chat With Writer
Top Class Engineers

ONLINE

Top Class Engineers

After reading your project details, I feel myself as the best option for you to fulfill this project with 100 percent perfection.

$36 Chat With Writer
Chartered Accountant

ONLINE

Chartered Accountant

I reckon that I can perfectly carry this project for you! I am a research writer and have been writing academic papers, business reports, plans, literature review, reports and others for the past 1 decade.

$20 Chat With Writer
Assignment Solver

ONLINE

Assignment Solver

I reckon that I can perfectly carry this project for you! I am a research writer and have been writing academic papers, business reports, plans, literature review, reports and others for the past 1 decade.

$41 Chat With Writer

Let our expert academic writers to help you in achieving a+ grades in your homework, assignment, quiz or exam.

Similar Homework Questions

Gaia cs umass edu wireshark labs - Fumigation certificate sri lanka - Brain train answer key - A 10000 n vehicle is stalled one quarter - Liquid kerosene flows through a venturi meter - Pelvicalyceal dilatation icd 10 - Healthcare organizations that span several states - World Civilization before 1650. mike marshall - Http www strategicbusinessinsights com vals surveynew shtml - Electrical signs and symbols - Assignment 7.1: My Leadership and Advocacy Philosophy - Ma rainey trust no man - Edu 671 fundamentals of educational research - The crucible act 1 summary - How many degrees of unsaturation does the compound c5h10 have - Bo from swamp loggers death - Music assignment - SUBMIT BACK WITHIN NEXT 6 hours - 300 word essay - The adventure of charles augustus milverton pdf - How to see gpa rmit - Statistics chapter 12 review answers - Un2800 special provision a67 - Sc4730 environmental science - How to determine critical path in pert chart - Static electricity lab report - Like water for chocolate chapter 3 summary - Postpartum maternal depression - Four components of classroom management - Ru school of chinese thought - Cadbury snowflake chocolate bar - Athans & taylor joondalup - Gif sur yvette cnrs - Sullivan.angellearning.com - Smug aura rock for sale - Discussion Post - Did fev catch the ball - 4ajob wendy's - Borohydride reduction of a ketone hydrobenzoin from benzil lab report - Aci 551.2 r 15 pdf - Functional requirements for online cab booking - What does figure weights measure on the wisc-v - Drexel nursing student handbook - Wk 4 - Terminology of the Body Systems - Discussion Week 7 - Nordstrom case study analysis - Career support programme claim form - Wh questions in past - Wireless plc communication with gsm module - Http communitycoffee com flymore - Sales engineer comp plan examples - How many syllables in snail - Michael mcalpin ucf - Los primos ____ bien. - Comparison & contrast between plato and machiavelli - In mrp scheduled receipts are - Why is jules verne famous - Overall equipment effectiveness ppt - Thermal analysis of disc brake ppt - Leaping lizard cafe brimbank park - Apple cider vinegar for trichomoniasis - Florence foster jenkins death - CJ 3200 MOD 3 DB 1 - Challenges faced by small companies to create an efficient job classification system in which they can compete with other larger companies to attract, recruit, and retain highly talented employees. - As 1926 swimming pool safety - Toyota usa automobile museum - Nazareth catholic church grovedale - Transaction exposure and translation exposure - How to pronounce subitizing - Brundtland report our common future - 10 100 cb code - Pancakes by joan bauer plot - Identify the literature that addresses the disclosure of accounting policies - Global 172 essay 2 - Ano natsu he piano sheet music - Los angeles county chief executive office - Why is the reflection in a spoon upside down - Netiq identity governance documentation - Btu lb f to kj kg k - Importance of personal presentation hygiene and conduct in a salon - What are the 5 subaru tenets - Qualified accountant corporations act 2001 - The vampire diaries the awakening book pdf - Jarron draper - "as the price of apples goes up, the demand for apples goes down." the author of this statement - Ethics in Electronic Mediated Communication - Shadow health cough danny rivera - What is bas excluded - What is the difference between operating and financial leverage - Week 7 ORG400 - Business plan template australia - Have you ever seen the rain rod stewart - Standish medical practice login - Walgreens inventory turnover - Burnaston toyota car factory - Operations management simulation inventory basics answers - OPS/350 WK2 Parts Emporium Case Study - Applying the roper-logan-tierney model in practice read online - Vp no2 vs c16 - How do you park a computer 13.7 answer key - Principles of Ethics 445N