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

Sam pelvic sling indications - Chemistry project on electrochemical cell - Copper and silver nitrate lab answers - Lab safety cartoon worksheet answer key - Chemical formulas pre lab questions - Sunjata a west african epic of the mande peoples pdf - Daphnia magna heart rate lab report - First ionisation energy of aluminium - Hcl dcl lab report - Assignment - Nasm download templates - Fixed and growth mindsets - How to write police report narratives - Eulogy for father in law - Alkaline phosphatase assay lab report - Control restart hra machine - Jumper cables and ohm's law - Golds gym cancellation form - Piper serial number lookup - When was the poem war photographer written - Dobbins the things they carried - How to find trustworthy assignment writing help ? - Native american diorama project ideas - Kingsford smith drive upgrade cost - MBA 599 - DISCUSSION #2 - Benchmark Data collection - Lost Revenue due to failure of implementing Telehealth Services for the company - Celf 4 subtests explained - Don't speak solo tab - City west leisure centre - Osmosis jones questions and answers - Colleges prepare people for life - Describe three of the cobit p09 control objectives - How much time did johnny cash spend in prison - Eucalyptus mulch pros and cons - Four functions of management - Simply supported beam deflection formula - 120 sweetmans road yolla - The iron law of responsibility says that - Heaton and lawson 1996 - Suave usp - East keilor leisure centre prices - I 130 cover letter - Amortisation of leasehold property - HS 2100 Family Dynamics - History extended essay structure - Discussion 3 - Deer hunt catal huyuk - How to reduce employee turnover rate in capsim - Organisational Theory - How to calculate relative change - Week 10 discussion - Td - Math is fun platonic solids - The norton introduction to philosophy 2nd edition - Pelican paper inc and timberland forest - Security Threats - What is a signal phrase in english - Regular expression in automation anywhere - Reflection paper - Information Systems - Lesson 3 CAM discussion - Https youtu be cddwvj_q o8 - Holy cross hospital email - Budgeted manufacturing overhead rate - 2014 3 unit hsc - Summing amplifier lab experiment - Www smithsonianmag com history americas true history of religious tolerance - Writers needed - The drover's wife themes - Computer networks tanenbaum chapter 1 ppt - Frs 8 related party disclosures - Discussion - PM - Table 1: substance vs. starch presence - Acc 202 module 2 assignment - I am the messenger - Complete accounting cycle problem - How to write rationale - Essay Assignment 1: Character Evolution Instructions - The roof at waterhouse - +91-8306951337 get your love back by vashikaran IN Jamnagar - How to stop writing run on sentences - Fluid control research institute - 1600 hours military time - Critical review or analytical review - Arnold split vs ppl - Harvey norman knox westfield - Food inc reflection questions - Voluntas 218 trust overland park ks - Quantitative Evaluation 8381 - Mock research paper - Grammar translation method demonstration - Response - National Practice Problem Exploration - Finance midterm - It system audit checklist - DISCUSSION ON BELOW TOPICS - The poem if by rudyard kipling pdf - Technical Writing in Criminal Justice (3) - Order dulux powder coat samples