Top Banner
ENG1410 C Programming: Topic #2 “C Programming: Variables & Identifiers Part 1” S. Areibi School of Engineering University of Guelph
59

ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Jan 10, 2022

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

ENG1410C Programming: Topic #2

“C Programming: Variables & Identifiers

Part 1”S. Areibi

School of EngineeringUniversity of Guelph

Page 2: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Topics

Introduction to C C Tokens .. C Program Structure .. Comments .. Identifiers .. C defined Types …. Variables ..

2

Page 3: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Textbook Resources

Chapter #3,

3

Page 4: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

C Tokens

Page 5: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

C is a structured programming language. It isconsidered a high-level language because it allows theprogrammer to concentrate on the problem at handand not worry about the machine that the programwill be using. That is another reason why it is used bysoftware developers whose applications have to run onmany different hardware platforms.

C Language

5

Page 6: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Keywordso These are reserved words of the C language. For example int,

float, if, else, for, while etc.

Identifierso An Identifier is a sequence of letters and digits, but must start with a

letter. Underscore ( _ ) is treated as a letter. Identifiers are case sensitive. Identifiers are used to name variables, functions etc.

o Valid: Root, _getchar, __sin, x1, x2, x3, x_1, Ifo Invalid: 324, short, price$, My Name

Constantso Constants like 13, ‘a’, 1.3e-5 etc.

Tokens in C

6

Page 7: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

String Literalso A sequence of characters enclosed in double quotes as “…”. For

example “13” is a string literal and not number 13. ‘a’ and “a” are different.

Operatorso Arithmetic operators like +, -, *, / ,% etc.o Logical operators like ||, &&, ! etc. and so on.

White Spaceso Spaces, new lines, tabs, comments ( A sequence of characters enclosed

in /* and */ ) etc. These are used to separate the adjacent identifiers,

kewords and constants.

Tokens in C

7

Page 8: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

C Structure

Page 9: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Structure of C Program

9

Page 10: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Greeting Program

10

Page 11: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Greeting Program

11

Any thing between /* …. */ is a comment

The compiler will not pay any attention to it

Comments are useful to document your programs

Page 12: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Greeting Program

12

Page 13: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Greeting ProgramOnce you compile your program and execute it, it will produce the following:

13

Page 14: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Greeting ProgramWhenever a \n is encountered a new line is printed

14

Page 15: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Comments

Page 16: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

16

Comments in C

Page 17: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

C Example: Simple

Page 18: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Your First C Program

/* A simple program that prints something */

#include <stdio.h>

main (){

printf ("Hello, world!\n");}

18

Output on the Screen Hello, world!

"The only way to learn a new programming language is by writing programs in it" [K&R]

Page 19: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

C: Identifiers

Page 20: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

One feature present in all computer languages isthe identifier.

Identifiers allow us to name data and other objectsin the program.

Each identified object in the computer is stored at aunique address.

Identifiers

20

Page 21: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Rules for Identifiers

21

An identifier must start with a letter or underscore: it may not have a space or a hyphen.

Note

C is a case-sensitive language.

Note

Page 22: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Valid vs. Invalid Names

22

Page 23: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

C: Types

Page 24: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

24

C Types

A type defines a set of values and a set of operations that can be applied on those values.

Page 25: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

C Variable Typeso The most common types are: char, int, float, and double.o Strings are arrays of characters (we’ll cover arrays later).o Declare a variable before you use it:

int x;/* declares an integer called x. Its value is not assigned. */

float y, z = 3.14159; /* declares two floating point numbers -- z is set equal to pi */

z = 4;/* now z is equal to 4 */

myVal = 2; /* This would be an error, because myVal was not yet declared */

25

Page 26: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

26

C Types: Char

Characterschar a, b, c1, c2;a = '0'; b = '\037'; c1 = 'K'; c2 = c1 + 1;

• Assigns values: 48, 31, 75, 76• The sequences '0',...,'9', 'a',...,'z', 'A',...,'Z' contain characters numbered consecutively

Castingprintf ("%c %d\n", c1, (int) c1);

• Outputs: K 75

Page 27: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

27

Char: ASCII Characters

ASCII, abbreviated from American Standard Code for Information Interchange is a 7-bit code, meaning that 128 characters (27) are defined. The code consists of 33 non-printable and 95 printable characters and includes both letters, punctuation marks, numbers and control characters.

Page 28: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

28

C Types: Char#include <stdio.h>int main() {

char c;printf("Enter a character: ");scanf("%c", &c);

// %d displays the integer value of a character// %c displays the actual characterprintf("ASCII value of %c = %d", c, c);

return 0;}

Output

Enter a character: GASCII value of G = 71

In this program, the user is asked to enter a character. The character is stored in variable c.

When %d format string is used, 71 (the ASCII value of G) is displayed.

When %c format string is used, 'G' itself is displayed.

Page 29: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

29

