0% found this document useful (0 votes)
71 views

3.variables & Operators

This document provides a summary of topics covered in Lecture 2 on variables in C programming. It discusses naming conventions for variables, different types of variables like char, int, float and double. It explains how to declare variables, initialize them, and use the sizeof operator to check their sizes. The document also covers constants, type conversions, casting, and arithmetic, logical and bitwise operators. It provides examples of declaring, initializing and performing operations on variables and constants.

Uploaded by

Tazbir Antu
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

3.variables & Operators

This document provides a summary of topics covered in Lecture 2 on variables in C programming. It discusses naming conventions for variables, different types of variables like char, int, float and double. It explains how to declare variables, initialize them, and use the sizeof operator to check their sizes. The document also covers constants, type conversions, casting, and arithmetic, logical and bitwise operators. It provides examples of declaring, initializing and performing operations on variables and constants.

Uploaded by

Tazbir Antu
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 35

Lecture 2

Sarwar Morshed
American International University-Bangladesh (AIUB)
Topics Covered
Naming Convention of Variables.
Types of Variables
Constants
Variable Declaration
Arithmetic, Logical and BitwiseOperators
Increment, Decrement and Assignment Operators
How to Declare a Variable
To declare a variable of type char with name ch.
char ch;
A variable is a location in memory where data is
stored.
A variable has two parts;
<type> <name>;
Type specifies what kind of data is allowed to store in
that variable.
Name or Identifier is used to identify the variable.
Naming Convention of Variables
A variable name cannot be a keyword.
Example: float, int, char, main, if, else, for, while.
These words are already reserved by C.
A variable name must start with either an
underscore ‘_’ or an alphabet (Lower or Upper).
A variable name can consist of digits, alphabets and
underscore.

Correct Incorrect
count 1count
test123 hi!!
high_balance high…balance
Types of Variables
Data Types
char - single character (8 bits)
int - 32 bits
float - 32 bits
double - 64 bits
The amount of space occupied by these data types
depends on the machine architecture
Modifiers
Variables could be signed or unsigned.
Variables could be short or long.
Types Of Variables
Unsigned data is always positive or zero.
If we have a signed char, then the range is from
-128 to 127.
If it is unsigned, then the range is from 0-255.

unsigned long int: 0 to 4,294,967,295


signed double: - 263 to 263 -1
unsigned double: 0 to 264-1
sizeof() function
#include <stdio.h>
main()
{
printf("****** SIZE OF DATA TYPES ***********\n");
printf("Size of char is %d bytes\n", sizeof(char));
printf("Size of int is %d bytes\n", sizeof(int));
printf("Size of float is %d bytes\n", sizeof(float));
printf("Size of double is %d bytes\n", sizeof(double));
printf("Size of short is %d bytes\n", sizeof(short));
printf("Size of long is %d bytes \n", sizeof(long));
}
Types of Variables
The standard headers <limits.h> and <float.h>
contains symbolic constants for all sizes.
Example: INT_MAX, INT_MIN, LONG_MAX and
LONG_MIN.
More on appendix B of KR book.
MAX and MIN
#include <stdio.h>
#include <limits.h>
main()
{
printf("****** MAX and MIN LIMITS ***********\n");
printf("Max int is %d, Min int is %d\n", INT_MAX, INT_MIN);
printf("Max short is %d, Min short is %d\n", SHRT_MAX, SHRT_MIN);
printf("Max long is %d, Min long is %d\n", LONG_MAX, LONG_MIN);
printf("Max char is %c, Min char is %c\n", CHAR_MAX, CHAR_MIN);
return 0;
}
Variable Declaration
Variables must be declared at the start of a function, before
use.
int lower;
int upper;
int step;
char c;
char d;

Variables with the same type can be grouped together:


int lower, upper, step;
char c, d;
Variable Initialization
Variables can also be initialized in the declaration.
int lower = 0, upper = 8, step = 1;
char c = ’f’, d = ’z’;
 What happens if a variable is not initialized and
then used?
void main() {
int a;
printf( "The value of a is: %d\n", a );
}
Constants
Constants are basically variables that cannot have
their values changed.

All data types have constants.


Constants
#define INT_CONST 1234
#define FLOAT_CONST 1234.98F
#define DOUBLE_CONST 1234.98
#define DOUBLE_CONST_EXP (1e-2)
#define A 'A'
#define V_TAB '\013'
#define V_TAB2 '\xb'
#define STRING_CONST "Hello World\n"
Constants Program
main()
{
printf("Int Constant is %d\n", INT_CONST);
printf("Float Constant is %f\n", FLOAT_CONST);
printf("Double Constant is %f\n", DOUBLE_CONST);
printf("Double Exp Constant is %f\n",
DOUBLE_CONST_EXP);
printf("A Constant is %c\n", A);
printf("V_TAB Constant is %c\n", V_TAB);
printf("V_TAB Constant is %c\n", V_TAB2);
printf("STRING_CONST is %s\n", STRING_CONST);
}
ASCII Characters
ASCII stands for American Standard Code for
Information Interchange.
A character is 8 bits long.
The characters are represented by an 8 bit integer.
For example, the character code for ‘A’ is 65 and the
character code for ‘a’ is 97.
Character Constants
All characters are represented as integers (usually signed),
and can be treated as integers.
 Escape codes correspond to characters, for use in single-
quotes:
 Examples: \n (newline), \\ (backslash), \" (double quote)
 Example use: char a = ’\n’;
