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

What processes and systems might actually stifle innovation and intrapreneurship - Formic acid and sodium formate equation - A christmas carol staves - For my own good all causes shall give way - 1/3 of 5/8 in its simplest form - 10 planks of the communist manifesto pdf - Two ways to live - I just wanna be average - Quantify a network in order to map it, ensure everything in the system is reporting correctly, and demonstrate one of the first steps a hacker would take to try to gain access to the system. - 12$$ - The two blocks shown are originally at rest neglecting - Accounting transaction analysis worksheet - Pol 201 week 1 discussion 1 - Public Administration - Jody has a 5 pound bag of potatoes - The proper quantity of safety stock is typically determined by - What makes curley's wife an outsider quote - Which sentence in the passage contains an allusion - International Governance and Global Business - 200 words - Reading review the harlem renaissance answers - Understanding and using english grammar 4th edition answer key pdf - 1128 estuary road bouvard - Family planning clinic aberdare health centre - MGT312T Week 5 Apply Exercise SCORE 100 PERCENT - History revolutions study design - Different levels of formality - Windshield survey powerpoint presentation - Moss bros distribution centre - Difference between imaginative writing and technical writing - Christian bale housing market movie - Halo effect pmp peter principle - Leading change why transformation efforts fail - Calories in a jumbo marshmallow - Discussion - Air canada flight 143 - Anne sexton snow white analysis - Vera bradley competitive advantage - Meaning of dulce et decorum est - Steps in ethical decision making - Diagnostic day unit doncaster royal infirmary - 4 Page APA Report: Explain Continuum of Healthcare Delivery Across Systems and Services - Crossing void talent shuffle rank up - Agarose gel voltage per cm - Management Fundamentals - Special Education interviews - Animal abuse essay conclusion - How do jazz musicians learn improvisation - Chocolate havanese with blue eyes - How to get cengage answers - Ghi hmo with carveout rider - Nelson cursive handwriting scheme - How often were you absent from your previous job - 1 pembrook road wamberal - System analysis and design final project - For prof avril - Ron goldman crime scene - Essay help - Consumer health barrett 9th edition - The boston photographs thesis - Biblical idioms and phrases - In what ways did progressivism include both democratic and anti-democratic impulses? - N4455 professional development plan - Dennis the menace sip and snack napkins - The hate u give literary analysis - ASSESSMENT 3 THEORY AND ITS ROLE IN RESEARCH - Jerry maguire airport scene - Radical candor skip level meetings - The account classification for notes payable is - Personification in jasper jones - Credit suisse research reports - Discussion questions for bridge to terabithia - Preparation of benzoic acid from benzonitrile lab report - Use the given minimum and maximum data entries - Describe the deficiencies in ethical leadership at stacy's firm - Stevenson operations management 13th edition citation - Chiral carboxylic acid with the formula - Technology of the past - Write a policy memo( (2,500-3,000 words) - Acts of the apostles quiz questions and answers - Practical connection assignment 500 WORD ( due in 4 hours MANDATORY ) NO PLAGIARISIM ). - Cisco enterprise agreement benefits - A crate is supported by three cables as shown - Richard hamlin son of catherine hamlin - Writing a paragraph - Case problem specialty toys - Complete the Unix scripts - Computing price elasticity of demand - Nursing - Data driven decision making wgu - Hsbc hk iban number - The color of water - Listening to young children lancaster and broadbent 2003 - Conductivity of strong and weak electrolytes lab report - Asap fresh al tweet mp3 download - Lexicographers concern - Read Leaked Movie Trailer and a Confidentiality Agreement and complete the questions at the end of the case study. - Pd online moreton bay - Probability and statistics homework answers - Discussion 6051 M-4 - +91-8306951337 love marriage specialist astrologer IN Dhanbad