Intro to Programming in C. Motivation for Using C  High level, compiler language  Efficiency over user-friendliness  Allows programmer greater freedom,

Slides:



Advertisements
Similar presentations
C Language.
Advertisements

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.
Lecture 2 Introduction to C Programming
Introduction to C Programming
Structure of a C program
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
C programming an Introduction. Types There are only a few basic data types in C. char a character int an integer, in the range -32,767 to 32,767 long.
Chapter 2 Data Types, Declarations, and Displays
Introduction To C++ Programming 1.0 Basic C++ Program Structure 2.0 Program Control 3.0 Array And Structures 4.0 Function 5.0 Pointer 6.0 Secure Programming.
Basic Elements of C++ Chapter 2.
Computer Science 210 Computer Organization Introduction to C.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Outline Variables 1.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Input & Output: Console
C Programming Tutorial – Part I CS Introduction to Operating Systems.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Chapter 2: Using Data.
UniMAP Sem1-07/08EKT120: Computer Programming1 Week2.
Introduction to C Programming Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010 Fall.
Week 1 Algorithmization and Programming Languages.
C++ Programming: Basic Elements of C++.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
CECS 130 EXAM 1. To declare a constant (read only) value: const int x = 20; const float PI = 3.14; Can we do this? const int x;
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
UNIMAP Sem2-07/08EKT120: Computer Programming1 Week 2 – Introduction to Programming.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
Chapter 2: Basic Elements of C++
Computer Science 210 Computer Organization
Chapter 2 - Introduction to C Programming
C Programming Tutorial – Part I
C Short Overview Lembit Jürimägi.
C Basics.
By: Syed Shahrukh Haider
Introduction to C Programming
Computer Science 210 Computer Organization
Introduction to C++ Programming
Basics of ‘C’.
Introduction to C Programming
Assignment Operators Topics Increment and Decrement Operators
Assignment Operators Topics Increment and Decrement Operators
elementary programming
C Programming Getting started Variables Basic C operators Conditionals
Fundamental Programming
Session 1 – Introduction to Computer and Algorithm (Part 2)‏
DATA TYPES There are four basic data types associated with variables:
Introduction to C Programming
Assignment Operators Topics Increment and Decrement Operators
Chapter 12 Variables and Operators
Presentation transcript:

Intro to Programming in C

Motivation for Using C  High level, compiler language  Efficiency over user-friendliness  Allows programmer greater freedom, but chance for is error increased

Functions  C includes support for functions  Function structure return_type function_name(parameters) { variable declarations; body statements; return return_value; }  Example: int add_function(int a, int b) /* Pass values a and b to function */ { int sum; sum = a + b; return sum; /* Returns the integer variable sum */ }

Main Function  Each C program contains a main routine, which is itself a function  The main routine typically returns no value and contains no parameters, so the default return type is “void”  Example: void main(void) { main routine }

Creating Functions  Convention is to place function “prototype” above the main routine  Prototype includes function name and variables used: int add_function(int, int); /* function prototype */ main routine …  Function body defined below main routine: main routine {…} int add_function(int a, int b); { function body};

Calling Functions  Call a function by invoking its function name within the main routine or another function and passing parameters  Example: void main(void) { int a,b,x; … x = add_function(a, b); /* Passed by value */ /* x is set equal to the return value of add_function */ }

Basic Data Types  Int Represents standard integers (usually 32 bits)  Float Represents numbers with decimal precision (usually 32 bits) Can use notation: 2.3E10  2.3 * 10^10  Double Represents very large floating point numbers (usually 64 bits)  Character (Can also declare “byte” when using Processor Expert) Represents single ASCII characters Characters contained within single quotes: ‘a’  No String types!

Data Type Modifiers  Signed Allows the data type to take on negative and positive values Integers, doubles, and floats are signed by default  Unsigned Allows the data type to take on only positive values  Short Reduces range of values and storage space occupied by the variable (usually 16 bits)  Long Increases range of values and storage space occupied by the variable (usually 32 bits)

Declaring Variables  Variables are defined using the following format: type name1, …, name5;  Name rules: Cannot begin with a number Cannot contain spaces (can contain underscores) Cannot contain any punctuation marks or arithmetic operators Cannot be a reserved keyword C is case sensitive!  Examples int a, b, c; short int d; unsigned double e; float f; char g; …

