0% found this document useful (0 votes)
55 views33 pages

Center For Advanced Studies in Engineering

This document provides an overview of variables in the C programming language. It discusses how to declare variables, assign values to variables, and print variables. It also covers basic data types like int, float, and char, and operators like arithmetic, assignment, increment, and decrement operators. The key points are: 1) All variables must be declared before use with a name, type, and storage allocation. 2) Variables can store integer, floating point, character, and other data types. 3) The assignment operator (=) is used to assign values to variables. 4) Printf and scanf are used to output and input variable values. 5) Operators allow mathematical and other operations on variables
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views33 pages

Center For Advanced Studies in Engineering

This document provides an overview of variables in the C programming language. It discusses how to declare variables, assign values to variables, and print variables. It also covers basic data types like int, float, and char, and operators like arithmetic, assignment, increment, and decrement operators. The key points are: 1) All variables must be declared before use with a name, type, and storage allocation. 2) Variables can store integer, floating point, character, and other data types. 3) The assignment operator (=) is used to assign values to variables. 4) Printf and scanf are used to output and input variable values. 5) Operators allow mathematical and other operations on variables
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Center for Advanced

Studies in Engineering

Programming in C

Lecture2

1
C Techniques
z Variables
z Operators
z Decisions
z Loops

2
Variable Definition

int x;
X

All variables must be defined as to specify their


name, type and set aside storage. 3
X = 10 ; 10 10
X = 30 ;
30 30
4
Variables
z Variables, can be declared anywhere in the
program.
z Name & type must be declared before use
z However they are only visible to the program
within the block of code in which they are
defined.
void main()
{
int x = 4;

}
5
Values and Variables
z Basic Types:
z Integers (signed and unsigned)

z short

z int

z long or long int

z Floating point numbers

z float

z double

z Characters

z Boolean

6
Basic Types: int,float,char

z Integers (int)
0 1 1000 -1 -10 666
z Floating point numbers (float)
1.0 .1 1.0e-1 1e1
z Characters (char)
’a’ ’z’ ’A’ ’Z’ ’?’ ’@’ ’0’ ’9’

7
int x;
C Variables float sum, product;

z Variables in C store data in memory so that the data can be


accessed throughout the execution of a program
z A variable stores data corresponding to a specific type.
z Each variable that a C program uses must be declared at the
beginning of the function before it can be used.
z specify the type of the variable
z numeric types: int short long float double
z character type: char
z specify a name for the variable
z any previously unused C identifier can be used (with some
more exceptions discussed later)

8
What Does a Variable
Declaration Do?
int apartmentNumber;
float tax_rate_Y2K;
char middleInitial;

A declaration tells the compiler to allocate enough


memory to hold a value of this data type, and to
associate the identifier with this location.

4 bytes for tax_rate_Y2K 1 byte for middleInitial


9
Variable Names
z Variables names are called identifiers
z Rules for constructing valid variables in C:
z can contain letters (upper and lower case),
digits, and the underscore ( _ ) character
z cannot start with a digit
z cannot be a reserved (key) word
z can be at most 256 characters long, though
some compilers only look at first 32 characters
z are case sensitive
10
Keywords of C (32)
Keyw o rd s
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

11
Identifiers
z VALID
apartment_number tax_rate_Y2K
PrintHeading ageOfHorse_

z NOT VALID
apartment# 2000TaxRate
Age-Of-Cat day of week

z Using meaningful variable names is a good


programming practice.
z Using _ as the first character is not
recommended.
12
Initializing Variable
You can assign (give) a value to a variable by
using the assignment operator =

VARIABLE DECLARATIONS
char middleInitial ;
char letter ;
int apartmentNumber;

VALID ASSIGNMENT STATEMENTS


middleInitial = ‘K’ ;
letter = middleInitial ;
apartmentNumber = 8 ;

13
Assignment Statement
z An assignment statement is used to put a value into a
variable.
z The previous value is replaced
z Syntax:

<variable> = <expression>;

z <variable> is any declared variable in the program


z <expression> is anything that produces a value of the
appropriate type.
z first, the expression on right is evaluated.
z then the resulting value is stored in the memory location of
variable on left.
14
C Variable Covered Range
Data Type Possible Range of Values

char -127 to 127

short -32,767 to 32,767

int -2,147,483,648 to 2,147,483,647

float 6 Digits of Precision

double 10 Digits of Precision

boolean True or False

