Week 8 Arrays Part 2 String & Pointer

Slides:



Advertisements
Similar presentations
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 16P. 1Winter Quarter Strings Lecture 16.
Advertisements

Programming and Data Structure
Structures Spring 2013Programming and Data Structure1.
Single Variable and a Lot of Variables The declaration int k; float f; reserve one single integer variable called k and one single floating point variable.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
ECE Application Programming Instructor: Dr. Michael Geiger Spring 2012 Lecture 31: PE5.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
By Senem Kumova Metin 1 POINTERS + ARRAYS + STRINGS REVIEW.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
Topic 9A – Arrays as Function Arguments. CISC105 – Topic 9A Arrays as Function Arguments There are two ways to use arrays as function arguments: Use an.
Introduction to Computers and Programming Class 22 Character Arrays (Strings) Professor Avi Rosenfeld.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring Arrays 6.4Examples Using Arrays 6.5Passing.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Multiple-Subscripted Array
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 9: Pass-by-Value.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Introduction to Arrays CSC 1401: Introduction to Programming with Java Week 10 – Lecture 1 Wanda M. Kunkle.
Week 7 – String. Outline Passing Array to Function Print the Array How Arrays are passed in a function call Introduction to Strings String Type Character.
- SEARCHING - SORTING.  Given:  The array  The search target: the array element value we are looking for  Algorithm:  Start with the initial array.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
EPSII 59:006 Spring Introduction Fundamentals of Strings and Characters Character Handling Library String Conversion Functions Standard Input/Output.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
C Static Arrays Pepper. What is an array? Memory locations – same type – next to each other (contiguous) – Same name – Indexed by position number of type.
UniMAP Sem2-08/09 DKT121: Fundamental of Computer Programming1 Introduction to C – Part 2.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
+ ARRAYS - SEARCHING - SORTING Dr. Soha S. Zaghloul updated by Rasha M. AL_Eidan 2015.
“In mathematics and computer programming, Index notation is used to specify the elements of an array of numbers”
C Lecture Notes 1 Arrays Lecture 6. C Lecture Notes 2 6.1Introduction Arrays –Structures of related data items –Static entity – same size throughout program.
1 Structures UniMAP SEM I - 11/12EKT 120 Computer Programming.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
UniMAP SEM I - 10/11EKT 120 Computer Programming1 Lecture 8 – Arrays (2) and Strings.
Cop3530sp12. Parameter passing call by value- appropriate for small objects that should not be altered by the function call by constant reference- appropriate.
1. Pointers –Powerful, but difficult to master –Simulate pass-by-reference –Close relationship with arrays and strings 2.
Pointer Lecture 2 Course Name: High Level Programming Language Year : 2010.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Unit 6 Data Types and Arrays. Key Concepts Explicit and automatic conversion ASCII Enumerated types Function parameters Arrays Loops and arrays Passing.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
EC-111 Algorithms & Computing Lecture #9 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Pointers Call-by-Reference.
Methods. Creating your own methods Java allows you to create custom methods inside its main body. public class Test { // insert your own methods right.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Prepared by Andrew Jung. Accessing Pointer Data Pointer can be used to access the contents of an array Look at the following syntax: /* Declaration and.
Pointers Pointers are variables that contain memory addresses as their values. A variable directly contains a specific value. A pointer contains an address.
Test 2 Review Outline.
Introduction to Programming Using C
Tutorial 8 Pointers and Strings
CS 1430: Programming in C++.
Vectors.
EKT150 : Computer Programming
Pointers Kingdom of Saudi Arabia
Topics discussed in this section:
CS250 Introduction to Computer Science II
Presentation transcript:

Week 8 Arrays Part 2 String & Pointer Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming Outline Passing Array to Function Print the Array How Arrays are passed in a function call Introduction to Strings String Type Character Array Declaration of Strings Fundamentals of Strings & Characters Initialization of Strings Assigning Values to Strings Calculation of String Size String Conversion Functions Comparison Functions of the Strings ASCII Table Sem1-06/07 EKT120: Computer Programming

Passing Array to Function void initialize (int list [ ]) { int count; for (count = 0; count < 5; count ++) list [count] = 0; } passing array list [ ] to function Initialize all element inside array list[ ] to 0 i.e: list [0]=0; . list [4]=0 Sem1-06/07 EKT120: Computer Programming

Array as Parameters to Function If size changes (lets say 10 or 20), need to write another function. Introduce another variable, size without need to write another function. void initialize (int list [ ], int size) { int count; for (count = 0; count < size; count ++) list [count] = 0; } Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming Constant Arrays Prevent the function from changing the values in array. Use word const in declaration. Function can modify array x but not array y. void example (int x[ ], const int y[ ], int sizeX[ ], int sizeY[]) { ….. …. } Sem1-06/07 EKT120: Computer Programming

Initialize all elements inside array x[ ] to 0 Initialize an array to 0 void initializeArray (int x [ ], int sizeX) { int counter; for (counter = 0; counter < sizeX; counter ++) x [counter] = 0; } Initialize all elements inside array x[ ] to 0 i.e: x[0]=0,x[1]=0…….x[sizeX-1] Sem1-06/07 EKT120: Computer Programming

Read data and store it in an array void fillArray (int x [ ], int sizeX) { int counter; for (counter = 0; counter < sizeX; counter ++) scanf (“%d”, &x[counter]); } Store Read Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming Print the Array void printArray (const int x [ ], int sizeX) { int counter; for (counter = 0; counter < sizeX; counter ++) printf (“%d”, x [counter]); } Sem1-06/07 EKT120: Computer Programming

Find & return the sum of an array int sumArray (const int x [ ], int sizeX) { int counter; int sum = 0; for (counter = 0; counter < sizeX; counter ++) sum = sum + x [counter]; return sum; } Constant array int x[ ] with sizeX having element from 0 to (sizeX – 1) passed to sumArray function. Sum all elements in array x[ ] with size of sizeX x[0] + x[1] + ………x[sizeX - 1] Sem1-06/07 EKT120: Computer Programming

Find & return Index of largest element of an array int indexLargestElement (const int x [ ], int sizeX) { int counter; int maxIndex = 0; for (counter = 0; counter < sizeX; counter ++) if ( x[maxIndex] < x[counter] ) maxIndex = counter; // copy counter to maxIndex return maxIndex; } Program to find the index of the largest element. Test each element in array x[ ] x[counter]  test each index starts from 0 to (sizeX – 1) Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming Let sizeX = 3 x[sizeX] = x[3]={2,6,3} x[0]=2,x[1]=6,x[2]=3 Test each element to find the index of largest element. x[counter] = x[0]>maxIndex, 2>0 maxIndex=counter maxIndex=0, repeat until counter = 2. x[counter]=x[1]>2, 6>2 maxIndex=counter maxIndex=1, repeat until counter = 2. x[counter]=x[2]>6, but 3<6 maxIndex=counter maxIndex=1, counter = 2. exit for loop return maxIndex=1. x 2 6 3 x[0] x[1] x[2] Sem1-06/07 EKT120: Computer Programming

Copy One Array Into Another Array void copyArray (const int x [ ], int y [ ], int length) { int counter; for (counter = 0; counter < length; counter ++) y [counter] = x [counter]; } Length = size of array x[ ], array x[ ] is a constant array y [counter] = x [counter]; // copy each element between arrays Sem1-06/07 EKT120: Computer Programming

How Arrays are passed in a function call #include <stdio.h> const int arraySize = 10; void initializeArray (int x [], int sizeX); void fillArray (int x [], int sizeX); void printArray (const int x [], int sizeX); int sumArray (const int x [], int sizeX); int indexLargestElement (const int x [], int sizeX); void copyArray (const int x [], int y [], int length); Sem1-06/07 EKT120: Computer Programming

How Arrays are passed in a function call int main() { int listA [arraySize] = {0}; int listB [arraySize]; printArray (listA, arraySize); initializeArray (listB, arraySize); printArray (listB, arraySize); fillArray (listA, arraySize); sumArray (listA, arraySize); copyArray (listA, listB, arraySize); return 0; } Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming Sample Program #include <stdio.h> void printArray( const int a[][3]); // function prototype //function main begins program execution int main() { //initialize array1, array2, array3 int array1 [2][3] = { {1, 2, 3}, {4, 5, 6} }; int array2 [2][3] = { 1, 2, 3, 4, 5 }; int array3 [2][3] = { {1, 2 }, { 4 } }; printf (“Values in array1 by row are : \n); printArray (array1); printf ("Values in array2 by row are : \n"); printArray (array2); printf ("Values in array3 by row are : \n"); printArray (array3); return 0; } // end of main Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming Sample Program (cont…) Function To Output Array With Two Rows And Three Columns void printArray (const int a[][3]) { int i; //row counter int j; //column counter //loop through row for (i = 0; i <= 1; i++) //output column values for (j = 0; j <= 2; j++) printf ("%d ", a[i][j]); } // end inner for printf ("\n"); // start new line of output } // end outer for } // end function printArray Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming Output Values in array1 by row are : 1 2 3 4 5 6 Values in array2 by row are : 4 5 0 Values in array3 by row are : 1 2 0 4 0 0 Compare with the following………. int array1 [2][3] = { {1, 2, 3}, {4, 5, 6} }; int array2 [2][3] = { 1, 2, 3, 4, 5 }; int array3 [2][3] = { {1, 2 }, { 4 } }; Sem1-06/07 EKT120: Computer Programming

Details…………review lecture W7 string Re-Cap from previous lecture….. Previous….array that contain numerical values in each array element. String….array that contain a single char in each element including the last element of these arrays is the null character (\0). String….arrays of characters Numerical array works element by element More convenient work with strings by using the address of the first element of string (advantage of pointer).   pointer becomes very important. Details…………review lecture W7 string Sem1-06/07 EKT120: Computer Programming

Assigning values to string The left hand side value of an assignation can only be array items and not the entire array, the probable way to assign a string of characters to an array of char can be shown as: newstring[0] = ‘W’; newstring[1] = ‘e’; newstring[2] = ‘l’; newstring[3] = ‘c’; newstring[4] = ‘o’; newstring[5] = ‘m’; newstring[6] = ‘e’; newstring[7] = ‘\0’; Sem1-06/07 EKT120: Computer Programming

Calculation of string size What are the result? char is 1 byte, the total number of alphabets plus a null would be the size of the string. Example program: #include <stdio.h> #include <string.h> char newstring[] = {'W','e','l','c','o','m','e','\0'}; char mystring[] = "Good Bye"; int main() { printf ("Size of newstring is %d", sizeof (newstring)); //size of string Welcome printf ("\nSize of mystring is %d", sizeof (mystring));// size of string Good Bye return 0; } Sem1-06/07 EKT120: Computer Programming

Character & String manipulation Eg: a program may need to verify that an ID number of first year students starts with ’04’. Determine whether last three characters in a part number are valid. Built-in functions available – makes it easier. Sem1-06/07 EKT120: Computer Programming

Controlling the Case of a Character ‘K’ is not equal to ‘k’. Previously use: if (choice == ‘K’ || choice == ‘k’) while (choice == ‘K’ || choice == ‘k’) Can use a function that temporarily converts the letter to uppercase or lowercase before comparing it. strupr(charVariable) strlwr(charVariable) Sem1-06/07 EKT120: Computer Programming

Controlling the Case of a Character Example strupr char repeat; printf ( “Continue? (Y or N) : “); scanf (“%c”, &repeat); while (strupr(repeat) == ‘Y’) { ….. } While loop performed even though the ‘y’ is entered. Function strupr temporarily converts the letter to uppercase Sem1-06/07 EKT120: Computer Programming

Controlling the Case of a Character Example of strupr char name[]; printf (“Enter a name : “); scanf (“%s”, name); strupr( name ); printf("The name in uppercase is %s", name ); Function strupr temporarily converts the letter to uppercase even though user keyed lowercase. Sem1-06/07 EKT120: Computer Programming

Sample Program To convert a string to uppercase #include <stdio.h> #include <string.h> void main() { char name[80]; /* declare an array of characters 0-79 */ printf("Enter in a name in lowercase\n"); scanf( "%s", name ); strupr( name ); // converts to uppercase printf("The name in uppercase is %s", name ); } Output Enter in a name in lowercase ahmad The name in uppercase is AHMAD Sem1-06/07 EKT120: Computer Programming

Controlling the Case of a Character Real value does not changed. The functions only affect characters of letters or alphabet. Doesn’t affect numbers and special characters such as $ and %. If the character of already lowercase or uppercase, the function will not affect the real value. It will return the original value. char repeat = ‘Y’; letter = strupr(repeat); Letter = ?........affected or not? Sem1-06/07 EKT120: Computer Programming

String Conversion Functions In <stdlib.h> (general utilities library) Convert strings of digits to integer and floating-point values Sem1-06/07 EKT120: Computer Programming

Comparison Functions of the String Comparing strings Computer compares numeric ASCII codes of characters in string int strcmp( const char *s1, const char *s2 ); Compares string s1 to s2 Returns a negative number if s1 < s2, zero if s1 == s2 or a positive number if s1 > s2 int strncmp( const char *s1, const char *s2, size_t n ); Compares up to n characters of string s1 to s2 Returns values as above Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming ASCII Table ASCII Character Set 1 2 3 4 5 6 7 8 9 nul soh stx etx eot enq ack bel bs ht If vt ff cr so si dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us sp ! “ # $ % & ` ( ) * + , - . / : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ’ a b 10 d e f g h i j k l 11 n o p q r s t v 12 x y z { | } ~ del Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming Sample program 1 #include <stdio.h> #include <string.h> int main() { char string1[ 20 ], string2[ 20 ]; //declaration of string1 and string2 int result; printf( "Enter two strings: " ); scanf( "%s%s", string1, string2 ); result = strcmp( string1, string2 ); // compare between string1 and string2 if ( result > 0 ) printf( "\"%s\" is greater than \"%s\"\n", string1, string2 ); else if ( result == 0 ) printf( "\"%s\" is equal to \"%s\"\n", string1, string2 ); else printf( "\"%s\" is less than \"%s\"\n", string1, string2 ); return 0; } Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming Output Enter two strings: computer programming "computer" is less than "programming" Enter two strings: programming computer "programming" is greater than "computer" Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming Sample program 2 #include <stdio.h> #include <string.h> int main() { char string1[ 20 ], string2[ 20 ]; int result, compareCount; printf( "Enter two strings: " ); scanf( "%s%s", string1, string2 ); printf( "How many characters should be compared: " ); scanf( "%d", &compareCount ); result = strncmp( string1, string2, compareCount ); if ( result > 0 ) printf( "\"%s\" is greater than \"%s\" up to %d characters\n", string1, string2, compareCount ); else if ( result == 0 ) printf( "\"%s\" is equal to \"%s\" up to %d characters\n", else printf( "\"%s\" is less than \"%s\" up to %d characters\n", return 0; } Sem1-06/07 EKT120: Computer Programming

EKT120: Computer Programming Output Enter two strings: computer programming How many characters should be compared: 7 "computer" is less than "programming" up to 7 characters Enter two strings: programming computer "programming" is greater than "computer" up to 7 characters Sem1-06/07 EKT120: Computer Programming

Built in Functions for String Handling strcat Appends a string strchr Finds first occurrence of a given character strcmp Compares two strings strcmpi Compares two strings, non-case sensitive strcpy Copies one string to another strlen Finds length of a string strlwr Converts a string to lowercase strnca t Appends n characters of string strncmp Compares n characters of two strings strncpy Copies n characters of one string to another strnset Sets n characters of string to a given character strrchr Finds last occurrence of given character in string strrev Reverses string strset Sets all characters of string to a given character strspn Finds first substring from given character set in string strupr Converts string to uppercase Sem1-06/07 EKT120: Computer Programming