Initializing Variables  Possible to initialize variables within declaration: int a = 3; byte x = 0x02; byte y = 0b ; char b = ‘b’;  Constants Use keyword “const” Constants cannot be changed after initialization Example: const int b = 5;

Assigning Variables  Valid assignments int a,b; int c = 5; a = 10; a = c; a = b = c = 0;  Type Casting Possible to convert between several types: (type) variable_name Examples: x = (int) float_variable /* Converts a float to an integer x = (int) char_variable /* Converts a character to ASCII value x = (char) int_variable /* Converts ASCII to appropriate character x = (float) int_variable /* Converts an integer to a float

Variable Scope  Global variables Declared above the main routine, normal syntax (convention is to use all caps) Available to all functions Global constants declared using: #define VARIABLE_NAME value  Local variables Declared within a function Only available to the function in which declared, able to pass on to other functions

Pointers  Used to point to a memory location of a variable  Points to the beginning of the memory segment the variable occupies  Use the ‘*’ operator in front of variable to declare a pointer float test_var; float *test_var_loc;  Use the ‘&’ operator to get the memory location of non-pointer variables test_var_loc = &(test_var)

Pointer Operations  Using the ‘*’ in front of an already declared pointer yields contents of memory location pointed to  Example: int test_var = 10; int X; int *location; location = &(test_var); X = *location; /* The variable X now contains the value 10

Pointer Operations (cont.)  Possible to assign values to memory location using pointer  Example: int test_var = 10; int *location; location = &(test_var); *location = 20; /* The variable test_var now contains the value 20

Function Calls Using Pointers  Possible to pass “by reference” using pointers  Example: void set_zero( int *a) { *a = 0; } void main() { int b = 10; set_zero(&b); /* b is now set to zero */ }

Pointer Notes  Not useful to initialize pointers in the declaration: Initially, pointer points to “garbage” location, so assigning a value to this location is useless  Useful in debugging  Used heavily in string manipulation  Make linked-lists possible

Arrays  Arrays are defined as follows: type var_name[size]  Array index begins at zero  Array index ends at size – 1  Example: int array1[3] = {1, 2, 3} /* array1[0] = 1, array1[1] = 2, array1[2] = 3 */

Arrays (cont.)  Multidimensional arrays: int multi_array[10][10]; /* 10x10 array */  Possible to use as many dimensions as needed  Can initialize entire array at once: multi_array[ ][ ] = 0;

Strings  There is no “string” type in C  Strings made possible through character arrays  Declared as a pointer to a character or an array of characters

Creating Strings  Pointer method Creates a pointer to the first location of the string char *test_string = “Hello World”; Strings always terminated with the null character: ‘\0’  Array method Easier to understand char test_string[20] = “Hello World”;

String Manipulation  Many useful functions contained within “string.h” strlen(string) returns the length of the string excluding the null character strcpy(string1, string2) copies contents of string2 into string 1 strcmp(string1, string2) compares string 1 to string 2, returns 1 if same and 0 if different strstr(string1, string2) searches string1 for the substring string2, returns the location at which the substring begins or null strcat(string1, string2) concatenates string2 onto the end of string1

Structures  Creates a new data type that can hold several data types within one variable  Use “struct” keyword typedef struct { char name[30]; char address[50]; int birth_year; int birth_month; int birth_day; } PersonalData;  Declare variable of type PersonalData PersonalData record1;  Access struct using dot notation record1.name = “Sam Castillo”;

Arithmetic Operations  Addition: + a + b  Adds a to b  Subtraction: - a – b  Subtracts b from a  Multiplication: * a * b  Multiplies a by b  Division: \ a \ b  Does integer division of a by b  Modulus: % a % b  Returns remainder of a \ b

Comparison Operators  Greater than: >, >= a >= b  Tests if a is greater than or equal to b  Less than: <, <= a <= b  Tests if a is less than or equal to b  Equal to: == a == b  Tests if a is equal to b  Not equal: != a != b  Tests if a is not equal to b

Bit Operators  Shift Left: << a << b  Shifts bits in a left by b bits  Shift Right: >> a >> b  Shifts bits in a right by b bits  And: & a & b  Does the bit-wise AND of a and b  Or: | a | b  Does the bit-wise OR of a and b  Exclusive OR: ^ a ^ b  Does the bit-wise XOR of a and b

