Introduction to C Programming

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
CS 6301 Lecture 2: First Program1. CS Topics of this lecture Introduce first program  Explore inputs and outputs of a program Arithmetic using.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Chapter 2 Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
Introduction to C Programming
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
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.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Principles of Programming Chapter 4: Basic C Operators  In this chapter, you will learn about:  Arithmetic operators  Unary operators  Binary operators.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
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.
Chapter 1.2 Introduction to C++ Programming
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 6 JavaScript: Introduction to Scripting
Chapter 1.2 Introduction to C++ Programming
Chapter 1: Introduction to computers and C++ Programming
Introduction to C++ Programming
Chapter 2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
CSC201: Computer Programming
BASIC ELEMENTS OF A COMPUTER PROGRAM
Chapter 2 - Introduction to C Programming
Chapter 2, Part I Introduction to C Programming
Basic Elements of C++.
Fundamental of Programming (C)
Chapter 2 - Introduction to C Programming
Introduction to C Programming
Basic Elements of C++ Chapter 2.
2008/10/01: Lecture 8 CMSC 104, Section 0101 John Y. Park
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Chapter 2 - Introduction to C Programming
Chapter 2 Introduction to C Programming
Chapter 2 - Introduction to C Programming
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
INPUT & OUTPUT scanf & printf.
Introduction to C++ Programming
Variables in C Topics Naming Variables Declaring Variables
Chapter 2 - Introduction to C Programming
Variables in C Topics Naming Variables Declaring Variables
Chapter 2 - Introduction to C Programming
Introduction to C++ Programming
Chapter 2: Introduction to C++.
Introduction to Java Applications
Programs written in C and C++ can run on many different computers
Chapter 2 - Introduction to C Programming
Variables in C Topics Naming Variables Declaring Variables
2008/10/01: Lecture 8 CMSC 104, Section 0101 John Y. Park
DATA TYPES There are four basic data types associated with variables:
Variables in C Topics Naming Variables Declaring Variables
Introduction to C Programming
Variables in C Topics Naming Variables Declaring Variables
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Variables in C Topics Naming Variables Declaring Variables
Introduction to C Programming
Presentation transcript:

Introduction to C Programming C How to Program, 6/e

OBJECTIVES Simple C program Variables Data types Arithmetic in C Operations Precedence Rules

A Simple C Program Examples: // int is return data type // main is entrance function int main() { statement 1; // …. return 0; }

C Program #include <stdio.h> // header file (preprocessor ) // calculating sum of two user input variables int main() { /* variable definition */ int a; int b; int result = 0; // get first variables form user printf("Enter first number:\n"); scanf("%d", &a); // get scoend variables form user printf("Enter scoend number:\n"); scanf("%d", &b); // sum of input variables result = a + b; printf("%d + %d = %d\n", a, b, result); system("Pause"); return 0; } Examples: Header file Main function Variables Input and output Process

2.2 A Simple C Program: Printing a Line of Text

2.2 A Simple C Program: Printing a Line of Text (Cont.) Lines 1 and 2 /* Fig. 2.1: fig02_01.c A first program in C */ begin with /* and end with */ indicating that these two lines are a comment. C99 also includes the C++ language’s // single-line comments in which everything from // to the end of the line is a comment.

2.2 A Simple C Program: Printing a Line of Text (Cont.) You insert comments to document programs and improve program readability. Comments do not cause the computer to perform any action when the program is run. Comments are ignored by the C compiler and do not cause any machine-language object code to be generated. Comments also help other people read and understand your program.

2.2 A Simple C Program: Printing a Line of Text (Cont.) #include <stdio.h> Lines beginning with # are processed by the preprocessor before the program is compiled. Line 3 tells the preprocessor to include the contents of the standard input/output header (<stdio.h>) in the program.

