Fundamentals of C. Structure of a C Program

Similar documents
C: How to Program. Week /Mar/05

ANSI C Programming Simple Programs

Chapter 2 - Introduction to C Programming

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

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

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Programming and Data Structures

UNIT- 3 Introduction to C++

Work relative to other classes

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

CS102: Variables and Expressions

Chapter 1 & 2 Introduction to C Language

BASIC ELEMENTS OF A COMPUTER PROGRAM

1.1 Introduction to C Language. Department of CSE

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

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Lecture 3. More About C

Basics of Java Programming

BITG 1233: Introduction to C++

Basics of Programming

JAVA Programming Fundamentals

6.096 Introduction to C++ January (IAP) 2009

Fundamental of Programming (C)

Computers Programming Course 5. Iulian Năstac

INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT. Dept. of Electronic Engineering, NCHU. Original slides are from

Differentiate Between Keywords and Identifiers

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

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

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Fundamentals of Programming

Input/Output Week 5:Lesson 16.1

Operators & Expressions

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

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

Programming in C++ 5. Integral data types

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

DEPARTMENT OF MATHS, MJ COLLEGE

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

SEQUENTIAL STRUCTURE. Erkut ERDEM Hacettepe University October 2010

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Programming for Engineers Introduction to C

Computer System and programming in C

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C++ Programming: From Problem Analysis to Program Design, Third Edition

Fundamentals of Programming Session 4

A First Program - Greeting.cpp

Basic Types and Formatted I/O

Chapter 2. Lexical Elements & Operators

C - Basic Introduction

Basic Elements of C. Staff Incharge: S.Sasirekha

Chapter 2: Overview of C. Problem Solving & Program Design in C

CC112 Structured Programming

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Number Systems, Scalar Types, and Input and Output

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

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

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++

Programming in C++ 4. The lexical basis of C++

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

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

Unit 4. Input/Output Functions

2. Numbers In, Numbers Out

Introduction to C Language

C Programming a Q & A Approach

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

3. Types of Algorithmic and Program Instructions

Introduction to Programming

Programming. C++ Basics

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Java Notes. 10th ICSE. Saravanan Ganesh

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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:

Lecture 02 C FUNDAMENTALS

Data types, variables, constants

CSC 1107: Structured Programming

2. Numbers In, Numbers Out

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

Reserved Words and Identifiers

Fundamental of C programming. - Ompal Singh

Creating a C++ Program

Have the same meaning as variables in algebra Single alphabetic character Each variable needs an identifier that distinguishes it from the others a =

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

Introduction to C# Applications

Objectives. In this chapter, you will:

First of all, it is a variable, just like other variables you studied

Unit 3. Operators. School of Science and Technology INTRODUCTION

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

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

Stream Model of I/O. Basic I/O in C

CSCI 171 Chapter Outlines

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS )

Fundamentals of Programming

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Transcription:

Fundamentals of C Structure of a C Program 1

Our First Simple Program Comments - Different Modes 2

Comments - Rules Preprocessor Directives Preprocessor directives start with # e.g. #include copies a file into the source code before compilation 2 forms..we will usually see the first #include <systemfilename> #include undefinedfilename Within : personal file in your own directory 3

We will almost always use #include <stdio.h> stdio.h is the standard input/output header Contains code required for I/O (Input/Output).hfiles are header files Includes header ; The.obj part on Linking NO code is generally included except on linking Header files contain definitions The function : main() ALL Programs must have a main() function. Later we will have add other functions. Different Formats: main( ) int main (void ) ***The book likes this void main(void) int main( ) 4

main( ) End with, void main(void) return; ************************** int main (void ), int main( ) End with return 0; Back To Our First Program 5

Variables A Variable is a block of memory that stores data. A variable has a particular Type, i.e. it stores a particular kind of data A variable is named with an appropriate Identifier (or Name) Suppose we have a variable declared as follows: int number_of_days This reserves a block of memory which holds an integer 6

Schematic view: number_of_days 365 In the course of the program we might want to change the value in the variable. So that later we might want: number_of_days 7361 The actual view of memory: 4 bytes number_of_days 01100000 11001010 10010100 00100111 So a variable takes a fixed number of bytes in memory 7

Rules for Naming Variables 1. First character: alphabetic or underscore 2. Consist only of alphanumeric or underscores 3. Only first 31 characters count 4. Cannot duplicate a reserved word Legal/Illegal Variable Names Use meaningful names Legal a student_name salary time_of_day Illegal $sum 2names stdnt number int 8