Variables of type char can be thought of as either a character
of an integer.
printf( "%c", ’a’ ); /* a is printed */
printf( "%d", ’a’ ); /* 97 is printed */
printf( "%c", 97 ); /* a is printed */
printf( "%d", 97 ); /* 97 is printed */
Character Constants
Lower-case letters, upper-case letters, digits
“consecutive”
’a’ == 97, ’b’ == 98, . . ., ’z’ == 122
’A’ == 65, ’B’ == 66, . . ., ’Z’ == 90
’0’ == 48, ’1’ == 49, . . ., ’9’ == 57
• Some more examples of the integer values
corresponding to character constants:
’ ’ == 32, ’*’ == 42, ’\n’ == 10, ’\\’ == 92, . . .
Characters
#include <stdio.h>
void main() {
char i;
printf( "Here’s the alphabet, in lower-case:\n" );
for( i = 'a'; i <='z'; i++ ) {
printf( "%c", i );
}
printf( "\n\nHere’s the alphabet, in upper-case:\n" );
for( i = 'A'; i <= 'Z'; i++ ) {
printf( "%c", i );
}
}
Characters
#include <stdio.h>
void main() {
char i;
printf( "Here’s the alphabet, in lower-case:\n" );
for( i = 97; i <= 122; i++ ) {
printf( "%c", i );
}
printf( "\n\nHere’s the alphabet, in upper-case:\n" );
for( i = 65; i <= 90; i++ ) {
printf( "%c", i );
}
}
String Constants
There is no string data type, but there could be string
constants.
A String Constant is an array of characters enclosed
within double quotes.
“this is a test”
The internal representation of a string has a null
character ‘\0’ at the end.
This representation allows strings to be as large as
possible.
String Constants
Example: "A string" is a string.
The statement printf( "A string" ); would print that
string.
You’ll never see anything like
String s = "A string";.
Strings will be covered later in the course.
Type Conversions
C is very flexible with type conversions.
If an operator has operands of different types, they
are converted according to a small number of
rules.
Automatic conversions occur when a “narrower”
operand can be converted into a “wider one”.
Example: adding an int and a long will cause the
int to be converted automatically.
Type Conversions
Keep in mind that a char is just a small integer, so
you can do arithmetic operations: e.g., ’c’ - ’a’ is 2.
(No type conversion required!)
Conversions also occur when you try to assign a
variable of one type to another.
Be careful! the new assigned variable might be different!
 Example: if x is float and i is int, then the
assignment i = x will truncate any fractional part
of x.
Type Conversion Example
#include <stdio.h>

void main() {
float f = 1.245;
int i;
i=f;
printf("%d\n", i);
f=i+f;
printf("%0.3f\n", f);
}
Casting
You can explicitly cast a variable of one type to be a
variable of another type.
This is useful if you aren’t sure how conversion will
work, or you want to force conversion to happen in a
specific way.
Example:
int a = (int) 12.54;
Casting Example
#include <stdio.h>

void main() {
int a=15, b=10;
double x;
x = a / b;
printf("%0.3f\n", x);
x = (double) a / (double) b;
printf("%0.3f\n", x);
}
Using Scanf
Use scanf to get input from the user.
Same syntax as printf.
Use %d, %f, %c etc.
Can get many inputs with single scanf
scanf("%d%d%d", &a, &b, &c);
Use & (ampersand) before the variable.
Printing a float
Simple form:
printf( "%f", 3.141592653 );
Fancy form:
printf( "%6.2f", 3.141592653 ); // prints two spaces followed
by 3.14
6 specifies minimum field width: at least 6 characters
will be printed, with spaces added if necessary
2 specifies max. number of digits to be printed after the
decimal point
Printing an int as an octal number
printf( "%o\n", 17 ); // prints 21
Printing an int as a hexadecimal number
printf( "%x\n", 31 ); // prints 1F
scanf / printf example
#include <stdio.h>

void main() {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
printf("a=%d, b=%d, c=%d", a, b, c);
}
Arithmetic Operators
• C has a number of arithmetic operators.
Assignment operator: =
Binary arithmetic operators: +, -, *, /, %
Can be applied to int, float, or double, except for
% which can only be applied to integers.
% is the “modulus” or “mod” operator: a % b is equal
to the remainder when a is divided by b.
Example: 8 % 3 == 2.
Unary arithmetic operator: -. Example:
x = -y;
Arithmetic Operators
Shortcut operators: +=, -=, *=, /=
x += 2; /* equivalent to x = x + 2; */
x *= 2; /* equivalent to x = x * 2; */
Increment/decrement operators: ++, --
x++; /* acts like x = x + 1; */
x--; /* acts like x = x - 1; */
++ and – –: tricky expressions
Both x++ and ++x are expressions. The expression x++ acts
like x, and ++x acts like the expression x+1.
What’s special is the side effect: evaluating these
expressions causes x to be incremented by 1.
int a = 10, b, c;
b = a++; /* a is now 11, b is 10 */
c = ++b; /* a, b, c are all 11 */
For clarity, try not to mix ++ or - - into complicated
expressions.
 Note that the expression that ++ or -- is applied to must
be a variable.
(x + 2)++; /* no good! */
x + 2 = 8; /* no good! */
(x++)++; /* no good! */
Order of Evaluation
How are expressions with many operators evaluated?
Two considerations:
Precedence
Associativity
How is 1 + 2 * 3 evaluated?
Parentheses must be used if we want the addition to
be performed first.
Order of Evaluation
What about expressions containing operators at the
same precedence level? E.g., (12 / 6 * 2) or (5 - 3 - 1)?
These parse as:
((12 / 6) * 2) and ((5 - 3) -1)
They are left associative.

You might also like