Programming Review: Functions, pointers and strings.

Slides:



Advertisements
Similar presentations
Lecture 3 Some commonly used C programming tricks. The system command Project No. 1: A warm-up project.
Advertisements

Computer Programming w/ Eng. Applications
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Chapter 7 Process Environment Chien-Chung Shen CIS, UD
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
A file reminder Files are used to store data and information They are manipulated through a pointer to FILE (FILE *) This pointer is returned when opening.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
1 Strings ( מחרוזות ). 2 Agenda Definition and initialization Termination Input / Output String library.
Command-line arguments CS 201 Fundamental Structures of Computer Science.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
1 More on Pointers. 2 Reminder 3 Pointers Pointer is a variable that contains the address of a variable Here P is said to point to the variable C C 7.
What does this program do ? #include int main(int argc, char* argv[]) { int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n",
Exercise 10 Review: pointers, strings and recursion.
Exercise 7 Strings. An array of characters Used to store text Another way to initialize: char A[ ]=“blabla”;
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
C Programming Strings. Array of characters – most common type of array in C  Let’s make them easier for use Denote the end of array using a special character.
Programming Pointers. Variables in Memory x i c The compiler determines where variables are placed in memory This placement cannot.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Literals and Variables Dale Roberts,
Programming Arrays. Question Write a program that reads 3 numbers from the user and print them in ascending order. How many variables do we need to store.
Command line arguments. – main can take two arguments conventionally called argc and argv. – Information regarding command line arguments are passed to.
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
Strlen() implementation /* strlen : return length of string s */ int strlen(char *s) { int n; for (n = 0 ; s[n] != ‘\0’ ; n++) ; return n; } /* strlen.
CPT: Arrays of Pointers/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to illustrate the use of arrays.
How to start Visual Studio 2008 or 2010 (command-line program)
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Command Line Arguments.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
File IO and command line input CSE 2451 Rong Shi.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
1 Command-Line Processing In many operating systems, command-line options are allowed to input parameters to the program SomeProgram Param1 Param2 Param3.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
מערכים (arrays) 02 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 15 1 Department of Computer Science-BGU.
Weeks 5-6 Pointers and Arrays Basic pointer type Pointers and Arrays Address arithmetic Pointer Arrays User-defined data types Structures Unions Pointers.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
C Programming - Structures. Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure.
Cryptography.
Functions. Why use functions? They can break your problem down into smaller sub-tasks (modularity).  easier to solve complex problems They make a program.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Recursion.
Exercise 1 #include int main() { printf(“Hello C Programming!\n”); return 0; } 1.Run your Visual Studio 2008 or Create a new “project” and add.
Computer Programming for Engineers
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
Today’s Material Strings Definition Representation Initialization
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
“Success consists of going from failure to failure without loss of enthusiasm.” Winston Churchill.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
LINKED LISTS.
C Primer.
Characters and Strings
Strings (מחרוזות).
Command Line Arguments
Command line arguments
Command Line Arguments
Pointers Department of Computer Science-BGU יום שלישי 31 יולי 2018.
CSE 303 Concepts and Tools for Software Development
INC 161 , CPE 100 Computer Programming
C Stuff CS 2308.
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Programming Strings.
Functions Reasons Concepts Passing arguments to a function
Characters and Strings
Strings Adapted from Dr. Mary Eberlein, UT Austin.
15213 C Primer 17 September 2002.
Presentation transcript:

Programming Review: Functions, pointers and strings

Pointers int nums[] = {1, 2, 3}; char str[] = "moshe"; int* q = nums; char* p = str; q num m o s h e \0 p str

Pointers int nums[] = {1, 2, 3}; char str[] = "moshe"; int* q = nums; char* p = str; (q+1) (p+3) m o s h e \0 str

Pointers p[i] *(p+i) m o s h e \0 q p q[1]q[2]q[0] p[1]p[4] p[0] *p

Pointers and Functions If we want to change a variable inside a function, we must pass it a pointer to the variable (its address) The function will “fill” this address with the right value Example: Swap void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; }

Pointers and Functions Variables that are defined inside the function “die” when the function ends!!! char* func() { char str[LENGTH + 1];... return str; } str doesn’t exist outside the function’s body

1.What is wrong here? int main() { int n = 3; multBy3(n); printf(“n=%d”,n); } void multBy3(int n) { int num = n; num *= 3; n = num; }

2.What is wrong here? int main() { int n = 3; multBy3(&n); printf(“n=%d”,n); } void multBy3(int *n) { int num = n; num *= 3; n = num; }

3.What is wrong here? int main() { int n = 3; multBy3(&n); printf(“n=%d”,n); } void multBy3(int *n) { int num = *n; num *= 3; n = num; }

4.What is wrong here? int main() { int n = 3; multBy3(&n); printf(“n=%d”,n); } void multBy3(int *n) { int num = *n; num *= 3; n = &num; }

References 1. Define a variable in the main 2. Pass its address to the function 3. The function fills the address with a value 4. The main can use it as a normal variable int main() { int num; }

References 1. Define a variable in the main 2. Pass its address to the function 3. The function fills the address with a value 4. The main can use it as a normal variable Int main() { int num; multBy3(&num); }

References 1. Define a variable in the main 2. Pass its address to the function 3. The function fills the address with a value 4. The main can use it as a normal variable void multBy3(int *n) { (*n) *=3; } Int main() { int num; multBy3(&num); }

References 1. Define a variable in the main 2. Pass its address to the function 3. The function fills the address with a value 4. The main can use it as a normal variable Int main() { int num; multBy3(&num); printf(“num=%d”,num); }

Exercise with pointers and strings Implement the following function: char* str_any(char *str1, char *str2);  Input – two strings str1, str2  Output – pointer to the first occurrence in str1 of any of the characters contained in str2

Exercise (cont.) Write a program that accepts a string from the user and replaces all punctuation signs (,.;:!? ) with spaces

Solution (str_any.c) char* str_any(char* str1, char* str2) { while (*str1 != '\0') { if (strchr(str2, *str1) != NULL) { return str1; } ++str1; } return NULL; }

Solution int main(void) { char* punc = ".,;:!?"; char s[MAX_LENGTH + 1]; char *p; printf("Please enter a line of text\n"); scanf("%100s", s); for (p = str_any(s, punc); p != NULL; p = str_any(p + 1, punc)) { *p = ' '; } printf("Resulting string is:\n%s\n", s); return 0; }

Command line arguments Command line arguments are arguments for the main function  Recall that main is basically a function  It can receive arguments like other functions  The ‘calling function’ in this case is the operating system, or another program

‘main’ prototype When we want main to accept command line arguments, we must define it like this  argc holds the number of arguments that were entered by the caller  argv is an array of pointers to char – an array of strings – holding the text values of the arguments The first argument is always the program’s name int main(int argc, char* argv[])

‘main’ prototype int main(int argc, char* argv[]) argc : 3 argv : \0 p r o g n a m e \0 t e x t \0

Example /* This program displays its command-line arguments */ #include int main(int argc, char *argv[]) { int i; printf("The program's command line arguments are: \n"); for (i = 0; i < argc; ++i) { printf("%s\n", argv[i]); } return 0; }

Specifying the arguments In Visual Studio: Project  Settings  Debug, in the ‘program arguments’ field

Specifying the arguments We can also specify the arguments directly, by using the Windows console (Start  Run…, then type ‘cmd’ and drag the executable into the window. Then type the arguments and )

Helper functions – atoi/atof Command line arguments are received in the form of strings These functions are used when we want to transform them into numbers For example – atof(“13.5”) returns the number Must #include int atoi(char s[]); double atof(char s[]);

Exercise Write a program that accepts two numbers as command line arguments, representing a rectangle’s height and width (as floating- point numbers). The program should display the rectangle’s area and perimeter

Solution (args_rectangle.c) int main(int argc, char* argv[]) { double width, height; if (argc != 3) { printf("Wrong number of arguments!\n"); return 1; } width = atof(argv[1]); height = atof(argv[2]); printf("The rectangle's area is %g\n", width * height); printf("The rectangle's perimeter is %g\n", 2 * (width + height)); return 0; }