# 5 Arrays and Pointers

Save this PDF as:

Size: px
Start display at page:

## Transcription

1 5 Arrays and Pointers 5.1 One-dimensional arrays Arrays offer a convenient way to store and access blocks of data. Think of arrays as a sequential list that offers indexed access. For example, a list of quiz scores of this C programming course with 110 students may be stored in a C array. The idea is that instead of having 110 different identifiers, one for each student, we can use a single identifier for the entire class: the array grade[]. A particular user s score could be accessed by a C program using the construction: grade [ index ] where index would be an integer, in this case in the interval [0, 109]. Note that the first student would be accessed using the index 0 and the 110 th student by the index 109! A one-dimensional array in C is therefore a list of variables that are all of the same type and are referenced through a common name. An individual variable in the array is called an array element. An one-dimensional array is declared using the syntax: type variable name [ size ] ; where size is an integer. One may also declare a variable to be an array with no storage allocated at declaration time. We will study those later. For example, int my array [ 5 0 ] ; double velocity [ ] ; declares an array of integers my_array with room for 50 elements and an array of doubles velocity with room for 100 elements. We repeat one more time that that, in C, array subscripts start at zero, so that the valid following are valid elements of the above declared array are my array [ 0 ], my array [ 1 ],..., my array [49] velocity [ 0 ], velocity [ 1 ],..., velocity [99] Note also that C makes no attempt to verify the validity of the indexed element in an array so the burden is all on the programmer to make sure his or her code does not access an invalid memory address. MAE 9 60 Maurício de Oliveira

