At the end of this lecture you should be able to have a basic overview of fundamental structures in C and be ready to go into details.

Similar documents
Fundamentals of Programming

Fundamental of Programming (C)

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

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

DEPARTMENT OF MATHS, MJ COLLEGE

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

Technical Questions. Q 1) What are the key features in C programming language?

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

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

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

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

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

Work relative to other classes

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Variables and Operators 2/20/01 Lecture #

SSOL Language Reference Manual

Topic 2: C++ Programming fundamentals

Basics of Java Programming

Unit 3. Operators. School of Science and Technology INTRODUCTION

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Operators. Java operators are classified into three categories:

Programming for Engineers Iteration

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

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

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

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

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Variables and literals

Course Outline Introduction to C-Programming

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

Computer Programming : C++

printf( Please enter another number: ); scanf( %d, &num2);

Computer System and programming in C

Full file at C How to Program, 6/e Multiple Choice Test Bank

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Fundamentals of Programming

Operators and Expressions:

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

UNIT- 3 Introduction to C++

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Introduction to C Final Review Chapters 1-6 & 13

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

Add Subtract Multiply Divide

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Lecture 6. Statements

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

6.096 Introduction to C++ January (IAP) 2009

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

Informatica e Sistemi in Tempo Reale

C Functions. 5.2 Program Modules in C

Bits, Words, and Integers

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

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Lecture 5 Tao Wang 1

today cs3157-fall2002-sklar-lect05 1

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

CHIL CSS HTML Integrated Language

Learning to Program with Haiku

Data Types and Variables in C language

ME 461 C review Session Fall 2009 S. Keres

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

COMP Primitive and Class Types. Yi Hong May 14, 2015

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

ISA 563 : Fundamentals of Systems Programming

The Arithmetic Operators

Procedures, Parameters, Values and Variables. Steven R. Bagley

Datatypes, Variables, and Operations

CMPT 125: Lecture 3 Data and Expressions

Numbers In, Numbers Out

CS 31: Intro to Systems Binary Arithmetic. Martin Gagné Swarthmore College January 24, 2016

Creating a C++ Program

P.E.S. INSTITUTE OF TECHNOLOGY BANGALORE SOUTH CAMPUS 1 ST INTERNAL ASSESMENT TEST (SCEME AND SOLUTIONS)

Computer Programing. for Physicists [SCPY204] Class 02: 25 Jan 2018

CpSc 1111 Lab 5 Formatting and Flow Control

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Java is an objet-oriented programming language providing features that support

Function Call Stack and Activation Records

Chapter 2: Using Data

Lecture 3. More About C

Conditionals. For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations:

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Visual C# Instructor s Manual Table of Contents

CS112 Lecture: Primitive Types, Operators, Strings

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

The C++ Language. Arizona State University 1

Arithmetic Expressions in C

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

Control Flow, Functions and Basic Linkage

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

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

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

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

Transcription:

Objective of this lecture: At the end of this lecture you should be able to have a basic overview of fundamental structures in C and be ready to go into details. Fundamental Programming Structures in C We will briefly tour the fundamental programming structures in C. This lecture is a summary and each subject covered in these notes will be discussed at length throughout the course. Data Types The following are the data types defined in C: char: a single byte that holds one character (A byte is defined as an 8-bit storage unit. One bit could be either 0 or 1. One bit is the smallest storage unit on a computer.) int: an integer number. Size depends on the machine. Typically, it is 4 bytes. float: single-precision floating number. Size depends on the machine. double: double-precision floating number. Size depends on the machine. There are also short int and long int defined for small and large integer numbers, respectively. Variables The C programming language requires you to declare the type of each variable you use. First, the type is placed, then the name of the variable is placed. A semi-column terminates the declaration. For instance: int i; double x; char ch; The first one above declares an integer, the second one declares a double-precision floating point number, and the last one declares a single byte. Note on style: Make it a habit to declare meaningful variable names, even if they end up being long. If a variable name has more than one word in it, my convention is to have the first letter of the first word lowercase and the first letter of next word uppercase. For instance, do not just declare int f; for, say, gravitational force, rather use int gravitationalforce. This style would make your programs more readable by others, and even by yourself, when you need to revisit a program you had written a long while ago.

