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

Major fish diseases and their control ppt - Taco bell employee handbook 2019 - Sandisk ssd plus cache - The outsiders questions chapter 2 - Week 3 Project - Economics in Healthcare Setting - Information literacy - Wk#4 Research paper - Aliant payment systems inc - Hoa lac hi tech park - Electron configuration quiz answer key - 36 area of region between 2 curves homework answers - What does relative humidity describe about air - Www veltechuniv edu in fee payment - Nursing metaparadigm diagram - Cogent on net buildings - Tacoma longshore casual draw 2018 - Glo bus practice year 6 - Metar decoder key - Wileyplus financial accounting chapter 9 answers - Boston sea rovers internship - What is stance in writing - Questions 2 - Environmental and sanitation engineering uts - Axe street barking development - A negative times interest earned ratio suggests that the company - Astrology in the elizabethan era - Computer hardware industry average financial ratios - Resistance problems with solutions - In praise of folly summary sparknotes - Photosynthesis and cellular respiration practice test - Motivating Behavior and Work and Rewards Assignment - Foxx and azrin toilet training article - Combustion analysis of a 13.42 g sample - Iturralde v hilo medical center usa summary - Originally carol ann duffy - Project Assignment: - If x is binomial with n = 5 and p = 0.05, the chance that x is at least 1 is 0.6240 - Research paper. - Resource Assignment - Social exchange theory and ethics in nursing - DOC690 MOD 2 - Reciprocal inhibition in healthcare - Old english hsc syllabus - The meryl corporation common stock - 4800 x 1200 dpi meaning - Post-mortem - David i steinberg law group llc - She should have died hereafter technique - The Art of Interviewing - submission after one hour - Netflix porter's five forces analysis 2017 - Test - 3 cubed minus 2 squared times 5 - Argumentative Paper #4 - Aunt alexandra being racist - The pump in a vacuum cleaner is merely - The microscope field is the ________ - Greek club liverpool nsw 2170 - Discussion 1 - Name of eight english kings - Parts of the sun - In the jilting of granny weatherall who is cornelia - Choose a specific regulatory behavior - Comparing humans to computers - The following information about monfort manufacturing is available - Which of the following would be considered an assurance engagement - Borderlands 2 caustic caverns ever blow bubbles - Oral language composite wiat iii - Econ10003 - introductory macroeconomics - Chain of command pros and cons - Amadeus net flights search - Cities of the world - American politics in comparative perspective - Discussion Question - 1.30 as a fraction - Lag length selection eviews - The norton introduction to literature 13th edition table of contents - Multisim word generator and logic analyzer - Sarbanes oxley act powerpoint presentation - What is the difference between nude and naked - Lg hi macs white granite - James squire dan murphys - Nursing interventions for kussmaul respirations - I need to complete my assinments for cert iv in disablity - Your response is off by a multiple of ten webassign - Stoichiometry of a precipitation reaction labpaq answers - 1234567891011 find the mistake if you are genius answer - Https www amazon com ref nav_logo_prime - 10 25 police code - Counselor impairment - Hid proximity entryprox manual - Vmware vsphere data protection advanced - Gpss world student version free download - Kfc industry classification - Story map for two kinds answers - Glasbrook bros ltd v glamorgan county council - Corporate visions power messaging - Existentialism and human emotions summary - Kip r irvine assembly language pdf - Bundaberg dump opening hours - How do language techniques effect the reader