Other Operators  One’s compliment: ~ ~a  Performs one’s compliment of a  Pre-increment: ++ ++a  the value of a after incrementing  Post-increment: ++ a++  the value of a before incrementing  Pre-decrement: -- --a  the value of a after decrementing  Post-decrement: -- a--  the value of a before decrementing  Negation: ! !a  does the negation of a

If statements  Basic structure: if (test_statement) { do this if test statement is true; } else if (test_statement) { do this if test statement is true; } else { do this if the above conditions were false; }

Alternative If Statement  C provides a more concise way to create an If statement  The syntax: decision statement ? true statement:false statement  Example int X = 4; X == 5 ? X = 6 : X = 7; /* First, the program checks if X is equal to 5 If X was equal to 5, then X would be set equal to 6 Since X wasn’t equal to 5, X is set to equal 7 */

For Loops  Basic structure for(control variable; loop condition; increment) { statements; }  Example: int count; int a = 1; for(count = 1; count <= 5; count++) { a = a*2; } /* Here a = 32 when the loop completes */  Cannot declare control variable within the for loop!  Can exit a for loop at any time with the statement “break”

While Loops  While loop: Condition is evaluated each time the loop runs, including the first time it is called while(condition) {statements; }  Do While loop: Statements are executed the first time, then execution depends on whether the condition evaluates to 1 do { statements; } while(condition)

Printing to the Screen  Output to the screen using “printf” function  Structure: printf(“Text…”, variables used);  To insert variables, must use “control sequences”

Printf Control Sequences  Denoted with a “%” %d  integers, doubles %u  unsigned integers %c  characters %s  strings (character arrays) %f  fixed floating point values %e  scientific notation floating point %x  hexadecimal values %o  octal values

Inserting Control Sequences  Insert the sequences in the Text portion of the printf statement int a = 20; char c = ‘b’; printf(“The value of a is %d.”, a); printf(“The value of c is %c.”, c);

Output Formatting  Padding the end of the output printf(“%6d, int_val) /* Pads up to 6 places  Padding the start of the output printf(“%-6d, int_val) /* Pads up to 6 places  Floating point precision printf(“%.3d, float_val) /* Prints 3 decimal places  Truncating strings printf(“%.3s, string_val) /* Prints first 3 characters  Truncating and Padding printf(%10.5, string_val) /* Prints first 5 characters, pads last 5

Outputting Special Characters  Possible to output with the following codes: \b  backspace \f  form feed \n  new line \r  carriage return \t  horizontal tab \v  vertical tab \”  double quote \’  single quote \\  backslash \ddd  octal ASCII code \xddd  hex ASCII code

Receiving Keyboard Input  Using the “scanf” function scanf(“String…”, pointers);  Must use control sequence, different from printf  Must use “&” when referring to input variables  Example: scanf(“%d”, &int_var); scanf(“%f”, &float_var); scanf(“%c”, &char_var);

Scanf Control Sequences  Denoted with a “%” %d  integers %ld  long integers %h  short integers %c  single character %s  strings (character arrays) %f  fixed floating point values %lf  long float type %e  scientific notation floating point %x  hexadecimal values %o  octal values

Dangers of Scanf  Scanf can cause many errors if used incorrectly  The control sequence used must match the type of variable that is storing the input  If types don’t match, scanf quits Input file will hold onto data, which is used in next scanf call

Including Separate Files  Start by including all necessary libraries and files before the main routine  Use the #include operator to include each header-file as needed  Example: #include #include #include  Include all function headers before the main routine

Commonly Used Libraries  Stdlib.h Contains many of C’s general use functions  Stdio.h Contains all input/output functions  Math.h Contains many math-related functions  String.h Cointains all string manipulation functions

Creating Header Files  Create desired functions within a text editor  Save with the.h extension  Include the header file within the main program using the #include operator

Header File Example  Header File: test.h int testfunction1( ) { function body… } int testfunction2() { function body } …  Main file #include …  Now have access to all functions defined within test.h

Putting it all together  Example Program Structure #include … #define … Global variable declarations… function prototypes…. main routine { local variable declarations main body function calls } function definitions… { local variable declarations body statements return }