C Types: Char (Example)Write a program that reads from the user a lower case letter, and prints its corresponding upper case letter.

#include <stdio.h>int main() {

char lowercase;char uppercase;

printf(“Please enter a lower case letter: ");scanf("%c", &lowercase); // Since the difference between lower case and upper case is 32 uppercase = lowercase -32;// display the upper case equivalent of the lower case letterprintf(“The upper case of %c is %c", lowercase, uppercase);return 0;

}Output:Please enter a lower case letter: t

The upper case of t is T

Page 30: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

30

C Types: Integers

sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long)

Note

Page 31: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

31

C Types: int

In this program, an integer variable number is declared.

Then, the user is asked to enter an integer number. This number is stored in the number variable.

Finally, the value stored in number is displayed on the screen using printf().

#include <stdio.h>int main() {

int number;

printf("Enter an integer: "); // reads and stores inputscanf("%d", &number);// displays outputprintf("You entered: %d", number);

return 0;}

Output

Enter an integer: 25You entered: 25

Page 32: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

32

C Types: Float

sizeof (float) ≤ sizeof (double) ≤ sizeof (long double)

Note

Page 33: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

33

IEEE 754 Single PrecisionThe IEEE 754 standard specifies the single precision binary floating point as follows:

o Sign bit: 1 bito Exponent width: 8 bitso Significant precision: 24 bits

• The sign bit determines the sign of the number.• The exponent is an 8-bit unsigned integer from 0 to 255.

In baised form, an exponent value of 127 represents the actual zero. Exponents range from -126 to +127

• The true significand includes 23 fraction bits to the right of the binary point

Page 34: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

34

C Types: float/double

In this program, the user is asked to enter two numbers which are stored in variables a and b respectively.

Then, the product of a and b is evaluated and the result is stored in product.

Finally, product is displayed on the screen using printf().

#include <stdio.h>int main() {

double a, b, product;printf("Enter two numbers: ");scanf("%lf %lf", &a, &b);

// Calculating productproduct = a * b;// %.2lf displays number up to 2 decimal pointprintf("Product = %.2lf", product);

return 0;}

Output

Enter two numbers: 2.4 1.12Product = 2.69

Page 35: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

StringsStrings are '\0'-terminated arrays of char :

char s[3] = "hi"; /* invisible '\0' */char t[3] = {'h', 'i', '\0'};

String operations#include <string.h>strlen ("there"); /* returns 5 */strcpy (s, t); /* copy t to s */strcmp (s, t) /* alphabetical comparison */

35

Page 36: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

36

C Types: Strings

Here, using a for loop, we have iterated over characters of the string from i = 0 to until '\0' (null character) is encountered. In each iteration, the value of i is increased by 1.

When the loop ends, the length of the string will be stored in the i variable.

Note: Here, the array s[] has 19 elements. The last element s[18] is the null character '\n'. But our loop does not count this character as it terminates upon encountering it.

#include <stdio.h>int main() {

char s[] = "Programming is fun";int i;

for (i = 0; s[i] != '\0'; ++i);

printf("Length of the string: %d", i);return 0;

}

Output

Length of the string: 18

Page 37: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

C: Variables

Page 38: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Variables are named memory locations that have atype, such as integer or character, which is inheritedfrom their type.

The type determines the values that a variable maycontain and the operations that may be used with itsvalues.

Variables

38

Page 39: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Variables in Programming Represent storage units in a program Used to store/retrieve data over life of program Type of variable determines what can be placed in

the storage unit Assignment – process of placing a particular value in

a variable Variables must be declared before they are assigned The value of a variable can change; A constant

always has the same value

39

Page 40: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Naming Variables When a variable is declared it is given a name Good programming practices

Choose a name that reflects the role of the variable in a program, e.g.

• Good: customer_name, ss_number;• Bad : cn, ss;

Don’t be afraid to have long names if it aids in readability Restrictions

Name must begin with a letter; otherwise, can contain digits or any other characters. C is CASE SENSITIVE! Use 31 or fewer characters to aid in portability

40

Page 41: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Declaring Variables All variables must always be declared before the first

executable instruction in a C program Variable declarations are always:

var_type var_name;o int age;o float annual_salary;o double weight, height; /* multiple vars ok */

In most cases, variables have no meaningful value at this stage. Memory is set aside for them, but they are not meaningful until assigned.

41

Page 42: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Variable Declaration All variables must be declared in a C program before

the first executable statement! Examples:

42

void main(){

int a, b, c;float d;/* Do something here */

}

Page 43: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Variables: Declaration

Rules:• declarations must precede executable statements

43

Page 44: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Variables: Declaration

44

Page 45: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Variables: Declaration

Example:float x;double d = 5;int *p, i, a[100];char s[21];

Syntax:type variable_name, ... [= value];

Rules:• declarations must precede executable statements• int type may be modified by: long, short, unsigned

45

Page 46: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Variable Assignment After variables are declared, they must (should) be

given values. This is called assignment and it is done with the ‘=‘