15
The char type
z char stores a character variable
z We can print char with %c
z A char has a single quote not a double quote.

void main()
{
char a, b;

a= 'x'; /* Set a to the character x */

printf ("a is %c\n",a);


}
16
Sizeof

z Sizeof: returns size of variable or data type in


number of bytes

sizeof(int) /* sizeof a type */


sizeof x /* sizeof a data object */

17
Printing variables and constants to the
screen with printf
• Use the following conversion specifications:

%d for an integer %c for a character


%f for a float %f for a double
Example:
int sum = 5;
float avg = 12.2;
char ch = ‘A’;
printf(“The sum is %d\n”, sum);
printf(“avg = %f”\n”, avg);
prinf(“ch = %c\n”, ch);
printf(“%d, %f, %c\n”, sum, avg, ch);
printf(“%d\n”, 5); 18
Reading data from the keyboard with
scanf

z Used to assign a value typed on the keyboard to


a variable.
z Used similarly to printf. You must use the
following conversion specifications:
Data Type scanf conversion spec.
int %d
long %ld
float %f
double %lf
char %c
character string %s
z The user must type a value followed by the Enter Key.
z Ex:
scanf(“%d”, &num); 19
Example:
Program to find the average of two numbers

#include <stdio.h> z Note that you can declare more


than one variable per line.
int main ()
{
z We divide by 2.0 instead of 2 so
int num1, num2; that the right hand side is a float
float avg; (i.e. no truncation takes place)
z scanf is used similarly to printf,
/* get two inputs */ except that you need to put an
printf( "Enter the first integer:”); ampersand (&) before the
scanf(“%d”, &num1); variable name
printf(“Enter the second integer:”);
scanf(“%d”, &num2); z The first argument of the scanf
function is the conversion
/* compute and print the avg */ specifier(s) in quotes, then the
avg = (num1 + num2) / 2.0; variable name(s)
printf(“The average is %f\n”, avg);

return 0;
} 20
Operators
z Arithmetic Operators
z Increment/ Decrement Operators
z Relational Operators

21
Arithmetic Operators

z + = add
z - = subtract
z * = multiply
z / = division
z % = modulus - remainder

22
Modulus

z produces remainder
z only on integer division
z division by zero = error
z Example:
ans = 13% 5;

ans=3

23
Precedence

Operator(s) Operation(s) Order of evaluation (precedence)


() Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs of parentheses “on the same level” (i.e.,
not nested), they are evaluated left to right.
*, /, or % Multiplication,Divi Evaluated second. If there are several, they are
sion, Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.

24
Arithmetic Assignment Operators
z All the arithmetic operators can be combined
with the equal sign:
z += addition assignment operator
z -= subtraction assignment operator
z *= multiplication assignment operator
z /= division assignment operator
z %= remainder assignment operator

25
Examples
z total= total + number;
z total += number;
z d= d-a;
z d-=a;
z Shorthand Assigns:
x*=3 (multiply x by 3)
x+=5 (add 5 to x)
x-=10 (subtract 10 from x)
x/=2 (halve x)
26
Increment/Decrement Operators
z ++ (increment)
z -- (decrement)

z Pre and Post Increment and decrement

z int a;

z a++; ++a;
z a--; --a;

27
C Operators
z There is a subtle difference between x++ and ++x.
z ++x will increment the variable before it does anything
else with it, x++ will increment after any assignments.
x = 10; x = 10;
y = ++x; y = x++;

Here y is set to 11 Now y is set to 10

z In the first two cases x is set to 11, but in the first this is
done before the assignment.
28
Relational\Logical Operators
z C defines these logical operators:
z < less than
z > greater than
z <= less than or equal to
z >= greater than or equal to
z == equal to
z != not equal to

z You can compare any variable. Characters are


compared based on their ASCII values.
z All answers will be true (not zero) or false (0)
z You can extend the logic with && (and), ~ (not) and ||
(or).
29
Example

z no space between operators


z = = is invalid == OK

z int age;
z age = 15;
z Printf(“Is age less than 21? %d”, age<21);

z age = 51;
z Printf(“Is age equal to 51? %d”, age==50);
30
z Arithmetic operators have a higher
precedence than relational operators, that is ,
are evaluated before relational operators.

z Printf(“Answere is %d”, 2+1<4);

z Printf(“Answere is %d”, 1<2+4);

31
Compound statements

z && and
z || or
z ! not

32
SUMMARY

33

You might also like