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

Elena gilbert house inside - St augustine political philosophy - Hp 41c battery bay repair kit - 8x 3 6x 9 - The art of public speaking chapter 4 - Ethical issues with questionnaires - Funny poems about chores - Math - Glen waverley secondary college term dates - A 10 year bond pays an annual coupon - Business strategy game low cost strategy - Attached book in spanish - Environmental causes of miscarriage - Week 4 Part 2 - The condition of learning - Answer these questions - PPT(Team Management) - How is macy's positioned in the fashion market - Mount stuart memorial hall - Nsq1 - How does nike use management information systems - Essential skills for classroom management - Final Project - The moths and other stories pdf - C & k property management - Capsim final report paper - Reading Assignment - Benetton group annual report - One page paper - Uaa disability support services - Zanna don t script - Common base amplifier lab manual - Sociology o level marking scheme - Onboarding strategies to supercharge millennial employees - English 6 - Stork pmt poultry processing systems - Capricorn credit union bsb - Best report card comments - Analysing twentieth century history units 1 & 2 answers - Chemistry of hazardous materials meyer - The most consistent feature of workplace drug prevention programs has been - Hepa filter leak repair - Shadow health digital clinical experience health assessment - Consumer needs - Bose einstein condensate properties - Mrs watanabe and the japanese yen carry trade mini case - Ford cost of goods sold - Competitive And Technological Forces - Measuring the speed of light with a microwave oven - Adib foreign exchange rates - Peter pan and wendy play script pdf - Abbreviations used in prescription writing - Tip calculator app android studio - Accuracy reliability and validity secondary sources - Proj 587 week 5 case study - Hank kolb director quality assurance solutions - Construct grammatically correct sentences - Costco Strategic Management - Zeise's salt structure - Sydney water online bill - Unit 9 Final - Propaganda how not to be bamboozled summary - Funny props for skits - Borderlands 3 relentless night hawkin - Determination of the ka of a weak acid - Bell hooks engaged pedagogy - Snhu 107 final project ii academic success plan template - Compass maritime services - +971561686603 Abortion pills in Dubai/Abu Dhabi-mifepristone & misoprostol in DUBAI - Metropolitan dairy - What is the primary purpose of community corrections - How Is Policy Formulated? - Finding nemo movie worksheet - A wrinkle in time chapter 2 - Goring and woodcote medical practice - Xe full electron configuration - When washing hands which of the following statements is incorrect - 2 page - Gcu apa style guide - Create a personal vision statement - Find unicorn for couple - Artworks made using alternative media and processes - Case study - Chamberlain college of nursing program outcome 5 - Fry steel for sale - Monash unit guide 2016 - Chapter 5 - Dynamics in nursing art and science of professional practice - Macbeth act 1 scene 3 - Week 3 Discussion Terr - Comodo endpoint security ended prematurely - Ethics and Diversity - Apple watch series 5 target market - Graphological features english language - Excel 2016 module 8 review assignment - MarketingManagement_Assessment2 - Mcgraw hill connect economics homework answers - Limiting reagent lab vinegar and baking soda - An frg provides activities and support that encourages - Ultimate wood heaters hobart