operator. Examples:

float a, b; int c; b = 2.12; c = 200;

46

Page 47: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Variables: Initialization

47

When a variable is defined, it is not initialized. We must initialize any variable requiring prescribed data when the function starts.

Note

Page 48: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Changing Variable Values

Example:int x, y, z;x = 2;x = x + 1;

Getting Fancyy = z = 4 + 5;x += 1;++x;x++;y = x--;

Note:• assignment statements return value, which may or may not be ignored; same goes for increment statements

48

Page 49: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Variables: Example 1

49

#include <stdio.h>

// program prints a number of type intint main() {

/* Declaring a variable called “number” of type integer */int number = 4;

printf (“Number is %d”, number);return 0;

}

Output on the Screen: Number is 4

49

Page 50: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Variables: Example 2

50

#include <stdio.h>// program reads and prints the same thingint main() {

/* Declaring a variable “number” of type integer */int number ;

printf (“ Enter a Number: “); scanf (“%d”, &number);printf (“Number is %d\n”, number);return 0;

}

Output on the Screen : (1) Enter a number: 4(2) Number is 4

50

Page 51: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Variables: Example 3

51

#include <stdio.h>#include <stdbool.h>int main (void){

int integerVar = 100;float floatVar = 331.79;double doubleVar = 8.44e+11;char charVar = 'W';bool boolVar = 0;

printf("integerVar (using %% i)= %i\n", integerVar);printf("integerVar (using %% d)= %d\n", integerVar);printf("floatVar (using %% f)= %f\n", floatVar);printf("doubleVar (using %% e) = %e\n", doubleVar);printf("doubleVar (using %% g)= %g\n", doubleVar);printf("charVar (using %% c) = %c\n",charVar);printf("boolVar (using %%i) = %i\n",boolVar);

return 0;}

51

After executing this program:

integerVar (using %i) = 100integerVar(using %d) = 100floatVar (using %f) = 331.79doubleVar (using %e) = 8.44+011doubleVar (using %g) = 8.44+011charVar (using %c) = WboolVar = 0

Page 52: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Write a program that asks a user to enter the numberof days travelled.

The program would then display theo Full weeks traveledo Remaining days traveled

For example:o If the user entered 19o The program will displayo Full weeks traveled 2o Remaining days traveled 4

A Simple Program

52

Page 53: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

A Simple Program

53

#include <stdio.h>/* program reads number of days travelled and prints fullWeeks, remainDays */int main() {

/* Declaring the variables */int daysTraveled;int fullWeeks, remainDays;

/* Prompt the user to enter the total number of days travelled */printf (“ Enter the total number of days travelled: “); scanf (“%d”, &daysTraveled);/* Calculate the # of weeks and remaining days of total daysTraveled */fullWeeks = daysTraveled/ 7;remainingDays = daysTraveled % 7;

printf (“%d days are %d weeks and %d days\n”, daysTraveled, fullWeeks, remainDays);return 0;

}

53

Enter the total number of days traveled: 19

19 days are 2 weeks and 4 days

Page 54: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Size of Variables

54

#include <stdio.h> int main() {

short a;long b;long long c;long double d;

printf("size of short = %d bytes\n", sizeof(a));printf("size of long = %d bytes\n", sizeof(b));printf("size of long long = %d bytes\n", sizeof(c));printf("size of long double= %d bytes\n", sizeof(d));return 0;

}

• You can always check the size of a variable using the sizeof () operator.

Page 55: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Summary

Page 56: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Summary C is a structured high level programming language that is used

extensively by software developers. One feature present in all computer languages is the identifier

that allow us to name data and other objects in the program. A type in the C programming language defines a set of values

and a set of operations that can be applied on those values. The most common types in the C programming language are:

char, int, float, and double. Variables are named memory locations that have a type, such

as integer or character, which is inherited from their type. The type determines the values that a variable may contain and

the operations that may be used with its values. Constants are data values that cannot be changed during the

execution of a program. Like variables, constants have a type.

56

Page 57: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

Resources

Page 58: ENG1410 C Programming: Topic #2 “C Programming: Variables ...

C Variables/Types: Resourceso YouTube:

https://www.youtube.com/watch?v=gsQX0VKPBws https://www.youtube.com/watch?v=k1ur8rX-DQQ https://www.youtube.com/watch?v=j1u3V6pzwEI

o Documents: https://www.unf.edu/~wkloster/2220/ppts/cprogramming_tutorial.pdf

o Examples: https://beginnersbook.com/2015/02/simple-c-programs/ https://www.studytonight.com/c/programs/ https://www.programiz.com/c-programming/examples

o Test Yourself: https://www.javatpoint.com/c-quiz https://www.tutorialspoint.com/cprogramming/cprogramming_online_quiz.htm https://data-flair.training/blogs/online-c-programming-test/

58

Page 59: ENG1410 C Programming: Topic #2 “C Programming: Variables ...