C Programming Basics
|
|
- Solomon West
- 6 years ago
- Views:
Transcription
1 CSE 2421: Systems I Low-Level Programming and Computer Organization C Programming Basics Presentation B Read/Study: Reek , 4, and 5, Bryant Gojko Babić 08/29/2017 C Programming Language C is a language for expressing common ideas in programming in a way that most people are comfortable with, since it is procedural not object oriented (as Java) Portable, versatile, simple, straight-forward, and has many important, yet subtle, details Reasonably close to the machine: allows direct manipulation of memory via pointers provide language constructs that map efficiently to machine instructions, not to byte code (as Java does) requires minimal run-time support appropriate for writing device drives, operating systems C has the best combination of speed, low memory use, lowlevel access to the hardware, and popularity. Presentation B 2 1
2 C Keywords You shouldn't use them for any other purpose in a C program. But, they are allowed only within double quotation marks, i.e. as a part of string literal. g. babic Presentation B 3 C Variables and Identifiers C variables are names for memory locations we write a value in them and change the value stored but we cannot erase the memory location, since some value is always there Variables names are called identifiers Choosing variable names first character must be a letter or the underscore remaining characters must be letters, numbers or underscore character Keywords (also called reserved words) are used by the C language and cannot be used as identifiers g. babic Presentation B 4 2
3 Declaring Variables in C Before use, variables must be declared Examples: int number; double weight, total; int for signed integer and could store 3, 102, 3211, -456, etc. double or float for rational numbers with a fractional component and could store 1.34, 4.0, , etc. Declaration at the beginning Immediately prior to use int main() int main() int score1, score2; int sum, score1, score2; int sum; sum = score1 + score2; sum = score1 + score 2; return 0; return 0; g. babic Presentation B 5 Assignment Statements An assignment statement changes the value of a variable total = weight + number; total is set to the sum weight and number Assignment statements (as many others) end with a semicolon The single variable to be changed is always on the left of the assignment operator = On the right of the assignment operator can be Constants age = 21; Variables my_cost = your_cost; Expressions circumference = diameter * ; The = operator in is not an equal sign, e.g. this legal number = number + 3; g. babic Presentation B 6 3
4 Initializing Variables Declaring a variable does not give it a value Giving a variable its first value is initializing the variable Variables can be initialized in assignment statements double mpg; mpg = 26.3; // declare the variable // initialize the variable Declaration and initialization can be combined using two methods: double mpg = 26.3, area = 0.0, volume; int number = -20, i, j; g. babic Presentation B 7 Integers and Real Numbers Numbers of type int are stored as exact values Type int does not contain decimal points Examples: Numbers of type double (or float) may be stored (sometimes) as approximate due to limitations on a number of significant digits that can be represented. Type double or float can be written in two ways: conventional notation Examples: exponent or scientific notation Examples: 3.41e1 means e17 means e-6 means g. babic Presentation B 8 4
5 Machine has word size Nominal size of integer-valued data Including addresses Machine Word Some current machines use 32 bits (4 bytes) words Limits addresses to 4G-1; Why? Becoming too small for memory-intensive applications High-end systems use 64 bits (8 bytes) words Potential address space 1.8 X bytes x86-64 machines support 48-bit addresses: 256 Terabytes Machines support multiple data formats Fractions or multiples of word size Always integral number of bytes bryant Presentation B 9 Word-Oriented Memory Organization 32-bit 64-bit words words Bytes Address Address specifies a byte locations Address of first byte in word Addresses of successive words differ by 4 (32-bit) or 8 (64-bit) bryant Presentation B Addr = 0000?? Addr = 0004?? Addr = 0008?? Addr = 0012?? Addr = 0000?? Addr = 0008??
6 C Basic Data Types Four basic data types in C integers, floating-point values, pointers, and aggregate types: arrays and structures. C Data Type Typical 32-bit Intel IA32 x86-64 char short int int Sizes of all data types are given in bytes long int long long int float (6-7 digit precision) double (15 digit precision) long double 8 10/12 10/16 pointer bryant Presentation B 11 (ClassEx1) Example with Basic I/O #include<stdio.h> Example run: int main() alpha ~/Cse2421> ClassEx1 Enter integer and real: i1= 34 f1= int i1; New i1= 17 f1=7.99 float f1; alpha ~/Cse2421> printf("enter integer and real: "); scanf ("%d %f", &i1, &f1); // do not forget & before variables printf ("i1= %d f1=%f", i1, f1); // no & i1=f1 +10; printf ("\nnew i1= %d f1=%.2f", i1, f1); /* f1 will be printed with 2 decimals */ g. babic Presentation B 12 6
7 Arithmetic Operators Arithmetic is performed with operators: + for addition, - for subtraction, * for multiplication, / for division An operand is a number or variable used by the operator Arithmetic operators can be used with any numeric type including char Result of an operator depends on the types of operands If both operands are int, the result is int If one or both operands are float, the result is float e.g., division with at least one operator of type float produces the expected results. float divisor = 3, dividend = 5, quotient; quotient = dividend / divisor; quotient = Result is the same if either dividend or divisor is int Integer division by zero? Float/double division by zero? g. babic Presentation B 13 Division of Integers Be careful with the division operator! Integer division discards the fractional part! int / int produces an integer result (true for variables or numeric constants) int dividend = 5, divisor = 3; float quotient; quotient = dividend / divisor; The value of quotient is 1.0, not % operator gives the remainder from integer division int dividend=5, divisor=3, remainder; remainder = dividend % divisor The value of remainder is 2 Arithmetic operators have the usual algebraic precedence with left to right evaluation in the case of the same precedence. g. babic Presentation B 14 7
8 Use spacing to make expressions readable. x+y*z or x + y * z Arithmetic Expressions Use parentheses to alter the order of operations x + y * z ( y is multiplied by z first) (x + y) * z ( x and y are added first) Some expressions occur so often that C contains to shorthand operators for them: count = count + 2; count += 2; Similar operators: -=, *=, /=, %= Increment operator ++ adds 1 to the value of a variable x++; is equivalent to x = x + 1; Decrement operator -- subtracts 1 from the value of a variable x--; is equivalent to x = x 1; g. babic Presentation B 15 Arithmetic Expressions: Examples g. babic Presentation B 16 8
9 Introductory Assignment B Write C program (Size.c), that prints sizes in bytes of all C data types (given in B11) in a system the program would run. Compile your code once as usual and once with switch m32. When you run each of two executable codes, you should be getting different outputs. In file Readme provide outputs of your program and comment them. Hint: Read Reek sections Before Wednesday class, submit Size.c (at the beginning provide compilation commands used) and Readme using the following: submit c2421ac int2 Size.c Readme Turn in a hard copies of Size.c and Readme at the beginning of the class on Wednesday. g. babic Presentation B 17 Relational Operators g. babic Presentation B 18 9
10 Used to compare two values > >= < <= ==!= Relational Operators (cont.) Precedence order given above; then left to right. Arithmetic operators have higher precedence than relational operators. When you perform comparison with the relational operators, the operator will return 1 if the comparison is true, or 0 if the comparison is false. e.g. the check 2 == 2 evaluates to 1. e.g. printf( %d, 2==1); what will be printed? g. babic Presentation B 19 While Loop The Expression is checked first and only if true the body is executed. The Expression is checked again after the body has been executed and only if true the body is executed again. Expression Expression g. babic Presentation B 20 10
11 (ClassEx2) Example: While Loop /* print Fahrenheit-Celsius table for fahr = 0, 20,..., 300 where the conversion factor is C = (5/9) x (F-32) */ int main() float celsius; int fahr, lower, upper, step; lower =0; // lower limit of temperature scale upper = 300; // upper limit step = 20; // step size fahr = lower; while (fahr <= upper) celsius = 5 * (fahr-32) / 9; // problem? printf("%d %.2f\n", fahr, celsius); fahr = fahr + step; return 0; Presentation B 21 C does not have a Boolean type and int is used instead C treats integer 0 as FALSE and any non-zero value as TRUE Example: i = 0; while (i 10) /*body*/ i=i+1; // probably found inside the body The body will execute until the variable i takes on the value 10 at which time the expression (i 10) will become false (i.e. 0). g. babic Boolean Type Presentation B 22 11
12 Logical (Boolean) Operators Logical Operators are: &&,, and! and, or, and not (logical negate), respectively Boolean expressions are evaluated using values from the truth tables below g. babic Presentation B 23 Logical Expression Logical expressions can be combined into complex expressions && is and operator true only if both expressions are true e.g.: ( (2 < x) && (x < 7) ) True only if x is between 2 and 7; inside parentheses are optional but enhance meaning is or operator true if either or both expressions are true e.g: ( ( x = = 1) ( x = = y) ) True if x contains 1 or/and if x contains the same value as y! is not operator negates any Boolean expression!(x = = y) True if x is NOT equal to y! operator may make expressions difficult to understand, thus use only when appropriate Relational operators have higher precedence than logical operators && and II and lower precedence than! g. babic Presentation B 24 12
13 Short-Circuit Evaluation Some Boolean expressions do not need to be completely evaluated, e.g. the value of the expression (x >= 0) && ( y > 1) or (x >= 0) ( y > 1) can be determined by evaluating only (x >= 0) C uses the above approach called short-circuit evaluation Short-circuit evaluation can be used to prevent run time errors, such as in this example: if ((kids!= 0) && (pieces / kids >= 2) ) printf( \neach child may have two pieces! ); If the value of kids is zero, short-circuit evaluation prevents evaluation of (pieces / 0 >= 2), since integer division by zero causes a run-time error. g. babic Presentation B 25 Problems with! The expression (! time > limit ), with limit = 60, is evaluated as (!time) > limit If time is an int with value 36, what is!time? False! Or zero since it will be compared to an integer The expression is further evaluated as: 0 > limit false The intent of the previous expression was most likely the expression (! ( time > limit) ) which evaluates as: (! ( false) ) true Before using the! operator see if you can express the same idea more clearly without the! operator g. babic Presentation B 26 13
14 If-Else Statement Expression Expression g. babic Presentation B 27 Keywords that are very important to looping are break and continue. break will exit the most immediately surrounding loop regardless of what the conditions of the loop are. break is useful if we want to exit a loop under special circumstances. continue is another keyword that controls the flow of loops. If you are executing a loop and hit a continue statement, the loop will stop its current iteration, update itself (in the case of FOR loops) and begin to execute again from the top. Essentially, the continue statement is saying "this iteration of the loop is done, let's continue with the loop without executing whatever code comes after me. g. babic Break and Continue Statements Presentation B 28 14
15 (ClassEx3) Example: if-else, break & continue #include <stdio.h> Guessing a factor of MAGIC integer #define MAGIC 100 int main() int i=5, fact, quotient, success=0; while (i--) // What is this? printf("guess a factor of MAGIC larger than 1: "); scanf("%d",&fact); if (fact<2) printf("you provided illegal number. Try again.\n"); continue; quotient = MAGIC % fact; if (0==quotient) printf("you got it!\n"); success=1; break; else printf("sorry,you missed it. Try again.\n"); if (success==0)printf ("You exhausted all your tries"); g. babic Presentation B 29 For Loop For loop is designed for tasks such as adding numbers in a given range and sometimes it is more convenient to use than a while loop But, a for loop does not do anything a while loop cannot do sum = 0; n = 1; while(n <= 10) // this while loop adds numbers 1 to 10 sum = sum + n; n++; sum = 0; for (n = 1; n <= 10; n++) //this for loop does the same as above sum = sum + n; The for loop uses the same components as the while loop but in a more compact form. g. babic Presentation B 30 15
16 For Loop with a Multistatement Body All expressions inside for statement often contain more complex expressions: for (x = sqrt(y); x < z+ 1000; x= pow(y,3.3)).. pow and sqrt are two functions from math library g. babic Presentation B 31 (ClassEx1A) Example with Basic I/O #include<stdio.h> int main() Cse2421> ClassEx1A Enter one integer and one rational: int i1; i1dec= 201 i1hex= C9 f1= float f1; Newi1dec= 44 Newi1hex = 2C f1=34.06 printf("enter one integer and one rational: "); scanf ("%d %f", &i1, &f1); // do not forget & before variables printf ("i1dec= %d i1hex= %X f1=%f", i1, i1, f1); // no & i1=f1 +10; printf ("\nnewi1dec= %d Newihex= %X f1=%.2f", i1, i1, f1); g. babic Presentation B 32 16
17 Goto Statement Goto plus a labeled statement goto label ; label: statement ; A statement labeled with label is meaningful only to a goto statement and in any other context, a labeled statement is executed without regard to its label, i.e. it is ignored. A label must reside in the same function as goto and can appear before only one statement in the same function. The set of label names following a goto has its own name space so the names do not interfere with other identifiers. It is good programming style to use the break and continue statement in preference to goto whenever possible. However, since the break statement only exits from one level of the loop, a goto may be necessary for exiting a loop from within a deeply nested loop. Presentation B 33 #include <stdio.h> int main() int i, j; for ( i = 0; i < 10; i++ ) Example: goto Statement In this example, a goto statement transfers control to the point labeled stop when i equals 5. printf( "Outer loop executing. i = %d\n", i ); for ( j = 0; j < 3; j++ ) printf( " Inner loop executing. j = %d\n", j ); if ( i == 5 ) goto stop; printf( "Loop exited. i = %d\n", i ); // This will never execute stop: printf( "Jumped to stop. i = %d\n", i ); return 0; Presentation B 34 17
18 Common Pitfalls Using = instead of == Example: if ( x == 3) // This is probably correct The compiler will also accept the following: if (x = 3) // This is probably wrong? but stores 3 in x instead of comparing x and 3 and since the result is 3 (non-zero), the expression is always true. Also, be careful translating inequalities to C e.g. if x < y < z should be translated into C as if ( ( x < y ) && ( y < z ) ) NOT as if ( x < y < z ) and compiler will not indicate an error g. babic Presentation B 35 (CommonPitfals) Common Pitfalls Program #include <stdio.h> void main() int x=2, y=15, z=9; printf("x= %d y= %d z= %d\n", x, y, z); if(x=5) printf("x equals 5\n"); if(x<y<z) printf("x<y<z true"); else printf("x<y<z not true"); printf("\nx= %d y= %d z= %d\n", x, y, z); Output: x= 2 y= 15 z= 9 x equals 5 x<y<z true x= 5 y= 15 z= 9 g. babic Presentation B 36 18
19 Do-While Loop A do-while loop is executed at least once. The body of the loop is first executed. The expression is checked after the body has been executed. Expression Expression g. babic Presentation B 37 Char Data Type Declare a variable letter of type char: char letter; This type variables are mostly used to store ASCII characters Character constants are enclosed in single quotes char letter = 'a ; // internally 97 Variables of type char are 8-bit integers, that can be used in any type of expression (arithmetic, relational or logical) as 32- bit integers we have used so far, e.g. letter=letter-32; // letter now has value 65 == A Always keep in mind distinction between a and a. 'a' is a value of type character "a" is a string of 2 characters containing character a followed by null character. g. babic Presentation B 38 19
20 (CharRead) Scanf and Printf with Char Variable int main() char c1, c2; printf("enter two chars:"); scanf("%c %c", &c1, &c2); printf("c1%%c= %c c1%%d= %d c2%%c= %c c2%%d= %d", c1, c1, c2, c2); alpha ~/Cse2421> CharRead Enter two chars:3 8 c1%c= 3 c1%d= 51 c2%c= 8 c2%d= 56 Note: scanf takes the first character entered (even if it is whitespace, because of no space in front) for its first char variable and then for the second char variable (because of a space between two %c) skips all whitespace characters until printable character is found. g. babic Presentation B 39 (CharRead2) Scanf and Printf with Char Variable int main() char c1, c2; printf("enter two chars:"); scanf("%c%c", &c1, &c2); printf("c1%%c= %c c1%%d= %d c2%%c= %c c2%%d= %d", c1, c1, c2, c2); alpha ~/Cse2421> CharRead2 Enter two chars:3 8 c1%c= 3 c1%d= 51 c2%c= c2%d= 32 Note: scanf takes the first character entered (even if it is whitespace, because of no space in front) for its first char variable and then for the second char variable (because of no space between two %c) the next character even if it is whitespace character. g. babic Presentation B 40 20
21 Introductory Assignment C Since C does not have exponentiation operator, your assignment is to write a C program (in file power.c), that accepts on input a rational number X (0<=X<=100.) and an integer A (0 <= A <=30) and then it calculates and prints results of X A as float. Check if each inputs is in a range. You may use the function pow only to check correctness of results your program provides. In file Readme provide outputs of your program for small, medium and large numbers and comment them. Before Thursday class, submit power.c and Readme using: submit c2421ac int3 power.c Readme Turn in a hard copy of the power.c and Readme at the beginning of Thursday class. g. babic Presentation B 41 (CharRead1) Scanf and Printf with Char Variable #include<stdio.h> int main() char c1, c2, c3; alpha ~/Cse2421> CharRead1 Enter two chars:1 2 3 c1%c= 1 c1%d= 49 c2%c= 2 c2%d= 50 Enter one more char: c3%c= c3%d= 32 printf("enter two chars:"); scanf("%c %c", &c1, &c2); printf("c1%%c= %c c1%%d= %d c2%%c= %c c2%%d= %d", c1, c1, c2, c2); printf("\nenter one more char:"); scanf("%c", &c3); printf("\nc3%%c= %c c3%%d= %d", c3, c3); g. babic Presentation B 42 21
22 Switch Statement switch (expression) case constant_1: Statement_Sequence_1 case constant_2: Statement_Sequence_2... case constant_n: Statement_Sequence_n default: Default_Statement_Sequence The expression must return one of integer types, including char. The value returned is compared to the constant values after each case and when a match is found, the sequence for that case is executed, following by execution of all sequences below that one. If no match, default sequence executed. 43 Usual Usage of Switch Statement switch (expression) case constant_1: Statement_Sequence_1 break; case constant_2: Statement_Sequence_2 break;... case constant_n: Statement_Sequence_n break; default: Default_Statement_Sequence The break statement ends the switch-statement Note: Default case is always optional; If there is no default, nothing happens when there is no match. g. babic Presentation B 44 22
23 (Switch) Example: Switch char grade; printf("enter your midterm grade:"); scanf("%c", &grade); switch (grade) case 'A': printf("excellent."); break; case 'B': printf("very good."); break; case 67: printf("passing."); break; case 'D': case 'F': printf("not good, study more."); break; default: printf("that is not a possible grade."); g. babic Presentation B 45 Precedence Rules Within a pair of parenthesis, the precedence of operations is: relational operations relational operations Operators with higher precedence performed first Binary operators with equal precedence performed left to right Unary operators of equal precedence are performed right to left The expression (x+1) > 2 (x + 1) < -3 is equivalent to ( (x + 1) > 2) ( ( x + 1) < -3) and is also equivalent to x + 1 > 2 x + 1 < - 3 g. babic Presentation B 46 23
24 More on Increment Operator i++ returns the current value of i, then increments i; an expression using i++ will use the value of i BEFORE it is incremented ++i increments i first and returns the new value of i; an expression using ++i will use the value of number AFTER it is incremented i has the same value after either version! Example: int i1 = 3, i2; i2 = 2 * (i1++); printf( i1= %d i2= %d, i1, i2); Output i1= 4 i2= 6 i1 = 3; i2 = 2 * (++i1); printf( i1= %d i2= %d, i1, i2); Output i1= 4 i2= 8 Same applies to the decrement operator -- g. babic Presentation B 47 Nested if-else statements Consider the following example: if (fuel_gauge_reading < 0.75) if (fuel_gauge_reading < 0.25) printf( Fuel very low. Caution!\n ); else printf("fuel over 3/4. Don't stop now!\n ); This would compile and run, but produce wrong results. The compiler pairs the "else" with the nearest previous "if Correct would be (using braces): if (fuel_gauge_reading < 0.75) if (fuel_gauge_reading < 0.25) prinff("fuel very low. Caution!\n ); else printf("fuel over 3/4. Don't stop now!\n ); g. babic Presentation B 48 24
25 More Boolean Examples Operator Operator's Name Example Result && AND 3>2 && 3>1 1(true) && AND 3>2 && 3<1 0(false) && AND 3<2 && 3<1 0(false) OR 3>2 3>1 1(true) OR 3>2 3<1 1(true) OR 3<2 3<1 0(false)! NOT!(3==2) 1(true)! NOT!(3==3) 0(false)! ( 2 0 ) Answer: 0! ( 2 5 && 0 ) Answer: 0 (and is evaluated before or)! ( ( 2 5 ) && 0 ) Answer: 1 (Parenthesis are useful) Presentation B 49 Named Constants and Constant Variables Number constants used throughout a program may be difficult to find and change when needed Constants may be named using #define directive, so they have meaning and allow us to change all occurrences simply by changing the value of the constant Example: # define MAX_ELEMENTS 100 //no semicolon declares named conctant MAX_ELEMENTS equal to 100 It is common to name constants with all capitals, they are usually declared outside main block. const int Window = 10; declares int variable named Window that can t be changed by the program (although it is a variable) Useful for using at places where only variables can be used, e.g. function declarations and function call g. babic Presentation B 50 25
26 Introductory Assignment D A number x is said to be prime if x is at least 2, and the only proper factors of x are itself and 1. So the first few primes are 2, 3, 5, 7, 11, 13, 17, 19, 23, etc. 4 or 6 or 8 isn't prime, since each is divisible by 2. And so on. In this assignment, you are to code a program prime.c to do the following: Prompt the user for input of a positive integer (call it X) greater than 1 and less than 100,000. Check if input is in a range. Generate and print all prime numbers between 2 and X (both inclusive). For example if the user enters 42 then the output should be: There are 13 prime numbers from 2 to 42 In file Readme provide output of your program for one large number on input. Submit before Friday class: submit c2421ac int4 prime.c Readme Turn in a hard copy of prime.c at the beginning of Friday class. g. babic Presentation B 51 26
Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2
More informationChapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments
Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights
More informationChapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and
More informationChapter 2. C++ Basics
Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables
More informationChapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Copyright 2011 Pearson Addison-Wesley. All rights reserved.
More informationChapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering
More informationChapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
More informationC: How to Program. Week /Mar/05
1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers
More information2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants
Data types, variables, constants Outline.1 Introduction. Text.3 Memory Concepts.4 Naming Convention of Variables.5 Arithmetic in C.6 Type Conversion Definition: Computer Program A Computer program is a
More informationChapter 3. More Flow of Control
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-2 Flow Of Control Flow of control refers to the
More informationCSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018
CSE 1001 Fundamentals of Software Development 1 Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018 Identifiers, Variables and Data Types Reserved Words Identifiers in C Variables and Values
More informationData types, variables, constants
Data types, variables, constants Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic in C 2.6 Decision
More informationFundamentals of Programming
Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables
More informationC OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed
C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationA complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.
1.3a Expressions Expressions An Expression is a sequence of operands and operators that reduces to a single value. An operator is a syntactical token that requires an action be taken An operand is an object
More informationLecture 3. More About C
Copyright 1996 David R. Hanson Computer Science 126, Fall 1996 3-1 Lecture 3. More About C Programming languages have their lingo Programming language Types are categories of values int, float, char Constants
More informationChapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic
More informationC OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure
C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces
More informationBasics of Java Programming
Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement
More informationProgramming and Data Structures
Programming and Data Structures Teacher: Sudeshna Sarkar sudeshna@cse.iitkgp.ernet.in Department of Computer Science and Engineering Indian Institute of Technology Kharagpur #include int main()
More informationUsing Boolean Expressions. Multiway Branches. More about C++ Loop Statements. Designing Loops. In this chapter, you will learn about:
Chapter 3 In this chapter, you will learn about: Using Boolean Expressions Multiway Branches More about C++ Loop Statements Designing Loops Boolean Expressions Take the Value true or false Boolean Value
More informationC Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee
C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,
More informationProgramming for Engineers Introduction to C
Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines
More information9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C
Overview The C Programming Language (with material from Dr. Bin Ren, William & Mary Computer Science) Motivation Hello, world! Basic Data Types Variables Arithmetic Operators Relational Operators Assignments
More informationProgramming Lecture 3
Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements
More informationExpressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators
Expressions 1 Expressions n Variables and constants linked with operators Arithmetic expressions n Uses arithmetic operators n Can evaluate to any value Logical expressions n Uses relational and logical
More informationThe C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)
The C Programming Language (with material from Dr. Bin Ren, William & Mary Computer Science) 1 Overview Motivation Hello, world! Basic Data Types Variables Arithmetic Operators Relational Operators Assignments
More information3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.
3. EXPRESSIONS It is a sequence of operands and operators that reduce to a single value. Operator : It is a symbolic token that represents an action to be taken. Ex: * is an multiplication operator. Operand:
More informationUNIT- 3 Introduction to C++
UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage
More informationThe C++ Language. Arizona State University 1
The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationBASIC ELEMENTS OF A COMPUTER PROGRAM
BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators
More information12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.
Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started
More information3. Java - Language Constructs I
Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks
More information1 Lexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler
More informationChapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics
Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional
More informationFull file at
Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional
More informationc) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.
2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C
More informationFeatures of C. Portable Procedural / Modular Structured Language Statically typed Middle level language
1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC
More informationObjectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program
Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationChapter 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
More information2. Numbers In, Numbers Out
COMP1917: Computing 1 2. Numbers In, Numbers Out Reading: Moffat, Chapter 2. COMP1917 15s2 2. Numbers In, Numbers Out 1 The Art of Programming Think about the problem Write down a proposed solution Break
More informationChapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction
Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers
More informationIntroduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan
Introduction to C Programming Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Printing texts Adding 2 integers Comparing 2 integers C.E.,
More informationReserved Words and Identifiers
1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the
More informationUIC. C Programming Primer. Bharathidasan University
C Programming Primer UIC C Programming Primer Bharathidasan University Contents Getting Started 02 Basic Concepts. 02 Variables, Data types and Constants...03 Control Statements and Loops 05 Expressions
More informationLESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:
LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words
More informationComputer System and programming in C
1 Basic Data Types Integral Types Integers are stored in various sizes. They can be signed or unsigned. Example Suppose an integer is represented by a byte (8 bits). Leftmost bit is sign bit. If the sign
More informationAssoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine
More informationStatements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14
Statements Control Flow Statements Based on slides from K. N. King Bryn Mawr College CS246 Programming Paradigm So far, we ve used return statements and expression statements. Most of C s remaining statements
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationBASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I
BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment
More informationContents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual
Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Contents 1 Introduction...2 2 Lexical Conventions...2 3 Types...3 4 Syntax...3 5 Expressions...4 6 Declarations...8 7 Statements...9
More informationFlow of Control. Flow of control The order in which statements are executed. Transfer of control
1 Programming in C Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control
More information2. Numbers In, Numbers Out
REGZ9280: Global Education Short Course - Engineering 2. Numbers In, Numbers Out Reading: Moffat, Chapter 2. REGZ9280 14s2 2. Numbers In, Numbers Out 1 The Art of Programming Think about the problem Write
More informationInformation Science 1
Information Science 1 Simple Calcula,ons Week 09 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 8 l Simple calculations Documenting
More informationV2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed
Programming in C 1 Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control
More information\n is used in a string to indicate the newline character. An expression produces data. The simplest expression
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationFull file at C How to Program, 6/e Multiple Choice Test Bank
2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)
More informationCS313D: ADVANCED PROGRAMMING LANGUAGE
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting
More information3. Java - Language Constructs I
Names and Identifiers A program (that is, a class) needs a name public class SudokuSolver {... 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations,
More informationThese are reserved words of the C language. For example int, float, if, else, for, while etc.
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 a sequence of letters and digits, but must start with a letter.
More informationChapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:
Java Programming, Eighth Edition 2-1 Chapter 2 Using Data A Guide to this Instructor s Manual: We have designed this Instructor s Manual to supplement and enhance your teaching experience through classroom
More informationUnit-II Programming and Problem Solving (BE1/4 CSE-2)
Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite
More informationUNIT - I. Introduction to C Programming. BY A. Vijay Bharath
UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been
More informationOverview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University
Overview of C, Part 2 CSE 130: Introduction to Programming in C Stony Brook University Integer Arithmetic in C Addition, subtraction, and multiplication work as you would expect Division (/) returns the
More informationLexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine
More informationChapter 12 Variables and Operators
Chapter 12 Variables and Operators Highlights (1) r. height width operator area = 3.14 * r *r + width * height literal/constant variable expression (assignment) statement 12-2 Highlights (2) r. height
More informationA Fast Review of C Essentials Part I
A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types
More informationBy the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program
1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize
More informationOperators. Java operators are classified into three categories:
Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.
More informationQUIZ: What value is stored in a after this
QUIZ: What value is stored in a after this statement is executed? Why? a = 23/7; QUIZ evaluates to 16. Lesson 4 Statements, Expressions, Operators Statement = complete instruction that directs the computer
More informationCSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York
CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this
More informationCourse Outline. Introduction to java
Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.
More informationAN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University
AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:
More informationUse of scanf. scanf("%d", &number);
Use of scanf We have now discussed how to print out formatted information to the screen, but this isn't nearly as useful unless we can read in information from the user. (This is one way we can make a
More informationLexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a
More informationCPE 101, reusing/mod slides from a UW course (used by permission) Lecture 5: Input and Output (I/O)
CPE 101, reusing/mod slides from a UW course (used by permission) Lecture 5: Input and Output (I/O) Overview (5) Topics Output: printf Input: scanf Basic format codes More on initializing variables 2000
More informationCpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting
CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting Your factors.c and multtable.c files are due by Wednesday, 11:59 pm, to be submitted on the SoC handin page at http://handin.cs.clemson.edu.
More informationThe SPL Programming Language Reference Manual
The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming
More informationLecture 3 Tao Wang 1
Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers
More information3. Types of Algorithmic and Program Instructions
3. Types of Algorithmic and Program Instructions Objectives 1. Introduce programming language concepts of variables, constants and their data types 2. Introduce types of algorithmic and program instructions
More informationDEPARTMENT OF MATHS, MJ COLLEGE
T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,
More informationProgramming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]
Programming in C and Data Structures [15PCD13/23] 1 PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme] Course objectives: The objectives of this course is to make students
More informationObjectives. In this chapter, you will:
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 arithmetic expressions Learn about
More informationExpressions and Data Types CSC 121 Spring 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types
More informationLesson 3 Introduction to Programming in C
jgromero@inf.uc3m.es Lesson 3 Introduction to Programming in C Programming Grade in Industrial Technology Engineering This work is licensed under a Creative Commons Reconocimiento-NoComercial-CompartirIgual
More informationObject oriented programming. Instructor: Masoud Asghari Web page: Ch: 3
Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning
More informationprintf( Please enter another number: ); scanf( %d, &num2);
CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful
More informationLecture 2. Examples of Software. Programming and Data Structure. Programming Languages. Operating Systems. Sudeshna Sarkar
Examples of Software Programming and Data Structure Lecture 2 Sudeshna Sarkar Read an integer and determine if it is a prime number. A Palindrome recognizer Read in airline route information as a matrix
More informationVariables and literals
Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of
More informationLECTURE 3 C++ Basics Part 2
LECTURE 3 C++ Basics Part 2 OVERVIEW Operators Type Conversions OPERATORS Operators are special built-in symbols that have functionality, and work on operands. Operators are actually functions that use
More informationFlow Control. CSC215 Lecture
Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements
More informationn Group of statements that are executed repeatedly while some condition remains true
Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,
More information2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program
Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program
More informationOperators And Expressions
Operators And Expressions Operators Arithmetic Operators Relational and Logical Operators Special Operators Arithmetic Operators Operator Action Subtraction, also unary minus + Addition * Multiplication
More informationDisplay Input and Output (I/O)
2000 UW CSE CSE / ENGR 142 Programming I isplay Input and Output (I/O) -1 Writing Useful Programs It s hard to write useful programs using only variables and assignment statements Even our Fahrenheit to
More informationC++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.
EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic
More information