Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Similar documents
Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

A flow chart is a graphical or symbolic representation of a process.

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

JAVA OPERATORS GENERAL

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Fundamentals of Programming

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Fundamental of Programming (C)

ME 461 C review Session Fall 2009 S. Keres

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Expression and Operator

Lecture 3. More About C

Writing Program in C Expressions and Control Structures (Selection Statements and Loops)

Part I Part 1 Expressions

Princeton University COS 333: Advanced Programming Techniques A Subset of C90

Computers Programming Course 6. Iulian Năstac

SISTEMI EMBEDDED. The C Pre-processor Fixed-size integer types Bit Manipulation. Federico Baronti Last version:

Part I Part 1 Expressions

SISTEMI EMBEDDED. The C Pre-processor Fixed-size integer types Bit Manipulation. Federico Baronti Last version:

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Work relative to other classes

SISTEMI EMBEDDED. The C Pre-processor Fixed-size integer types Bit Manipulation. Federico Baronti Last version:

SECTION II: LANGUAGE BASICS

Programming. Elementary Concepts

Informatics Ingeniería en Electrónica y Automática Industrial

Computer System and programming in C

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

The Java language has a wide variety of modifiers, including the following:

Review of the C Programming Language for Principles of Operating Systems

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following g roups:

6.096 Introduction to C++ January (IAP) 2009

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

C: How to Program. Week /Mar/05

HISTORY OF C LANGUAGE. Facts about C. Why Use C?

Arithmetic Operators. Portability: Printing Numbers

Problem Solving and 'C' Programming

COMP322 - Introduction to C++ Lecture 01 - Introduction

DEPARTMENT OF MATHS, MJ COLLEGE


Arithmetic and Bitwise Operations on Binary Data

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

Chapter 2 - Introduction to C Programming

Operators. Java operators are classified into three categories:

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Operators in C. Staff Incharge: S.Sasirekha

These are reserved words of the C language. For example int, float, if, else, for, while etc.

I Internal Examination Sept Class: - BCA I Subject: - Principles of Programming Lang. (BCA 104) MM: 40 Set: A Time: 1 ½ Hrs.

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Unit 3. Operators. School of Science and Technology INTRODUCTION

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Introduction to C Language

Topic 6: A Quick Intro To C

Mechatronics and Microcontrollers. Szilárd Aradi PhD Refresh of C

Review of the C Programming Language

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

C Programming Language (Chapter 2 of K&R) Variables and Constants

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Class B.Com. III Sem.

Prof. Navrati Saxena TA: Rochak Sachan

Programming for Engineers C Preprocessor

CSE 230 Intermediate Programming in C and C++

.Net Technologies. Components of.net Framework

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Unit-2 (Operators) ANAND KR.SRIVASTAVA

Quick Reference Guide

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

Programming for Engineers Iteration

The Arithmetic Operators

Arithmetic and Bitwise Operations on Binary Data

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CT 229. Java Syntax 26/09/2006 CT229

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Variables and literals

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Computers Programming Course 5. Iulian Năstac

Lecture 2: C Programming Basic

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

More Programming Constructs -- Introduction

Decision Making -Branching. Class Incharge: S. Sasirekha

CENG 447/547 Embedded and Real-Time Systems. Review of C coding and Soft Eng Concepts

Fundamental of C programming. - Ompal Singh

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Course Outline Introduction to C-Programming

Model Viva Questions for Programming in C lab

Operators and Expressions:

Introduction to C Final Review Chapters 1-6 & 13

CS2141 Software Development using C/C++ C++ Basics

Transcription:

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Data Types Basic Types Enumerated types The type void Derived types Types Description They are arithmetic types: (a) Integer types, (b) floating-point types They are again arithmetic types and they are used to define variables that can only assign certain discrete integer values. (keyword: enum) The type specifier void indicates that no value is available. (a) Pointer types, (b) Array types, (c ) Structure types

