Single Dimension Arrays

Similar documents
IV Unit Second Part STRUCTURES

Arrays in C. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Subject: Fundamental of Computer Programming 2068

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

ONE DIMENSIONAL ARRAYS

UNIT-V. Structures. The general syntax of structure is given below: Struct <tagname> { datatype membername1; datatype membername2; };

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Write a C program using arrays and structure

Array. Arrays. Declaring Arrays. Using Arrays

ME 172. Lecture 2. Data Types and Modifier 3/7/2011. variables scanf() printf() Basic data types are. Modifiers. char int float double

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Programming for Engineers Arrays

2. ARRAYS What is an Array? index number subscrip 2. Write array declarations for the following: 3. What is array initialization?

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array?

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Arrays and Pointers (part 1)

Arrays and Pointers (part 1)

Structure, Union. Ashishprajapati29.wordpress.com. 1 What is structure? How to declare a Structure? Explain with Example

EC312 Chapter 4: Arrays and Strings

b. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

3.3 Structures. Department of CSE

Chapter 3: Arrays and More C Functionality

Computers Programming Course 11. Iulian Năstac

Unit 3 Decision making, Looping and Arrays

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

How to declare an array in C?

Module 6: Array in C

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Example: Structure, Union. Syntax. of Structure: struct book { char title[100]; char author[50] ]; float price; }; void main( )

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Array Initialization

Q 1. Attempt any TEN of the following:

C: How to Program. Week /Apr/23

Two Dimensional Arrays

Content. In this chapter, you will learn:

C Program Development and Debugging under Unix SEEM 3460

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

LOOPS. 1- Write a program that prompts user to enter an integer N and determines and prints the sum of cubes from 5 to N (i.e. sum of 5 3 to N 3 ).

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Arrays and Strings. Arash Rafiey. September 12, 2017

Arrays. C Types. Derived. Function Array Pointer Structure Union Enumerated. EE 1910 Winter 2017/18

Essar Placement Paper

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

POINTERS, STRUCTURES AND INTRODUCTION TO DATA STRUCTURES

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA.

Object Oriented Pragramming (22316)

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Multi-Dimensional arrays

Intermediate Programming, Spring 2017*

C programming Lecture 2. Marina Krstic Marinkovic School of Mathematics Trinity College Dublin

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

Arrays, Pointers and Memory Management

AMCAT Automata Coding Sample Questions And Answers

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

CSCI 171 Chapter Outlines

211: Computer Architecture Summer 2016

Strings. Part III. 1) Introduction. 2) Definition. 3) Using Strings. 4) Input/Output. 5) Using string.h Library. 6) Strings as Function Parameters

C for Engineers and Scientists: An Interpretive Approach. Chapter 10: Arrays

Government Polytechnic Muzaffarpur.

Procedural Programming

Computers Programming Course 10. Iulian Năstac

Computer Science & Engineering 150A Problem Solving Using Computers

Introduction to Scientific Computing and Problem Solving

Pointers and Arrays 1

Should you know scanf and printf?

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Unit IV & V Previous Papers 1 mark Answers

BİL200 TUTORIAL-EXERCISES Objective:

PDS Class Test 2. Room Sections No of students

Arrays in C. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur. Basic Concept

SAE1A Programming in C. Unit : I - V

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

Tribhuvan University Institute of Science and Technology 2065

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Problem Solving and 'C' Programming

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Arrays. Arrays are of 3 types One dimensional array Two dimensional array Multidimensional array

Review of Important Topics in CS1600. Functions Arrays C-strings

CSE101-Lec#18. Multidimensional Arrays Application of arrays. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Guide for The C Programming Language Chapter 4


PROGRAMMAZIONE I A.A. 2017/2018

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

ESC101N: Fundamentals of Computing End-sem st semester

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations

Transcription:

ARRAYS

Single Dimension Arrays

Array Notion of an array Homogeneous collection of variables of same type. Group of consecutive memory locations. Linear and indexed data structure. To refer to an element, specify Array name Position number ( Index )

Array Format Elements of an array can be integers, floats, characters etc. All the elements share a common name with an index called subscript. In an array of n elements: [0] [1] [2] [3] [n-1]

One example: Arrays - Why? Employees salaries in a company. Each salary is a float. All the salaries could be stored as an array of floats. Can then do things like: Change an employee s salary Find out an employee s salary Get the total salary bill and do it more easily than representing each salary as a single float (convenience of representation)