Standard C Data Types Primitive C Data Types Data Type void character integer floating point C-Implementation void char (1 byte) unsigned short int (1 byte) unsigned int (2 or 4 bytes) unsigned long int (4 or 8 bytes) short int (1 or 2 byte) int (2 or 4 bytes) long int (4 or 8 bytes) float (4 bytes) double (8 bytes) long double (10 bytes) 9

Variables : Declaration Variables : Initialization How we put a value in a variable At compile time in the declaration: e.g. int x=5; At run time by an assignment: e.g. x =5; At run time by an input statement: e.g.scanf( %d,&x); 10

No variable is initialized until you do so! You can initialize a variable in the declaration char code = B ; char letter = B ; int i = 0; int age = 65; float pie = 3.1415; float salary 27.57; double variable2 = 3.1415926535; Special Characters ASCII Character Null character Alert (bell) Backspace Horizontal tab Newline Vertical Tab Symbolic Name \0 \a \b \t \n \v 11

Special Characters ASCII Character Form Feed Carriage return Single quote Double Quote Backslash Symbolic Name \f \r \ \ \\ Strings : Constants 12

Preprocessing : #define Defines constants #define name token Replaces the name with the token Example: #define PI 3.1415926535 #define SIZE 1000 Syntax for Define : #define Noequals sign Nosemicolon at the end 13

Constants To define a constant define a variable (usually, U.C.) with keyword: const This is how it works: const float PI = 3.1415926; This does NOT work: const float PI; PI = 3.1415926; /* not allowed to change it */ May be collected into a header file for general use Standard Input and Output 14

To OUTPUT you require #include <stdio.h> printf(format string, data list); Field specifiers are inside the format string i.e. Controls how the data looks when printed Standard printf statements #include <stdio.h> void main( ) /* This codes prints the values of two variables */ { int a = 57; int b = 145; } printf( "%d\n%d\n", a,b); return; 15

What happened? The statements int a = 57; a 57 int b = 145; b 145 The statement printf( "%d\n%d\n", a, b); prints: 57 145 Field Specifiers %<flag><minimum width><precision><size>code Codes: Size none Code c Type char Example %c h d short int %hd none d int %d l or L d long int %Ld none f float %f none f double %f L f long double %Lf 16

Specification of Width Value %d %4d 12 123 1234 12345 12 123 1234 12345 12 123 1234 12345 Precision specification for floats: %7.2f /* this prints the float in a field of seven characters with two characters after decimal: nnnn.dd */ 17

Another Example of printf #include <stdio.h> int main() /* This codes prints the values of two variables */ { int months = 9; float salary = 145.35; printf( "%d\n%7.2f\n", months, salary); return 0; } Another Example of printf #include <stdio.h> int main( ) /* This codes prints the values of two variables */ { int months = 9; float salary = 145.35; printf( "the number of months is%4d\nthe salary is%7.2f\n", months,salary); return 0; } 18

The output the number of months is 9 the salary is 145.35 Input: Getting information into memory: (reading) Requires: #include <stdio.h> scanf(format string, address list); Again : Field specifiers inside the format string 19

Standard scanf Statements scanf(format string, address list); scanf( %d%f, &age, &weight); At keyboard type 23 60.75 Result: 60.75 weight age 23 Field Specifiers %<flag><maximum width><size>code Remember : There is no precision issue here!!! Codes: Size none h none l or L none none L Code c d d d f f f Type char short int int long int float double long double Example %c %hd %d %Ld %f %f %Lf 20

Rules for scanf formats Addresses of a variable are specified with: &variablename A variety of rules apply to conversion Rules for scanf formats 1. Initial whitespace is ignored (except %c) 2. The conversion operation process until: i. End of file is reached ii. Maximum characters are processed iii. A whitespace character is found after a digit iv. An error is detected 21

Rules for scanf format strings 1. A field specifier for each variable 2. Other characters must be exactly matched 3. Cannot end format string with whitespace Examples of scanf scanf( %d%d%d%c,&a,&b,&c,&d); scanf( %d%d%d %c,&a,&b,&c,&d); scanf( %-8d%-8d%d,&a,&b,&c); %-8d /* left justify flag */ 22

Working with the variables: We want to operate on variables: e.g add two variables or subtract them. An Expression: rateofpay*hours tax e.g., + plus - minus * multiply / divide % mod Operators You create expressions out of operators. 23

Some Expressions 35 2 * 3 + 4 23 + b * 6 -salary Use parenthesis to clarify complicated expressions: (food + drinks)*(1+gst+pst) Assignment Assignment expressions evaluate to the expression on the right of the assignment operator. 24