Integer Types Type Storage size Value range char 1 byte -128 to 127 or 0 to 255 unsigned char 1 byte 0 to 255 signed char 1 byte -128 to 127 int 2 or 4 bytes -32,768 to 32,767 or - 2,147,483,648 to 2,147,483,647 unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 long 4 bytes -2,147,483,648 to 2,147,483,647 unsigned long 4 bytes 0 to 4,294,967,295

Floating-Point Types Type Storage size Value range Precision float 4 byte 1.2E-38 to 3.4E+38 6 decimal places double 8 byte 2.3E-308 to 1.7E+308 15 decimal places long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Enumerated types (Examples) enum Boolean { false; true; Boolean b; enum Color { red; orange; yellow; green; cyan; blue; violet; Color c; enum Degree { PhD; master; bachelor; associate; Degree d;

Array An array is a collection of data elements that are of the same type (e.g., a collection of integers, collection of characters, collection of doubles). Syntax: <type> <arrayname> [<array_size>] E.g., double grade[10] = {80, 85, 60, 75, 88, 95, 69, 78, 74, 96 ; 0 1 2 3 4 5 6 7 8 9 Grade 80 85 60 75 88 95 69 78 74 96

Array (Cont ) #include <stdio.h> /* calculate the average grade */ int main() { double grade[10] = {80, 85, 60, 75, 88, 95, 69, 78, 74, 96 ; int i; // array index double AvgGrade = 0; for (i = 0; i < 10; i++) { AvgGrade = AvgGrade + grade[i]/10; printf( Average grade = %4.2f\n, AvgGrade);

Two-Dimensional Array Syntax: <type> <arrayname> [<array_x_size>] [<array_y_size>] E.g., int image[4][4]={{0,1,1,0, {1,1,0,0, {0,1,0,1,{0,0,1,1; Column 0 Column 1 Column 2 Column 3 Row 0 Row 1 Row 2 Row 3 0 1 1 0 1 1 0 0 0 1 0 1 0 0 1 1

Operators Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators

Arithmetic Operators Operator Description Example + Adds two operands. A + B = 30 Subtracts second operand from the first. A B = -10 * Multiplies both operands. A * B = 200 / Divides numerator by denumerator. % Modulus Operator and remainder of after an integer division. ++ Increment operator increases the integer value by one. -- Decrement operator decreases the integer value by one. B / A = 2 B % A = 0 A++ A--

Relational Operators Operator Description Example == Checks if the values of two operands are equal or not. If yes, then the condition becomes true.!= Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. > Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. < Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. >= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. (A == B) is not true. (A!= B) is true. (A > B) is not true. (A < B) is true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. (A <= B) is true.

Logical Operators Operator Description Example && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. Called Logical OR Operator. If any of the two operands is nonzero, then the condition becomes true.! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. (A && B) is false. (A B) is true.!(a && B) is true.

Bitwise Operators p q p & q p q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1

Bitwise Operators (Cont ) Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) = 12, i.e., 0000 1100 Binary OR Operator copies a bit if it exists in either operand. (A B) = 61, i.e., 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. (A ^ B) = 49, i.e., 0011 0001 (~A ) = -61, i.e,. 1100 0011 in 2's complement form. A << 2 = 240 i.e., 1111 0000 A >> 2 = 15 i.e., 0000 1111

Assignment Operators Operator Description Example = Simple assignment operator. C = A + B will assign the value of A + B to C += Add AND assignment operator. C += A is equivalent to C = C + A -= Subtract AND assignment operator. C -= A is equivalent to C = C - A *= Multiply AND assignment operator. C *= A is equivalent to C = C * A /= Divide AND assignment operator. C /= A is equivalent to C = C / A %= Modulus AND assignment operator. C %= A is equivalent to C = C % A <<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2 &= Bitwise AND assignment operator. C &= 2 is same as C = C & 2 ^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2 = Bitwise inclusive OR and assignment operator. C = 2 is same as C = C 2

Misc Operators Operator Description Example sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4. & Returns the address of a variable. &a; returns the actual address of the variable. * Pointer to a variable. *a;? : Conditional Expression. If Condition is true? then value X : otherwise value Y

Operator Precedence 17

Conditional Statements if (expression) statement1 else statement2 else is optional expression is evaluated execute statement1 if TRUE, statement2 if FALSE if (expression1) statement1 else if (expression2) statement2 else statement3 expression2 is evaluated if expression1 is FALSE

Conditional Example #include <stdio.h> int main() { int x = 1; if(x==1) printf( Correct.\n ); else printf( Incorrect.\n );

Switch switch (expression) { case const_expr1: statement1 case const_expr2: statement2 default: statement3 expression is evaluated, compared to const_expr Statements are executed corresponding to the first matching expression default is optional

Break in a Switch Without a break statement, the case will not end If x==0 then both y=1; and y=2; are executed switch (x) { case 0: y = 1; case 1: y = 2; break; case 2: y=3;

While and For Loops for (expr1; expr2; expr3) { statement; expr1; while (expr2) { statement; expr3; expr1; do { statement; expr3; while (expr2); Initialization and increment are built into the for loop Condition checked at the top of a for/while loop Condition checked at the bottom of a do-while loop

While Example #include <stdio.h> int main() { int i = 0; while(i < 3) { printf( %d, i); i = i + 1; Three passes through the loop: i = 0, 1, 2 Exits loop when i=3

All Built Into the For Statement #include <stdio.h> int main() { int i; for (i = 0; i < 3 ; i++) { printf( %d, i); initialization termination step

Break and Continue Break jumps to the end of a for, while, do, or case while (x > 5) { y++; if (y < 3) break; x++; Continue jumps to the next iteration of a loop while (x > 5) { y++; if (y < 3) continue; x++;

Functions /* function returning the max between two numbers*/ int max(int num1, int num2) { int result; if(num1 > num2) result = num1; else result = num2; return result; #include <stdio.h> /*function declaration*/ int max(int num1, int num2); int main() { int a = 100; int b = 200; int ret; ret = max(a,b); Function call printf( Max value is : %d\n, ret); return 0; Function definition 26

Examples bool FPGALedSet (int mask) // set the 10 LEDs based on x 000 x 3FF 0 bool HexSet(int index, int value) //set sevseg display to a 5 6 1 hex value 0 F 4 2 bool SwitchRead(uint32_t *mask) // sets a mask to the binary value of the switches 3

How to Get User Input from Command Line #include <stdio.h> int main(int argc, char *argv[]){ int i; if(argc <2){ printf("no input! "); else{ for(i=0; i<argc; i++){ printf("%s ", argv[i]); printf("\n"); return 0;

How to Generate Random Numbers #include <stdio.h> #include <stdlib.h> int main() { int c, n; printf("ten random numbers in [1,100]\n"); for (c = 1; c <= 10; c++) { n = rand() % 100 + 1; printf("%d\n", n); return 0;

Local Variables void foo () { int i;. A variable is local if it s defined inside a function They can be used only by statements that are inside that function or block of code.

Global Variables int global_i void foo () { extern int global_i;. A variable is global if it s defined outside of any function A global variable must be declared as an extern in any function using it Extern not needed if global declaration is before the function Variables can be global across files

Globals Are Dangerous void foo () { extern int global_i;. global_i = a + b c ; int bar () { extern int global_i;. x = global_i *. Global variables can propagate bugs Bug in foo can cause bar to crash Debugging can become harder Reduce modularity of code

Preprocessor Directive #define #include #undef #ifdef #ifndef #if #else #elif #endif #error #pragma Description Substitutes a preprocessor macro. Inserts a particular header from another file. Undefines a preprocessor macro. Returns true if this macro is defined. Returns true if this macro is not defined. Tests if a compile time condition is true. The alternative for #if. #else and #if in one statement. Ends preprocessor conditional. Prints error message on stderr. Issues special commands to the compiler, using a standardized method.

Preprocessor Examples #include <stdio.h> # include myheader.h #ifndef MESSAGE #endif #define MESSAGE You wish #Undef FILE_SIZE #Define FILE_SIZE 42 #ifdef DEBUG /* Your debugging statements here*/ #endif