Assignments After you declare variables, you need to explicitly assign values to them by means of an assignment statement. Never leave a variable un-initialized. An un-initialized variable in C could have any random value and can adversely impact the flow of your programs. Here is a declaration: int i; And here is an initialization: i = 10; Operators Usual arithmetic operators +, -,, and / are used for addition, subtraction, multiplication, and division. The / operator is for integer division if both operators are integers. Note that 3 / 7 would, for instance, produce 0. The % operator is for modular arithmetic. x % y would yield the remainder of division of x by y. The C language allows for shortcuts in arithmetic expressions. For instance, instead of you can write i = i + 2; i += 2; Also, incrementing an integer by 1 (i = i +1) can be expressed as i++ or ++i. Similarly, decrementing an integer could be expressed as i-- or --i. The difference between i++ and ++i is the fact that in a given expression i++ will be evaluated after the value of i is used. In the case of --i, first i will be decremented, then its value will be used. The operator == (double equal sign) is the comparison operator. For instance, a == b will evaluate to true, if a is the same as b. On the other hand, the operator!= is the inequality check. For instance, a!=b will evaluate to true if a is not the same as b. Finally, C has the comparison operators like < (less than), <= (less than or equal to), > (more than), and >= (more than or equal to). The operator && is the logical AND operator and is the logical OR operator. For instance, (a == b && c <= d) will evaluate to true if both a equals b and c is smaller

than or equal to d. Similarly, (a==b c <=d) will evaluate to true if either a is equal to b or c is smaller than or equal to d. Caution: One common mistake is to use the assignment operator = in place of equality operator ==. Some compilers detect that and some others may not be as clever. When working with integer types, one can also deal with bitwise operators: & (and), (or), ^ (xor), and ~ (not). We will discuss these at length later in the course. Control Flow The C programming language has many constructs to impact the flow of execution path in a program. We will discuss conditional statements, indeterminate loops, determinate loops, and the switch statement. Conditional statements The simplest conditional statement in C is the if-statement: if (condition is true) statement1; statement2; statementn; What this statement allows one to do is to execute a set of statements if a particular condition holds true. For instance, let s assume you are trying to get cash from your bank account at an ATM machine, your balance is N YTL and the amount you want to get is K YTL. The software in the ATM machine might be running a conditional statement as if ( K <= N) Allow the operation. The amount asked will be be reduced from the account s balance. N = N K; The more general if-statement typically has an else-block as follows: if (condition is true)

else statement_a1; statement_a2; statement_an; statement_b1; statement_bn; Definition: A block is a statement enclosed within a left and a right curly bracket. The if-statement above has two blocks, one that gets executed if the condition is true and the other gets executed if the condition is false. The scope of a variable is a block. In other words, if you define a variable, say x, in a block, it will not be recognized outside that block. (We will talk about this later too.) To give an example of the general if-statement, let s consider the bank example again. What if you do not have enough cash in your bank account? Well, in our example we will simply print out an error message. See below. if ( K <= N) Allow the operation. The amount asked will be be reduced from the account s balance. N = N K; else Do not allow the transaction. printf( Not enough cash in your account! ); Note that in this example the condition is (K <= N) which evaluates to true or false. The if-statement can be nested with multiple conditions as follows: If (condition-1) block_1;

else if (condition-2) block_2; else if (condition-n) block_n else block_n+1; An example is determining letter grades based on numerical total grade as follows: if (totalgrade >= 90) lettergrade = AA ; else if (totalgrade >=85 && totalgrade < 90) lettergrade = BA ; else if (totalgrade >=80 && totalgrade < 85) lettergrade = BB and so forth. The && sign is the logical AND operation. Remember that both operands should evaluate to true, for the condition in else-if statements to evaluate to true. Suggested exercise: Convert the code piece above to a C program such that given a total numerical grade on the command-line, your program will print the letter grade. You can use the our University s rules to determine the letter grade. Indeterminate Loops In C there are control structures that allow you to repeat statements. There are two types of repeating loops: determinate ones that you would use if you know exactly how many times you will be looping and indeterminate ones that you would use if you do not know