Simple Assignment Contents of Variable x Contents of Variable y Expression Value of Expression Result of Expression 10 5 x=y+2 7 x = 7 10 5 x=x/y 2 x=2 10 5 x=y%4 1 x=1 Operator Precedence Operators have a built in order of precedence which is over ridden by using parenthesis 1+2*3+4 answer 11 1*2 + 3*5 answer 17-5*6+2 answer -28 25

Operators precedence (on the same level they are equal) 1. ( ) takes precedence 2. unary minus -7 unary plus +3 3. * Multiply / Divide 4 % Modulus 5. + add - subtract Examples Operators Examples of C statements using these : The following is a program fragment only int i, j,k, l, m; i = j + k; i = j + k * l / m; /* Here i gets the value j + (k*l/m) */ i = j * k + l * m /* Here i gets the value (j*k) + (l*m) */ 26

Examples Operators Examples of C statements using these : There is one division operator for integer and float but it means different things. 2 / 5 0 2.0 / 5.0 0.4 % is the modulus (remainder) operation 5 % 2 1 2 % 5 2 Unary operator + and - +a evaluates to the contents of a -a evaluates to the negative contents of a 27

Unary Expressions Contents of x Before Expression Value of Expression Contents of x After 10 ++x 11 11 10 --x 9 9 Unary operator ++ and -- Post-increment and decrement i++ i-- /*First use the value ; then do operation*/ Pre-increment and decrement ++i --i /*First do operation; then use the value */ 28

Unary operator ++ and -- Examples for int i, j, k; i=1; i++; /* i 2 */ j = i++ ; /*j 2 and then i 3 j =++i ; /* i 4 and then j 4 j = i-- /* j 4 and then i 3 Note that i++ and i=i+1 are equivalent Note that i-- and i=i-1 are equivalent Binary Compound Operators Often a variable is changed as follows : i = i + 5; /* Take the value of i add 5 and put the result back into the variable i*/. Leads to new assignment operators += -= *= /= %= i = i + 1; same as i += 1; j = j * k; same as j *= k ; 29

Compound Assignment Contents of Variable x Contents of Variable y Expression Value of Expression Result of Expression 10 5 x *= y 50 x = 50 10 5 x /= y 2 x = 2 10 5 x %= y 0 x = 0 10 5 x += y 15 x = 15 10 5 x -= y 5 x = 5 A Simple Program #include <stdio.h> int main( void ) { double x, y,z ; printf("pls. input two real numbers:\n") ; scanf("%f%f",&x,&y); z = x + y; } printf("x=%6.2f y=%6.2f z= %6.3f \n",x,y,z); return(0); 30

A Simple Program The OUTPUT >Please input two real numbers: 23.4 45.6 x= 23.40 y= 45.60 z=69.000 /* A simple program to average 3 numbers*/ #include <stdio.h> int main(void) { float number1,number2,number3,sum,average; printf("\n Please enter number1. "); scanf("%f",&number1); printf("\n Please enter number2. "); scanf("%f",&number2); printf("\n Please enter number3. "); scanf("%f",&number3); sum = number1+number2+number3; average = sum/3.0; printf("\nthe sum of %f %f and %f is= %f",number1, number2,number3, sum); printf("\nthe average is = %f\n",average); return 0; } 31

Whats the problem with the previous program? What if you wanted to average 50 numbers? It would be very clumsy to repeat 50 times. Also you have to change the program each time you have a different number of numbers. Program to calculate tax on a bill First you have to know the facts. Subtotal = food and drink PST = 0.08 GST =0.06 Tax = subtotal (PST+GST) Total = subtotal + tax 32

/* A simple program calculate restaurant bill: input: food and drink amounts output: subtotal, tax, total bill*/ #include <stdio.h> #define PST 0.08 #define GST 0.06 int main(void) { float food,drink,sum,total,tax; printf("\n Please enter food total. "); scanf("%f",&food); printf("\n Please enter drink total. "); scanf("%f",&drink); sum = food + drink; tax = sum*(gst +PST); total= sum+tax; printf("\nthe food total is $%6.2f ",food); printf("\nthe drink total is $%6.2f ",drink); printf("\n ====="); printf("\nthe subtotal is $%6.2f ",sum); printf("\nthe tax is $%6.2f ",tax); printf("\n ====="); printf("\nthe total is $%6.2f\n\n ",total); return 0; } Whats the problem with the previous program? The rule is not right. If the subtotal is less than $3.00 the no GST So we need decision possibility So we need CONTROL STRUCTURES 33

Unary Operator sizeof sizeof is an operator. It is NOT a function Evaluates to number of bytes for that item sizeof(int) sizeof(x) sizeof(3.256) 34