Arrays - Why? - Another Example main() { float sal1,sal2,sal3; } scanf ( %f,&sal1); scanf ( %f,&sal2); scanf ( %f,&sal3); main() { int sal[3], i=0; while (i < 3) { scanf ( %f,&sal[i]; } } Imagine having 100 variables...

Memory Layout

Declaration When declaring arrays, specify Data type of array ( integers, floats, characters..) Name of the array. Size: number of elements array_type array_name[ size ] ; Example: o int student[ 10 ] ; o float my_array [ 300 ] ;

Example For example, int x [ 4 ] ; Square bracket memory addresses 1004 An array of integers of 4 elements. Note that the starting memory address is determined by the operating system (just like that of simple variable). Contiguous memory locations are allocated. 1006 1008 1010 1012 1014 1016 1018 (x[0]) (x[1]) (x[2]) (x[3])

Examples Integer array of 20 elements: int array_1 [ 20 ]; Character array of 50 elements: char array_2 [ 50 ]; Float array of 100 elements: float array_3 [ 100 ];

sizeof() The amount of storage required to hold an array is directly related to its data type and the size. Example Total size in bytes for a 1 D array: total bytes = sizeof( data type) * size of array int a [ 7 ] ; total_bytes = 2 * 7 = 14 bytes in memory

Exercise int main( ) { float f1[10] ; char c1[10] ; printf( %d, sizeof(f1)); printf( %d, sizeof(c1)); return(0); } Output: 40 10

Example 1 Write a program to read 10 integers from the user and display them. int main( void) { int digit[ 10 ], t ; printf( \n Enter the value of 10 integers ) ; / * for reading 10 integers from the user using scanf * / for( t = 0, t < 10 ; t + + ) scanf( %d, &digit [ t ] ); /* for displaying the integers using printf */ for( t = 0, t < 10 ; t + + ) printf( %d, digit [ t ] ); Return(0);}

Exercise 1 In an organization 100 employee are there. Write a program to store the employee id and salary of all the employees. Then input the employee id, and display the salary of the employee.

Solution Steps Declare two arrays int emp_id[100] and float emp_sal[100] Emp_id emp_sal Input the value of both the arrays from the user. Input the emp_id for which salary is to be displayed. Search the above id in array emp_id[ ] and get the index if match found In the second array display the salary for the same index. 0 1 2. 100 0 1 2. 100

Solution #include<stdio.h> main() { int a[100],b[100],id,i; printf( eneter values"); for(i=0;i<=99;i++) { scanf("%d",&a[i]); scanf("%d",&b[i]); } printf("enter emp id"); scanf("%d",&id); printf("%d%d",a[id],b[id]); }

Exercise 2 Write a program to read 10 integers and add 5 to odd elements and 10 to even elements.

ARRAY Example Grade lists Sporting event times/scores Telephone numbers Voting tallies Digitized images

Initializing arrays Array elements must be initialized at time of declaration, otherwise they may contain garbage values Initialization can be done either at compile time or run time

Compile Time Initialization Initialize elements of array in same way as any other ordinary variables at time of declaration int number[3] = {0,0,0}; Float total[5] = {0.0,15.75,10.34}; // first three elements of array will be initialized; rest two will be initialized to 0. // if initializer list exceeds size of array, it will produce compiler error

int digits [ 10 ] = { 3, 30, 300} ; It will initialize only first three elements of array All individual array elements that are not assigned explicit initial values will automatically be set to zero. digits [ 0 ] = 3 digits [ 1 ] = 30 digits [ 2 ]= 300 digits [ 3 ] = 0 digits [ 4 ]= 0 digits[ 5 ]= 0 digits [ 7 ] = 0 digits [ 8 ] =0 digits [ 9 ] =0

Initializing Integer arrays Another way of initializing the elements of the array is as follows: o int array [ ] = { 2, 20, -30, 10, 100 } ; The array size need not be specified explicitly when initial values are included as a part of array declaration. Array size will automatically be set equal to the number of initial values specified with in definition.

Initializing Arrays The second way is to Initialize each array element separately id[0]=1234; id[2]=2883; id[3]=2322; id[4]=8888; id[5]=8237;

Run time initialization Explicitly initializing an array at run time Normally used for large array size Example: for(i=0; i<100; i++) { if(i<50) sum[i] = 0; else sum[i] = 1; }

Basics of character array If you are required to store a group of character like your name, city, or your college name, or any word or text you need to define a array of characters. A char variable can hold a SINGLE character only like char c = A ; char c1= B ; What if you need to store Sachin Tendulkar or MUMBAI a string.

Character Arrays To hold a single string you need to declare a single dimension character array o char str [ 11 ] ; When declaring a character array to hold a string( group of characters), one need to declare the array to be one character longer than the largest string that it will hold Example above array str[ 11 ] will hold 10 characters and a NULL character ( \0 ) at the end

How To Enter value? /* program to read user s name and display it */ int main( ) { char str [10 ] ; printf( Enter your name ); scanf( %s, str); printf( Your name is : %s, str); No need to put & return 0; }

In case of character arrays Name of the array is the starting address of the array char str[10]; &str [ 0 ] => str

Disadvantage of %s While reading a string using %s format specifier, it does not scan the string after the space bar. For example Schin Tendulkar It will scan only Sachin. It will IGNORE any space or tab space How to scan a complete text of words?

gets( ) gets( argument string) : Collects a string of characters terminated by new line character \n from the standard input stream ( stdin ). It allows to input spaces, tabs and copies all the character till new line into the argument string and append a NULL character \0 at the end of it. For example char str [ 20 ] ; gets( str ) ;

puts( ) puts( argument string ): It displays the string of characters from argument string to standard output till NULL character and appends a new line character at the end. For example puts ( str ) ;

EXAMPLE: Input ten numbers into an array, using values of 0 to 99, and print out all numbers except for the largest number.. /* to accept 10 values in the range 0 to 99 */ int size=10; int value[size], i; for (i=0; i< size; ++i) { scanf ( %d,&value[i]); } if (value[i] > 99 value[i] <0) { printf ( enter only values within 0-99 ); i--; }

/* to find the greatest among the list */ int maximum= 0; for (i=0; i< size; i++) { if (maximum < value[i] ) maximum = value[i]; }

/* to print all the values other than the greatest */ for (i=0; i< size; i++) { if (value[i]!= maximum ) printf ( %d, value[i]; }

Home Assignment Write a program to read a text from console and display the number of words and lines in the text.