2 The following example populates an array of integer then prints its elements using for loops: / Program w5 1. c / / This is a simple example with an integer array / main () { / declare array / int array [10], i ; / populate array / for ( i = 0; i < 10; i++) array [ i ] = 1 + i i ; / print array / for ( i = 0; i < 10;) printf ("%d ", array [ i ++]); / print 6th element / printf ("\nsixth element is %d\n", array [ 5 ] ) ; The output is as follows sixth element i s 26 In order to initialize arrays we use the syntax: type array name [ size ] = { value list ; Here are some examples: int i [ 5 ] = {1, 4, 9, 16, 30; char a [ 3 ] = { A, B, C ; double d [ ] = {1., 3., ; Note that the last initialization is performed without declaring the size of the array. The compiler will make sure enough space is allocated for the array, in this case, 3 elements. The initialization list may be smaller but not larger than the declared array size, if one is present in the declaration. Arrays are typically used in programs as fixed-size lists where one stores data. Entities typically found in scientific programing are also represented as arrays, MAE 9 61 Maurício de Oliveira

3 such as vectors and matrices. The following program computes the distance, the inner product and angle between two three dimensional vectors: / Program w5 2. c / / This programs computes the distance, the inner product and angle between two 3 dimensional vectors / #include <math. h> main () { / declare variables / int i ; double x [ 3 ] = {1., 3., 2.; double y [ 3 ] = {5., 0,. 2 ; double tmp; double norm x, norm y, distance, inner product, angle ; / compute distance and inner product / distance = inner product = norm x = norm x = 0. ; for ( i = 0; i < 3; i++) { / compute difference / tmp = x [ i ] y [ i ] ; / compute squared norm of the difference / distance += tmp tmp; / compute squared norm of x and y / norm x += x [ i ] x [ i ] ; norm y += y [ i ] y [ i ] ; / compute inner product <x, y> / inner product += x [ i ] y [ i ] ; / compute square roots of the norms / norm x = sqrt (norm x ) ; norm y = sqrt (norm y ) ; distance = sqrt ( distance ) ; / compute a ngle / angle = acos ( inner product / (norm x norm y ) ) ; MAE 9 62 Maurício de Oliveira

4 / print distance, inner product and angle / printf ("Distance = %2f\n", distance ) ; printf ("Inner product = %2f\n", inner product ) ; printf ("Angle = %2f degrees\n", angle 180 / M PI ) ; Recall that the Euclidean norm, the standard inner product and angle between two 3-dimensional vectors is given by the formulas: x = 3 3 x 2 i, x, y = x, y x i y i, x, y = arccos x y. i=1 i=1 5.2 Pointers A pointer is a variable that holds the memory address of another object. If a variable called p contains the address of another variable called q, then p is said to point to q. As we will see in this section, understanding pointers is fundamental to understanding arrays in C. In order to declare a pointer variable precede it by the * operator as in type variable name ; For example: int p ; double q1, q2 ; void v ; declare a pointer to an integer variable (p), two pointers to double variables (q1 and q2) and one pointer without a specific type (v). When declared uninitialized, pointers do not hold valid memory addresses. In order to assign the address of one existing variable to a pointer, use the operator address-of (&). Recall that & returns the address of the variable it precedes. This can be done at the pointer declaration or anywhere in your program through assignment. For example: int q ; int p1 ; / p1 is a pointer not i n i t i a l i z e d / int p2 = &q ; / p2 is a pointer holding the address of q / p1 = &q ; / now p1 also holds the address of q / MAE 9 63 Maurício de Oliveira

5 In order to access the memory address held by a pointer we use the dereference or indirection operator (*). The operator * returns the value stored at the pointer it precedes as well as serves as a proxy for the contents of that memory address during assignment operations. This is illustrated in the next simple program: / Program w8 6. c / main () { / declare variable and pointer / double q, r, p = &q ; / assign value to variables / q = 1.34; r = 6.78; / print variable, pointer and contents of pointer / printf (" value of q = %f\n", q ) ; printf ("address of q = %p\n", &q ) ; printf (" value of r = %f\n", r ) ; printf ("address of r = %p\n", &r ) ; printf (" value of p = %p\n", p ) ; printf ("address of p = %p\n", &p ) ; printf (" value of *p = %f\n", p ) ; / change variable value / q = 7.89; / print variable, pointer and contents of pointer / printf ("\n value of q = %f\n", q ) ; printf ("address of q = %p\n", &q ) ; printf (" value of r = %f\n", r ) ; printf ("address of r = %p\n", &r ) ; printf (" value of p = %p\n", p ) ; printf ("address of p = %p\n", &p ) ; printf (" value of *p = %f\n", p ) ; / change variable value through pointer / p = 12.86; / print variable, pointer and contents of pointer / printf ("\n value of q = %f\n", q ) ; printf ("address of q = %p\n", &q ) ; printf (" value of r = %f\n", r ) ; MAE 9 64 Maurício de Oliveira

6 printf ("address of r = %p\n", &r ) ; printf (" value of p = %p\n", p ) ; printf ("address of p = %p\n", &p ) ; printf (" value of *p = %f\n", p ) ; / change value of pointer and variable r / p = &r ; r = 5.69; / print variable, pointer and contents of pointer / printf ("\n value of q = %f\n", q ) ; printf ("address of q = %p\n", &q ) ; printf (" value of r = %f\n", r ) ; printf ("address of r = %p\n", &r ) ; printf (" value of p = %p\n", p ) ; printf ("address of p = %p\n", &p ) ; printf (" value of *p = %f\n", p ) ; A common mistake is to dereference a pointer when assigning it a value. The following two constructions are equivalent: and int p ; p = &q ; int p = &q ; whereas int p ; p = &q ; has a different meaning, usually incorrect. The arithmetic operators +, ++, -, and -- may be applied to pointer variables. Since pointer variables contain memory addresses you may add or subtract only integer quantities. For example, double x ;... x += 2;... Note that the precedence and binding of * is higher than all arithmetic operators but not higher than ++, hence *p++ increments p not *p, whereas *p+3 adds 3 to *p. MAE 9 65 Maurício de Oliveira

7 When doing pointer arithmetic, it is sometimes important to know the size of each variable type in bytes. This can vary with the hardware so C provide the keyword sizeof that returns the size in bytes of the type or variable that follows it in your current hardware. For example: sizeof ( int ) ; sizeof ( float ) ; sizeof ( double ) ; One often needs to use sizeof when using void pointers. At the end of this excerpt both pointers contain the exact same address: double l [ 1 0 ] ; double x = &l ; void v = ( void ) &l ; x += 2; v += 2 sizeof ( double ) ; In particular, they both point to the second element of the list l. Note the type cast from (double *) to (void *). 5.3 Relation between pointers and arrays In C, pointers and arrays are closely related and often interchangeable. When an array name is used without an index, a pointer to the start of the array is generated. Any operation that can be achieved by array indexing can also be done with pointers. The pointer version is ofter harder to read though. For example, the declaration: int a [ 1 0 ] ; defines an array a of size 10. The following statements are equivalent: int p1, p2 ; p1 = a ; p2 = &a [ 0 ] ; in that both p1 and p2 point to the first element of the array a. Indeed, a itself is a pointer and we can use equivalently pointer arithmetic or array indexing in order to access an element of an array. For example: int p1, p2 ; p1 = a + 3; p2 = &a [ 2 ] ; MAE 9 66 Maurício de Oliveira

8 will have p1 pointing to the fourth element of a and p2 pointing to the third element of a. We can also assign values to the array elements by dereferencing the pointer a as in: a = 2; (a + 1) = a ; (a + 2) = 4; which will set the first element of a to 2, then copy this value to the second element in the second statement. Finally we set the third element of the array to 4. Here is an example where an integer array is manipulated through pointers: / Program w5 1a. c / / This is an example with an integer array using pointer arithmetic / main () { / declare array / int array [10], i ; / declare pointer / int p ; / populate array / for (p = array, i = 0; i < 10; i++) (p + i ) = i + 1; / print array / for ( i = 0; i < 10; ) printf ("%d ", ( array + i ++)); printf ("\n" ) ; / populate array / for ( i = 10, p = array ; p < array + 10; p++ = i ); / print array / for (p = array ; p < array + 10; ) printf ("%d ", p++); printf ("\n" ) ; Note the subtleties of incrementing pointers while dereferencing. MAE 9 67 Maurício de Oliveira

9 5.4 Character arrays and C-strings C does not have a native character string type. Instead, all string manipulation is done through one-dimensional character arrays. The main difference is that most string functions will accept a character array as a string without needing to know its length. Instead, the end of a character string is signaled by the presence of a special character, the end-of-string character ( \0 ) which is simply a character with the decimal value 0. Such character arrays are called null-terminated strings. Note that one still has to allocate enough memory space when declaring character arrays regardless of where the end-of-string character is located. For example: char str1 [ 8 0 ] ; / Reserves 80 characters for str1 / char str2 [80] = { H, e, l, l, o,, w, o, r, l, d,! ; / Reserves 80 characters for str2 and i n i t i a l i z e s i ts contents ; Does not add end of string / char str3 [ ] = { H, e, l, l, o,, w, o, r, l, d,! ; / Reserves 12 characters for str3 and i n i t i a l i z e s i ts contents ; Does not add end of string / char str4 [80] = "Hello world!" ; / Reserves 80 characters for str4 and i n i t i a l i z e s i ts contents ; Adds end of string / char str5 [ ] = "Hello world!" ; / Reserves 13 characters for str4 and i n i t i a l i z e s i ts contents ; Adds end of string / Note that str5 is a 13 character array rather than a 12 character array because one extra character is allocated and initialized as the end of string character. This is a feature of str2 being initialized as a character string using double quotes ("). In contrast, str2 and str3 are initialized as character arrays, and therefore their constructor behaves as a standard array constructor. Note also that str2 and str3 will not work properly on most C-string functions that expect an end-of-string character. C provides several functions for reading character strings from the terminal, such as gets and scanf with the %s modifier. THEY ARE ALL UNSAFE AND SHOULD NOT BE USED! The reason why they are unsafe is because MAE 9 68 Maurício de Oliveira

10 they do not let the user specify the maximum number of characters in the user character array and this can and have been extensively exploited by malicious software. One should only use functions that allow explicit control of the maximum size of the input to the read. One such function is fgets. The following is an example: / Program w5 5. c / / Uses a character array to process a string. / #include <s t r i n g. h> main () { char str [ 8 1 ] ; int size ; printf ("Enter a string:\n" ) ; fgets ( str, 81, stdin ) ; printf ("You entered: %s \n", str ) ; size = strlen ( str ) ; printf ("Length of string is %d\n", size ) ; The meaning of stdin in fgets will be clear when we study files. A couple of details on using fgets: the newline character \n is part of the string; the function fgets returns a pointer to the string read; if none than it returns the null pointer NULL. This can be used to terminate terminal input. Note that we added the header <string.h> so as to access the library function strlen to compute the length of the string; this is part of the standard C library so there is no need to add any -l flag at compilation. Note also the use of the modifier %s with printf which is used to print a null-terminated string. The next improved version of the previous code takes care of those issues: / Program w5 5a. c / / Uses a character array to process a string ( better version ). / #include <s t r i n g. h> MAE 9 69 Maurício de Oliveira

11 main () { const int BUFFER SIZE = ; char str [BUFFER SIZE ] ; int size ; printf ("Enter a string:\n" ) ; / loop until useful string is input / while ( fgets ( str, BUFFER SIZE, stdin ) ) { size = strlen ( str ) ; / remove \n / i f ( str [ size 1] == \n ) / terminate string one character ahead / str [ size 1] = \0 ; i f ( size > 0 ) { printf ("You entered: %s \n", str ) ; printf ("Length of string is %d\n", size ) ; break ; else printf ("Enter a string:\n" ) ; After one hits <ENTER> we first remove the trailing \n and decrement the size of the string. If the length of str is 0, the loop will keep prompting you to enter a non-empty string. 5.5 Multi-dimensional arrays C allows the definition of multidimensional arrays using the following syntax: type variable name [ size1 ] [ size2 ]... [ sizem ] ; For example, to create a two-dimensional integer array called count, i.e. with 10 rows and 12 columns, the declaration is int count [ 1 0 ] [ 1 2 ] ; In science and engineering analysis, we often deal with matrices. Even though matrices can be thought as the quintessential two dimensional array, using a two-dimensional array to represent matrices is often a bad choice and may lead MAE 9 70 Maurício de Oliveira

12 to poor performance in today s hardware. Virtually all high-performance computation done with matrices adopts a flat one-dimensional representation for matrices. We will see some of this later in the course. The reason why two-dimensional arrays can lead to poor performance is the way the elements are stored and retrieved in the memory, one row at a time. Nevertheless, multidimensional arrays are helpful structures in contexts other than matrices, as we will see. A three-dimensional array is declared as: float values [ 1 0 ] [ 1 2 ] [ 8 ] ; Multidimensional arrays can be initialized using the syntax: int svar [ 3 ] [ 5 ] = { {1, 0, 3, 1, 3, {4, 9, 6, 0, 8, {7, 4, 9, 1, 10 ; However, the inner braces are mostly cosmetic, as the compiler will perform the exact same initialization out of int svar [ 3 ] [ 5 ] = { 1, 0, 3, 1, 3, 4, 9, 6, 0, 8, 7, 4, 9, 1, 10 ; As a convenience, just as in one-dimensional arrays, you may initialize the array by specifying all but the leftmost dimensions. The following excerpt int svar [ ] [ 5 ] = { 1, 0, 3, 1, 3, 4, 9, 6, 0, 8, 7, 4, 9, 1, 10 ; would declare and initialize the exact same 3 5 two-dimensional array as before. Note that the number of columns is needed to compute the row number. Elements in a multidimensional array are accessed one dimension at a time, from left to right. In the case of two-dimensional arrays, this means one row at a time. For example: int svar [ 3 ] [ 5 ] = { {1, 0, 3, 1, 3, {4, 9, 6, 0, 8, {7, 4, 9, 1, 10 ; svar [ 1 ] [ 3 ] = svar [ 2 ] [ 0 ] = 5; will set the elements in the second row and forth column and third row and first column of svar to 5. Recall that indexing starts at 0! MAE 9 71 Maurício de Oliveira

13 The next program illustrate the use of two-dimensional array to store a matrix of doubles: / Program w5 9. c / / Illustrates two dimensional arrays / main () { / declare variables / int i, j ; / declare two dimensional array / double array [ 3 ] [ 4 ] = { {3, 7, 4, 6, { 1, 2, 8,.5, {0, 3, 2, 10 ; / print matrix / for ( i = 0; i < 3; i++) { / print rows / for ( j = 0; j < 4; j++) / print element i, j / printf ("%12.4f ", array [ i ] [ j ] ) ; / end of row / printf ("\n" ) ; 5.6 Arrays of pointers The correspondence between pointers and arrays is a bit more subtle in the case of multidimensional arrays. Consider the example: int array [ 3 ] [ 5 ] ; int p1, p2, p3 ; p1 = &array [ 0 ] [ 0 ] ; p2 = array [ 0 ] ; p3 = array ; MAE 9 72 Maurício de Oliveira

14 All pointers p1, p2 and p3 point to the first element of array array. Note that a complete number of brackets will return an array element, which explains p1. The other pointer assignments can be understood by noting that the underlying type for a multidimensional array is that of a pointer-to-pointer. That is illustrated below in the case of a two-dimensional array: int array [ 3 ] [ 5 ] ; int p = array ; Therefore, array[0] and *array should dereference a pointer-to-pointer, returning in the above case a pointer to an int. The main difference between multidimensional arrays and arrays of pointer is however the fact that multidimensional arrays are rectangular data structures, with the same number of elements allocated for each specified dimension. This constraint is not necessarily present in an array of pointers. This is illustrated in the next example, where a non-rectangular array is created using an array of pointers: / Program w5 6. c / / Illustrates arrays of pointers to ints / main () { / declare variables / int i, j, n ; / declare rows / / the f i r s t element in a row is the number of elements to follow / int row1 [ ] = {3, 7, 4, 6 ; int row2 [ ] = {2, 1, 3 ; int row3 [ ] = {5, 1, 2, 3, 4, 5 ; / declare array of pointers to hold non rectangular array / int array [ ] = { row1, row2, row3 ; for ( i = 0; i < 3; i++) { / print row label / printf ("Row %d:\n", i + 1); / get number o f elements i n the row / n = array [ i ] [ 0 ] ; MAE 9 73 Maurício de Oliveira

15 / print elements of the row / for ( j = 1; j <= n ; j++) printf ("%d ", array [ i ] [ j ] ) ; printf ("\n" ) ; The next example uses an array of pointers to hold strings of different lengths: / Program w5 7. c / / Illustrates arrays of pointers to strings / main () { / declare variables / int i ; char messages [ ] = { "MAE 9 rocks!", "How I like my tutor!", "I was born to program in C." ; for ( i = 0; i < 3; i++) printf ("Message %d: %s \n", i + 1, messages [ i ] ) ; This construction is so commonly used that it is the mechanism by which command line parameters are passed to a C program. The next example illustrates this: / Program w5 8 / / Illustrate the use of command line parameters / main( int argc, char argv [ ] ) { int i ; for ( i = 0; i < argc ; i++) printf ("Parameter #%d: %s \n", i + 1, argv [ i ] ) ; MAE 9 74 Maurício de Oliveira

16 The above program produces iacs5. ucsd. edu% a. out 9 parameter k Parameter #1: a. out Parameter #2: 9 Parameter #3: parameter Parameter #4: k MAE 9 75 Maurício de Oliveira

### The C Programming Language course syllabus associate level

TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

### Arrays. Arrays, Argument Passing, Promotion, Demotion

Arrays Arrays, Argument Passing, Promotion, Demotion Review Introduction to C C History Compiling C Identifiers Variables Declaration, Definition, Initialization Variable Types Logical Operators Control

### arrays C Programming Language - Arrays

arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)

### 3 First Steps in C Programming

3 First Steps in C Programming The following is the typical structure of an executable C program: / C Program Structure / / This is a multline comment / / These are pre processor directives to include

### Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

### ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

The char Type ASCII Encoding The C char type stores small integers. It is usually 8 bits. char variables guaranteed to be able to hold integers 0.. +127. char variables mostly used to store characters

### Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Announcements Memory management Assignment 2 posted, due Friday Do two of the three problems Assignment 1 graded see grades on CMS Lecture 7 CS 113 Spring 2008 2 Safe user input If you use scanf(), include

### C Primer. Fall Introduction C vs. Java... 1

CS 33 Intro Computer Systems Doeppner C Primer Fall 2016 Contents 1 Introduction 1 1.1 C vs. Java.......................................... 1 2 Functions 1 2.1 The main() Function....................................

### C A short introduction

About these lectures C A short introduction Stefan Johansson Department of Computing Science Umeå University Objectives Give a short introduction to C and the C programming environment in Linux/Unix Go

### Punctuation in C. Identifiers and Expressions. Identifiers. Variables. Keywords. Identifier Examples

Identifiers and Expressions CSE 130: Introduction to C Programming Spring 2005 Punctuation in C Statements are terminated with a ; Groups of statements are enclosed by curly braces: { and } Commas separate

### Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

### Common C Errors. Compiled by: Leela Kamalesh Yadlapalli

Common C Errors Compiled by: Leela Kamalesh Yadlapalli This document shows some of the common errors and warnings that you may encounter during this class. Always remember to use the Wall option if you

### Sources: On the Web: Slides will be available on:

C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

### Python to C/C++ Fall 2011

Python to C/C++ Fall 2011 1. Main Program Python: Program code is indented after colon : def main(): body of program C/C++: Have more setup overhead. C: Both require #include directives to access libraries

### Standard printing function in C is printf Prints everything numbers, strings, etc. May be complex to use. Standard C library is called libc

Arrays and Structs and Pointers, Oh My! Programming in C Input and output Using printf Standard input and output Pointers Arrays Structures Combining these things together Arrays and Structs and Pointers,

### VB.NET Programming Fundamentals

Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

### Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

### In this Chapter you ll learn:

Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then stop. Lewis

### SANKALCHAND PATEL COLLEGE OF ENGINEERING, VISNAGAR ODD/EVEN ACADEMICSEMESTER (2014-15) ASSIGNMENT / QUESTION BANK (2110003) [F.Y.B.E.

SANKALCHAND PATEL COLLEGE OF ENGINEERING, VISNAGAR ODD/EVEN ACADEMICSEMESTER (2014-15) ASSIGNMENT / QUESTION BANK Subject: Computer Programming and Utilization (2110003) [F.Y.B.E.: ALL BRANCHES] Unit 1

### Adjusted/Modified by Nicole Tobias. Chapter 2: Basic Elements of C++

Adjusted/Modified by Nicole Tobias Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types

### C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 2: Basic Elements of C++

C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with the basic components of a C++ program,

### BHARATHIAR UNIVERSITY: COIMBATORE CENTRE FOR COLLABORATION OF INDUSTRY AND INSTITUTIONS(CCII) CERTIFICATE IN ADVANCED PROGRAMMING C++ LANGUAGE

Certificate in Advanced Programming - C++ Language Page 1 of 7 BHARATHIAR UNIVERSITY: COIMBATORE 641046 CENTRE FOR COLLABORATION OF INDUSTRY AND INSTITUTIONS(CCII) CERTIFICATE IN ADVANCED PROGRAMMING C++

### Going from Python to C

Going from Python to C Darin Brezeale December 8, 2011 Python is a high-level, interpreted language. C has many of the same types of programming constructs as in Python: arrays, loops, conditionals, functions,

### CSI 333 Lecture 2 Introduction to C: Part I 2 1 / 16

CSI 333 Lecture 2 Introduction to C: Part I 2 1 / 16 Basics of C Remark: Skim Chapters 1 through 6 of Deitel & Deitel. You will notice the following: C is (more or less) a subset of Java. (So, you are

### C programming. Intro to syntax & basic operations

C programming Intro to syntax & basic operations Example 1: simple calculation with I/O Program, line by line Line 1: preprocessor directive; used to incorporate code from existing library not actually

### Introduction to C Programming S Y STEMS

Introduction to C Programming CS 40: INTRODUCTION TO U NIX A ND L I NUX O P E R AT ING S Y STEMS Objectives Introduce C programming, including what it is and what it contains, which includes: Command line

### Dept. of CSE, IIT KGP

Programming in C: Basics CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of variable We must declare the

### INDEX. C programming Page 1 of 10. 5) Function. 1) Introduction to C Programming

INDEX 1) Introduction to C Programming a. What is C? b. Getting started with C 2) Data Types, Variables, Constants a. Constants, Variables and Keywords b. Types of Variables c. C Keyword d. Types of C

### Basic C Syntax. Comp-206 : Introduction to Software Systems Lecture 10. Alexandre Denault Computer Science McGill University Fall 2006

Basic C Syntax Comp-206 : Introduction to Software Systems Lecture 10 Alexandre Denault Computer Science McGill University Fall 2006 Next Week I'm away for the week. I'll still check my mails though. No

### Data Structure with C

Subject: Data Structure with C Topic: Strings In this chapter we are emphasizing the reading and storing string and also manipulation concepts through the following millstones. The discussion starts with

### 6.087 Lecture 5 January 15, 2010

6.087 Lecture 5 January 15, 2010 Review Pointers and Memory Addresses Physical and Virtual Memory Addressing and Indirection Functions with Multiple Outputs Arrays and Pointer Arithmetic Strings String

### Comp Arrays and Pointers. Class Notes. T h e G r o u p o f T h r e e

Comp 2401 Arrays and Pointers Class Notes 2013 T h e G r o u p o f T h r e e Introduction To Arrays: In C programming, one of the frequently problem is to handle similar types of data. For example: if

### M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE NOTE: IMPORTANT INSTRUCTIONS: 1. Question Paper in English and Hindi and Candidate can choose any one language. 2. In case of discrepancies in

### C programming: exercise sheet L2-STUE (2011-2012)

C programming: exercise sheet L2-STUE (2011-2012) Algorithms and Flowcharts Exercise 1: comparison Write the flowchart and associated algorithm that compare two numbers a and b. Exercise 2: 2 nd order

### 3) Some coders debug their programs by placing comment symbols on some codes instead of deleting it. How does this aid in debugging?

Freshers Club Important 100 C Interview Questions & Answers 1) How do you construct an increment statement or decrement statement in C? There are actually two ways you can do this. One is to use the increment

### 1. Constants. 2. Variables. 3. Reserved words or key words. 4. Constants. Character set in C

Character set in C We should use only the following characters in writing a C program. These characters can be combined to create C words. Alphabet: A, B, C, D.. Z, a, b, c, d..z Numeric digits: 0, 1,

### Final Exam Review. CS 1428 Fall Jill Seaman. Final Exam

Final Exam Review CS 1428 Fall 2011 Jill Seaman 1 Final Exam Friday, December 9, 11:00am to 1:30pm Derr 241 (here) Closed book, closed notes, clean desk Comprehensive (covers entire course) 25% of your

### Strings in C++ and Java. Questions:

Strings in C++ and Java Questions: 1 1. What kind of access control is achieved by the access control modifier protected? 2 2. There is a slight difference between how protected works in C++ and how it

### EC312 Chapter 4: Arrays and Strings

Objectives: (a) Describe how an array is stored in memory. (b) Define a string, and describe how strings are stored. EC312 Chapter 4: Arrays and Strings (c) Describe the implications of reading or writing

### A Rudimentary Intro to C programming

A Rudimentary Intro to C programming Wayne Goddard School of Computing, Clemson University, 2008 Part 4: Strings and Pointers 18 Strings.................................... D1 19 String Functions..............................

### As previously noted, a byte can contain a numeric value in the range 0-255. Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

Encoding of alphanumeric and special characters As previously noted, a byte can contain a numeric value in the range 0-255. Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets! Alphanumeric

### Example Solution to Exam in EDA150 C Programming

Example Solution to Exam in EDA150 C Programming Janurary 12, 2011, 14-19 Inga hjälpmedel! Examinator: Jonas Skeppstedt, tel 0767 888 124 30 out of 60p are needed to pass the exam. General Remarks A function

### Pointers. C and C++ Example. Manipulating pointers

Pointers C and C++ 3. Pointers Structures Alastair R. Beresford University of Cambridge Lent Term 28 Computer memory is often abstracted as a sequence of bytes, grouped into words Each byte has a unique

### Chapter 7. Arrays and Collections. Instructor s Manual Table of Contents. At a Glance. Chapter Overview. Chapter Objectives.

C# Programming: From Problem Analysis to Program Design, 2nd ed. 7-1 Chapter 7 Arrays and Collections At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes

### Pointers and dynamic memory management in C

Pointers and dynamic memory management in C Jakob Rieck Proseminar C - 2014 Contents 1 Introduction 2 2 Pointers 4 2.1 Declaration & Initialization................... 5 2.2 Using pointers..........................

### In this lecture you will learn:

Data Types and Variables Imed Hammouda Department of Software Systems Tampere University of Technology Objectives In this lecture you will learn: What is a data type and how types are represented in C++.

### CS193D Handout 04 Winter 2005/2006 January 11, 2006 A Crash Course in C++

CS193D Handout 04 Winter 2005/2006 January 11, 2006 A Crash Course in C++ Most people taking CS193D will already have some experience with C++. This handout is a quick refresher in case it s been a while.

### Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types In this lecture Computer Languages Assembly Language The compiler Operating system Data and program instructions Bits, Bytes and Data Types ASCII table Data Types

### Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

### Chapter 2: Problem Solving Using C++

Chapter 2: Problem Solving Using C++ 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common

### A First Book of C++ Chapter 2 Data Types, Declarations, and Displays

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays Objectives In this chapter, you will learn about: Data Types Arithmetic Operators Variables and Declarations Common Programming Errors

### Exercise 1 : Write a C++ program to calculate Fubanaci numbers X n, n=1,2,,1000 X n+1 = X n + X n-1, X 0 =1,, X 1 =1, n=1,2,

Programming problems Exercise 1 : Write a C++ program to calculate Fubanaci numbers X n, n=1,2,,1000 X n+1 = X n + X n-1, X 0 =1,, X 1 =1, n=1,2, Exercise 2: Write a C++ program TO REARRANGE A LIST OF

### UNIT III: 1. What is an array? How to declare and initialize arrays? Explain with examples

UNIT III: Arrays: Introduction, One-dimensional arrays, Declaring and Initializing arrays, Multidimensional arrays. Strings: Introduction to Strings, String operations with and without using String handling

### CIS 190: C/C++ Programming. Lecture 1 Introduction and Getting Started

CIS 190: C/C++ Programming Lecture 1 Introduction and Getting Started This course will teach you the basics of C and C++ give you more programming experience be appropriate for majors and non-majors not

### Borland C++ Compiler: Operators

Introduction Borland C++ Compiler: Operators An operator is a symbol that specifies which operation to perform in a statement or expression. An operand is one of the inputs of an operator. For example,

### Moving from Java to C++

Moving from Java to C++ This appendix explains how to transfer your Java programming skills to a substantial subset of C++. This is necessary for students who take their first programming course in Java

### Common Errors in C. David Chisnall. February 15, 2011

Common Errors in C David Chisnall February 15, 2011 The C Preprocessor Runs before parsing Allows some metaprogramming Preprocessor Macros Are Not Functions The preprocessor performs token substitution

### An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

### C++ Keywords. If/else Selection Structure. Looping Control Structures. Switch Statements. Example Program

C++ Keywords There are many keywords in C++ that are not used in other languages. bool, const_cast, delete, dynamic_cast, const, enum, extern, register, sizeof, typedef, explicit, friend, inline, mutable,

### Reading Assignment. Main Program in C. K.N. King Chapter 2. K.N. King Chapter 3. K.N. King Chapter 4. K.N. King Chapter 7. Our first C program

Reading Assignment Main Program in C In C the main program is a function called main The body of the function is enclosed in left ( ) and right ( ) curly braces. K.N. King Chapter 2 K.N. King Chapter 3

### Overview of a C Program

Overview of a C Program Programming with C CSCI 112, Spring 2015 Patrick Donnelly Montana State University Programming with C (CSCI 112) Spring 2015 2 / 42 C Language Components Preprocessor Directives

### PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

### Pass a multidimensional array using pointer

Passing arrays to functions A big topic for beginners is how to write a function that can be passed an array. A very common way of achieving this is done using pointers. This method can be seen all through

### Problem 2 Add the two 2 s complement signed 8-bit values given below, and express your answer in decimal.

Problem 1 Recall the definition of root in project 1. (The declaration of struct entrynode appears below.) struct entrynode * root; Give the type of each of the following expressions. The answer may be

### Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

### C AND C++ PROGRAMMING

C AND C++ PROGRAMMING Bharathidasan University A Courseware prepared by University Informatics Centre Part I - Programming in C Getting Started This courseware is intended to be an introduction to C programming

### Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Dr. Martin O. Steinhauser University of Basel Graduate Lecture Spring Semester 2014 Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct Friday, 7 th March

### Arrays in Java. Working with Arrays

Arrays in Java So far we have talked about variables as a storage location for a single value of a particular data type. We can also define a variable in such a way that it can store multiple values. Such

### Fundamentals of Programming

Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language

### Your first C program. Which one is best?

Your first C program #include void main(void) { printf( Hello, world!\n ); } #include void main(void) { printf( Hello, ); printf( world! ); printf( \n ); } Which one is best? #include

Standard C Input/Output 1 Output: printf() 2 Table of Contents Output: printf( ) - syntax & sematics Output: printf( ) - examples Output: printf( ) - format control Screen / Printer Control Input: scanf(

### C++ Programming Language

C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

### C Programming Dr. Hasan Demirel

C How to Program, H. M. Deitel and P. J. Deitel, Prentice Hall, 5 th edition (3 rd edition or above is also OK). Introduction to C Programming Dr. Hasan Demirel Programming Languages There are three types

### Project 2: Bejeweled

Project 2: Bejeweled Project Objective: Post: Tuesday March 26, 2013. Due: 11:59PM, Monday April 15, 2013 1. master the process of completing a programming project in UNIX. 2. get familiar with command

### Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Motivation Suppose that we want a program that can read in a list of numbers and sort that list, or nd the largest value in that list. To be concrete about it, suppose we have 15 numbers to read in from

1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

### The programming language C. sws1 1

The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

### PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

Lecture 11 Doubly Linked Lists & Array of Linked Lists In this lecture Doubly linked lists Array of Linked Lists Creating an Array of Linked Lists Representing a Sparse Matrix Defining a Node for a Sparse

### Python 3.3 to C/C++ Summer 2014

Python 3.3 to C/C++ Summer 2014 1. Main Program Python: Program code is indented after colon : def main(): body of program C/C++: Have more setup overhead. Both require #include directives to access libraries

### The Basics of C Programming. Marshall Brain

The Basics of C Programming Marshall Brain Last updated: October 30, 2013 Contents 1 C programming 1 What is C?................................. 2 The simplest C program, I........................ 2 Spacing

### IC221: Systems Programming 06-Week Written Exam [SOLUTIONS]

IC221: Systems Programming 06-Week Written Exam [SOLUTIONS] February 12, 2014 Answer the questions in the spaces provided on the question sheets. If you run out of room for an answer, continue on the back

### Programming for MSc Part I

Herbert Martin Dietze University of Buckingham herbert@the-little-red-haired-girl.org July 24, 2001 Abstract The course introduces the C programming language and fundamental software development techniques.

### WESTMORELAND COUNTY PUBLIC SCHOOLS 2011 2012 Integrated Instructional Pacing Guide and Checklist Computer Math

Textbook Correlation WESTMORELAND COUNTY PUBLIC SCHOOLS 2011 2012 Integrated Instructional Pacing Guide and Checklist Computer Math Following Directions Unit FIRST QUARTER AND SECOND QUARTER Logic Unit

### 12 INPUT AND OUTPUT OF DATA

12 INPUT AND OUTPUT OF DATA 12.1 INTRODUCTION In C language input and output of data is done by a collection of library functions like getchar, putchar, scanf, printf, gets and puts. These functions permit

### 6.096 Lab 1. Due: 7 January 12:30:00. September 20, 2011

6.096 Lab 1 Due: 7 January 1:30:00 September 0, 011 1 Additional Material 1.1 Constants A constant is an expressions with a fixed value. Kinds of constants: Literals: used to express particular values

### Programming Language: Syntax. Introduction to C Language Overview, variables, Operators, Statements

Programming Language: Syntax Introduction to C Language Overview, variables, Operators, Statements Based on slides McGraw-Hill Additional material 2004/2005 Lewis/Martin Modified by Diana Palsetia Syntax

### Summary. Pre requisition. Content Details: 1. Basics in C++

Summary C++ Language is one of the approaches to provide object-oriented functionality with C like syntax. C++ adds greater typing strength, scoping and other tools useful in object-oriented programming

### OBJECT ORIENTED PROGRAMMING IN C++

OBJECT ORIENTED PROGRAMMING IN C++ For Off Campus BSc Computer Science Programme UNIT 1 1. The goal of programmers is to develop software that are. A. Correct B. Reliable and maintainable C. Satisfy all

### The if-statement. Simple and compound statements. The if-statement comes in two forms: Simple statements:

1 2 Simple and compound s The if- Simple s: E.g.: expression; Various jumps : break, goto, continue, return. k = a * p + 3; printf("k = %d\n", k); 1 + 2; ; The if- comes in two forms: or E.g.: if (expression)

### VALLIAMMAI ENGINEERING COLLEGE SRM NAGAR, KATTANKULATHUR 603 203 DEPARTMENT OF COMPUTER APPLICATIONS QUESTION BANK IN REVISED BLOOM S TAXONOMY

ACADEMIC YEAR: 0 7 VALLIAMMAI ENGINEERING COLLEGE SRM NAGAR, KATTANKULATHUR 0 0 SEMESTER: ODD BRANCH: MCA YEAR: I SEMESTER: I SUBJECT CODE AND NAME: MC70 Problem Solving and Programming NAME OF THE FACULTY

### The char Data Type. Character and String Processing. Another Example /* Capitalize all lowercase letters */ while ((c = getchar())!

Character and String Processing CSE 130: Introduction to C Programming Spring 2005 The char Data Type A char value can be thought of as either a character or a small integer printf( %d, a ); /* prints

### TN203. Porting a Program to Dynamic C. Introduction

TN203 Porting a Program to Dynamic C Introduction Dynamic C has a number of improvements and differences compared to many other C compiler systems. This application note gives instructions and suggestions

### Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from

### 1 (1x17 =17 points) 2 (21 points) 3 (5 points) 4 (3 points) 5 (4 points) Total ( 50points) Page 1

CS 1621 MIDTERM EXAM 1 Name: Problem 1 (1x17 =17 points) 2 (21 points) 3 (5 points) 4 (3 points) 5 (4 points) Total ( 50points) Score Page 1 1. (1 x 17 = 17 points) Determine if each of the following statements

### Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Common to: CSE 2 nd sem IT 2 nd sem Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart

### COMP MIPS instructions 3 Feb. 10, 2016

In the past two lectures, we discussed MIPS operations on integers. Today we will consider a few data structures that you are familiar with, namely arrays and strings, and discuss how to implement them