2.2 A Simple C Program: Printing a Line of Text (Cont.) int main( void ) Every program in C begins executing at the function main. The parentheses after main indicate that main is a program building block called a function. The keyword int to the left of main indicates that main “returns” an integer (whole number) value. The void in parentheses here means that main does not receive any information. A left brace, {, begins the body of every function (line 7). A corresponding right brace ends each function (line 11). This pair of braces and the portion of the program between the braces is called a block.

2.2 A Simple C Program: Printing a Line of Text (Cont.) printf( "Welcome to C!\n" ); instructs the computer to perform an action, namely to print on the screen the string of characters marked by the quotation marks. A string is sometimes called a character string, a message or a literal. The entire line, including printf, its argument within the parentheses and the semicolon (;), is called a statement. Every statement must end with a semicolon (also known as the statement terminator).

2.2 A Simple C Program: Printing a Line of Text (Cont.) When encountering a backslash in a string, the compiler looks ahead at the next character and combines it with the backslash to form an escape sequence. The escape sequence \n means newline.

2.2 A Simple C Program: Printing a Line of Text (Cont.) return 0; /* indicate that program ended successfully */ is included at the end of every main function. The keyword return is one of several means we’ll use to exit a function. When the return statement is used at the end of main as shown here, the value 0 indicates that the program has terminated successfully.

Variables Have the same meaning as variables in algebra Single alphabetic character Each variable needs an identifier that distinguishes it from the others a = 5 x = a + b valid identifier in C may be given representations containing multiple characters A-Z, a-z, 0-9, and _ (underscore character) First character must be a letter or underscore (no, _no 9no) Usually only the first 32 characters are significant There can be no embedded blanks (student no) Identifiers are case sensitive (area, Area, AREA, ArEa) Keywords cannot be used as identifiers

Reserved Words(Keywords) in C auto break int long case char register return const continue short signed default do sizeof static double else struct switch enum extern typedef union float for unsigned void goto if volatile while

Naming Conventions C programmers generally agree on the following conventions for identifier: Use meaningful identifiers Separate words within identifiers with: underscores capitalize each word A variable is a location in memory where a value can be stored for use by a program. Examples: surfaceArea SurfaceArea Surface_Area

Variable declaration Before using a variable, you must declare it All variables must be defined with a name and a data type. Data_Type Identifier; int width; // width of rectangle float area; // result of calculating area stored in it char separator; // word separator Data_Type Identifier = Initial_Value; int width = 10; // width of rectangle float area = 255; // result of calculating area stored in it char seperator = ‘,’; // word separator Data_Type Identifier, Identifier, Identifier; int width, length, temporary; float radius, area = 0;

Data types Minimal set of basic data types primitive data types int float double char Void The size and range of these data types may vary among processor types and compilers

2.3 Another Simple C Program: Adding Two Integers

Printf / Scanf prints the literal Enter first integer on the screen and positions the cursor to the beginning of the next line. printf( "Enter first integer\n" ); /* prompt */ This message is called a prompt because it tells the user to take a specific action. The scanf function reads from the standard input, which is usually the keyboard. scanf( "%d", &integer1 ); /* read an integer */ uses scanf to obtain a value from the user.

Printf / Scanf This scanf has two arguments, "%d" and &integer1. The first argument, the format control string, indicates the type of data that should be input by the user. The %d conversion specifier indicates that the data should be an integer (the letter d stands for “decimal integer”). The second argument of scanf begins with an ampersand (&)—called the address operator in C—followed by the variable name. The ampersand, when combined with the variable name, tells scanf the location (or address) in memory at which the variable integer1 is stored.

Printf / Scanf When the computer executes the preceding scanf, it waits for the user to enter a value for variable integer1. The user responds by typing an integer, then pressing the Enter key to send the number to the computer. The computer then assigns this number, or value, to the variable integer1. Any subsequent references to integer1 in this program will use this same value.

2.5  Arithmetic in C The C arithmetic operators are summarized in Fig. 2.9.

Operators Arithmetic Operators Equality and Relational Operators unary operators operators that require only one operand binary operators operators that require two operands Equality and Relational Operators Logical Operators Bitwise Operators Assignment Operators Conditional Operator Width * High Operand

Arithmetic Operators Unary Operator C operation Operator Expression Explanation Positive + a = +3; Negative - b = -4; Increment ++ i++; Equivalent to i = i + 1 Decrement - - i - -; Equivalent to i = i - 1

PRE / POST Increment Consider this example: But if we have: int width = 9; printf("%d\n", width); width++; int width = 9; printf("%d\n", width++); printf("%d\n", width); 9 10 int width = 9; printf("%d\n", ++width); printf("%d\n", width); int width = 9; width++; printf("%d\n", width); 10

Equivalent Statements PRE / POST Increment int R = 10; int count = 10; ++ Or -- Statement Equivalent Statements R count R = count++; R = count; count = count + 1; 10 11 R = ++count; R = count--; count = count – 1; 9 R = --count;

Arithmetic Operators Binary Operators C operation Operator Expression Addition + b = a + 3; Subtraction - b = a – 4; Multiplication * b = a * 3; Division / b = a / c; Modulus (integer) % b = a % c;

Division The division of variables of type integer will always produce a variable of type integer as the result Example int a = 7, b; float z; b = a / 2; z = a / 2.0; printf("b = %d, z = %f\n", b, z); Since b is declared as an integer, the result of a/2 is 3, not 3.5 b = 3, z = 3.500000

Modulus You could only use modulus (%) operation on integer variables (int, long, char) z = a % 2.0; // error z = a % 0; // error Example int a = 7, b, c; b = a % 2; c = a / 2; printf("b = %d\n", b); printf("c = %d\n", c); Modulus will result in the remainder of a/2. 7 2 6 3 1 - a/2 integral a%2 remainder

Equality and Relational Operators Equality Operators: Relational Operators: Operator Example Meaning == x == y x is equal to y != x != y x is not equal to y Operator Example Meaning > x > y x is greater than y < x < y x is less than y >= x >= y x is greater than or equal to y <= x <= y x is less than or equal to y

Bitwise Operators Operator Name Description & AND Result is 1 if both operand bits are 1 | OR Result is 1 if either operand bit is 1 ^ XOR Result is 1 if operand bits are different ~ Not (Ones Complement) Each bit is reversed <<  Left Shift Multiply by 2 >>  Right Shift Divide by 2

Examples A = 199; B = 90; c = a & b = 66; c = a | b = 233; 1 1 1 1 1 1 1

Logical Operators Logical operators are useful when we want to test multiple conditions AND OR NOT

&& - Logical AND All the conditions must be true for the whole expression to be true Example: if (a == 1 && b == 2 && c == 3) means that the if statement is only true when a == 1 and b == 2 and c == 3 e1 e2 Result = e1 && e2 1 e1 e2 Result = e1 && e2 false true

|| - Logical OR The truth of one condition is enough to make the whole expression true Example: if (a == 1 || b == 2|| c == 3) means the if statement is true when either one of a, b or c has the right value e1 e2 Result = e1 || e2 1 e1 e2 Result = e1 || e2 false true

! - Logical NOT Reverse the meaning of a condition Example: if (!(radius > 90)) Means if radius not bigger than 90. e1 Result = !e1 false true e1 Result = !e1 1

Assignment Operators Assignment operators are used to combine the '=' operator with one of the binary arithmetic or bitwise operators Example : c = 9; Operator Expression Equivalent Statement Results += c += 7; c = c + 7; c = 16 -= c -= 8; c = c – 8; c = 1 *= c *= 10; c = c * 10; c = 90 /= c /= 5; c = c / 5; %= c %= 5; c = c % 5; c = 4 &= c &= 2 ; c = c & 2; c = 0 ^= c ^= 2; c = c ^ 2; c = 11 |= c |= 2; c = c | 2; <<= c <<= 2; c = c << 2; c = 36 >>= c >>= 2; c = c >> 2; c = 2

Conditional Operator The conditional operator (?:) is used to simplify an if/else statement Condition ? Expression1 : Expression2; The statement above is equivalent to: if (Condition) Expression1; else Expression2; Which are more readable?

Conditional Operator Example: if/else statement: if (total > 12) grade = ‘P’; else grade = ‘F’; conditional statement: (total > 12) ? grade = ‘P’: grade = ‘F’; OR grade =( total > 12) ? ‘P’: ‘F’;

Conditional Operator Example: if/else statement: if (total > 12) printf(“Passed!!\n”); else printf(“Failed!!\n”); Conditional Statement: printf(“%s!!\n”, total > 12 ? “Passed”: “Failed”);

Precedence Rules The rules specify which of the operators will be evaluated first For example: x = 3 * a - ++b%3; Precedence Operator Associativity Level 1 (highest) () left to right 2 unary right to left 3 * / % 4 + - 5 (lowest) = += -= *= /= %=

Precedence Rules how would this statement be evaluated? : x = 3 * a - ++b % 3; What is the value for X, for: a = 2, b = 4? x = 3 * a - ++b % 3; x = 3 * a - 5 % 3; x = 6 - 5 % 3; x = 6 – 2; x = 4;

Precedence Rules If we intend to have a statement evaluated differently from the way specified by the precedence rules, we need to specify it using parentheses ( ) x = 3 * a - ++b % 3; Consider having the following statement: x = 3 * ((a - ++b)%3); the expression inside a parentheses will be evaluated first The inner parentheses will be evaluated earlier compared to the outer parentheses

Precedence Rules how would this statement be evaluated? x = 3 * ((a - ++b)%3); What is the value for X, for: a = 2, b = 4? x = 3 * ((a - ++b) % 3); x = 3 * ((a - 5) % 3); x = 3 * ((-3) % 3); x = 3 * 0; x = 0;