exactly how many times the loop should run. The example for the former is the for-loop that we had seen earlier. For the latter C has two types of while loops, one that allows the execution of the block only if a given condition is true and another that would allow the execution of the block at least once, and then, only if the condition is true. The general form of the first type of indeterminate loop is while (condition) statement1; statementn; Note that this while loop allows execution of the block zero or more times. Here is an example: consider calculating the retirement savings of a person who would contribute a specific amount of money to his/her account every year, has a specific goal for retirement sum, and an interest rate value is given. Question is, can you calculate the number of years that will be required to save the target retirement amount? See Listing 3 below for the program. It is available in my hbar account. Note that the while-loop runs until the number of years is calculated for the target retirement savings. See if you can follow this program. Variable names are chosen explicit enough for this program to be readable easily. The only new function introduced here is atof(), which converts a given string to a floating point number. #include <stdio.h> #include <stdlib.h> This program calculates the number of years that a person needs to save a specific amount of money by contributing a fixed amount every year. A constant interest rate is given. Run it as retirement target contribution interest where target is the targeted savings, contribution is the amount contributed every year, and interest is the interest rate. Author: Yuksel Gunal int main(int argc, char argv) double target; double contribution; double interest; int years;

This is the running balance as years go by. double balance; Get the variables from command line. target = atof(argv[1]); contribution = atof(argv[2]); interest = atof(argv[3]); years = 0; while (balance < target) balance = (balance + contribution) (1 + interest / 100); years = years + 1; printf("it will take %d years to save %f YTL.\n", years, target); return (0); Listing 3. Estimating the number of years it will take person to save a specific amount of money by contributing a fixed amount to his/her bank account every year. The while loop that allows execution at least once has the following form: do statement1; statementn; while (condition); Here is an example. Consider generating random numbers until you hit a number between 0.9 and 1.0: do randomnumber= (1.0 rand()) / RAND_MAX; while (randomnumber < 0.9);

rand() is a C library function that generates a random number between 0 and RAND_MAX. RAND_MAX is defined in C standard library as the maximum possible random number. We do the division in order to produce a number between 0 and 1. The do-while flow above will run until a random number between 0.9 and 1.0 is generated. In order to achieve this task, the random number should be generated at least once, so we use the do-while block. Listing 4 below has a more sophisticated example. In a do-while loop we estimate the square root of a given number. The source code is available under my account at hbar as usual. See if you can follow what this program does. Variables name are chosen long enough to imply what they stand for. #include <stdio.h> #include <stdlib.h> This program calculates the square root of a number given on command line. Run it as squareroot N where squareroot is the executable name and N is the number, the square root of which we will calculate. Author: Yuksel Gunal int main(int argc, char argv) double number; double squarerootofnumber; double newsquarerootestimate; double oldsquarerootestimate; double accuracyofsquarerootestimate = 0.0001; Get the number from command line number = atof(argv[1]); newsquarerootestimate = number / 2; do Iterate until the the last two estimates differ by 0.0001. oldsquarerootestimate = newsquarerootestimate; newsquarerootestimate = (oldsquarerootestimate + number / oldsquarerootestimate) / 2;

printf("the new estimate of square root of %f is %f \n", number, newsquarerootestimate); while (abs(oldsquarerootestimate - newsquarerootestimate) > accuracyofsquarerootestimate); squarerootofnumber = newsquarerootestimate; printf("the estimated square root of %f is %f", number, squarerootofnumber); return (0); Listing 4. A simple estimation of square root using do-while loop. Determinate Loops When one knows the number of times a particular set of statements will be executed, then one could use the for-loop, which has the following form: for(statement1; expression1; expression2) block; We have already seen an example of this kind of loop in the factorial program (see Listing 1). Note that this loop is equivalent to the following while-loop: statement1; while (expression1) block; expression2; Multiple selections the switch statement Controlling flow by multiple if/else statements could be cumbersome. An alternative is to use the switch statement in which one could define different blocks based on various integer or character values of a variable. An example is as follows: switch (choice) case 1: break; case 2:

break; case N: break; default:. break; Things to note: Depending on the value of choice, a block of statements will be executed After each block of statements defined for each case one needs to use the break statement, otherwise statements until the next break will also get executed. If listed cases do not correspond to a value of choice, then the statements under default will be executed. The switch statement only works with integer-valued expressions or constant expressions. Arrays An array in C is a collection of items of the same type. For instance, a program might need to represent the names and grades of all students taking this class. Names of students could be represented in an array of strings and numerical grades of students could be represented in an integer array. Let s consider the case of the numerical grades; this array of integer values could be declared as: int grade[n]; where N will be the number of students in class. An element of this array is referenced as grade[i] where i could be a number starting from 0 to N-1. (A common problem in C is to reference an array element by using an index i which is outside the range of 0 to N-1.) We will discuss arrays in detail later in this course.