0% found this document useful (0 votes)
9 views10 pages

L2 - Variables and IO

Uploaded by

roukff61736220
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)
9 views10 pages

L2 - Variables and IO

Uploaded by

roukff61736220
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

Variables

▪ In programming, a variable is a container (storage area) to hold data.

▪ In real world we use various type containers for specific purpose


ME171: Computer Programming Language
• For example, we can use suitcase to store clothes, bucket to store
liquids etc.
Semester: January 2024
▪ In the same way variables of different data type is used to store different
types of data
• For example, integer variables are used to store integers, char
Variables & I/O variables are used to store characters etc.

▪ All variables in C must have a type, which specifies what kind of data it will
hold

▪ A variable must be declared before use in C programs


Dr. Sheikh Mohammad Shavik
Associate Professor, ME, BUET
Department of Mechanical Engineering, BUET 1 2
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 2

Variables Variables
▪ In C, every variable has two most fundamental attributes: ▪ There are different variants of the basic types
• 1. Data Type: Which types of data is to be used (int, char, float, double, • e.g. unsigned int which can only hold non-negative integers
etc.)
• long int which can hold larger integers
• 2. Variable Name: Which name (identifier) is to be used to address and
identify the variable in the code ▪ In addition to the basic types C allows the user to specify his/her own (user
defined) data types (which will be discussed later in the class)
▪ Syntax of declaring a variable:
▪ Declaration of an integer variable:
data_type(space)variable_name;
int playerScore;
▪ Some basic data types:
• Data type: integer type data
Type Description
• Variable name: playerScore
int Integer values. Example: 1, 5, 50, 100, 25509 etc.
float Floating point numbers. Example: 0.1, 2.53, 50.05 etc. ▪ As variable name is an identifier, it follows the same rules of naming an
identifier
double Floating point numbers (higher accuracy, large numbers)
char Character. Example: a, C, etc.

3
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 3 4
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 4
Variables: Uniqueness Variables: Uniqueness
▪ Most important property of a variable’s name is its uniqueness #include <stdio.h>
int a = 5; //Global Variable: Visibility is within the whole program
▪ Two variables in C cannot have the same name within same visibility. Note
int main(){
that C is case sensitive.
int a = 10; //Visibility within main block
• For example: printf("%d",a);
return 0;} Output: 10
#include <stdio.h> // Although this code works, but it is a very bad practice to use same variable
name for different variables in the same code, it is not recommended
int main()
#include <stdio.h>
{ int a = 5; //Visibility is within main block
int a = 10; //Visibility is within main block int main()
/* Two variables of same name */ { int a = 10; //Visibility within main block
printf("%d", a); a += 5; //Accessing local variable ‘a’ of the outer block
return 0;} { int a = 20; //Visibility within inner block
a += 10; //Accessing local variable ‘a’ of the inner block
printf("\t%d\t", a); } //Accessing local variable ‘a’ of the inner block
Output: Build Error (redefinition of ‘a’) printf("%d", a); //Accessing local variable ‘a’ of the outer block
return 0; } Output: 30 15
5
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 5 6
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 6

Variable Declaration & Definition Variable Declaration & Definition


▪ Declaration of variables means to acknowledge the compiler only about variable ▪ Storage Class:
name and its data type with its modifiers but compiler doesn’t reserve any
memory for the variables ▪ A storage class represents the scope, location, initial value and lifetime of a
variable. It tells from what part of code we can access a variable. There are total
▪ In c we can declare any variable with the help of extern keyword while it has not four types of standard storage classes in C.
initialized. Example of declaration:
Storage Class Purpose
extern int a; //Declaration of variable a
auto It is a default storage class. The scope of an auto variable is limited
▪ C statement in which a variable gets a memory is known as definition of variable with the particular block only.
extern It is a global variable. Keyword extern extends the visibility of the C
int a; //Definition of variable a variables and C functions. Extern variable is used when a particular
static int a; //Definition of variable a files need to access a variable from another file
register int a; //Definition of variable a static Static variable is a local variable that retains and stores its value
between function calls or block and remains visible only to the
extern int a=5; //Definition (Declaration plus Initialization) of variable a function or block in which it is defined.
• In the above c statements, all variables has been declared and defined at the register It is a variable which is stored inside a CPU Register instead of RAM
same time (most of the time we use this) to have quick access to these variables.

7
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 7 8
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 8
Variable Declaration & Definition Constants
▪ Variable declaration or definition should appear first in the main function ▪ The value of a constant can not be changed in entire code
#include <stdio.h> ▪ Two methods of defining a constant in C:
int main() { 1. using #define
int a = 100; 2. using const keyword
printf(“%d”, a); Not recommended ▪ 1. Using #define
int b; • Should be defined before main function
b = a++; • No need for specification of data type of the constant
printf(“%d”, a); • Its not a statement, so no semicolon (;) should be used
return 0; }
▪ 2. Using const keyword
• Can be defined both globally or locally
#include<stdio.h>
• Definition is similar to variable definition with const keyword before the data type
int main(){
int a = 100, b; #define TRUE 1
#define FALSE 0 const int id = 44;
printf(“%d”, a); Recommended
#define Grade “A” //Character Constant const float PI = 3.1416;
b = a++; #define PI 3.1416 const int grade; //no value is assigned
printf(“%d”, a) ; #define CONST “String Constant” // String Constant
return 0; }
9
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 9 10
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 10

Escape Sequences Data Types


▪ Sometimes, it is necessary to use characters which cannot be typed or has special ▪ Data types in C refer to an extensive system used for declaring variables or
meaning in C programming functions of different types
▪ For example: newline(enter), tab, question mark etc.
▪ The type of a variable determines how much space it occupies in storage
▪ In order to use these characters, escape sequence is used
and how the bit pattern stored is interpreted
▪ For example: \f form feed is a page breaking ASCII character which when comes in
the output leads the output to continue from the next line at the same place ▪ Data Types
• Primitive: int, char, float, double, void
• Derived: Array, Pointer, Function
• Custom Data Types: enum, Structure, Union, Bit-field, typedef

11
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 11 12
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 12
Data Types Data Types
▪ Void data type: ▪ Enumerated Data Type (enum)
▪Enumerated data type is a custom data type having finite set of enumeration
• The void type has no values therefore we cannot declare it as variable
constants. The keyword 'enum' is used to create enumerated data type.
as we did in case of integer and float
▪Enumeration data type consists of named integer constants as a list. It start
• The void data type is usually used with function to specify its type. In C with 0 (zero) by default and value is incremented by 1 for the sequential
program we declare, "main ()" as void type because it does not return identifiers in the list.
any value. ▪Syntax: enum [data_type] {const1, const2…., constN};
▪ Typedef Data Type : ▪enum example in C:
• It is used to create new data type. But it is commonly used to change enum month { Jan, Feb, Mar }; /* Jan, Feb and Mar variables will be assigned to
existing data type with another name. 0, 1 and 2 respectively by default */
enum month { Jan = 1, Feb, Mar }; /* Feb and Mar variables will be assigned to 2
• Syntax: typedef [data_type] new_data_type; and 3 respectively by default */
• Example: enum month { Jan = 20, Feb, Mar }; /* Jan is assigned to 20. Feb and Mar
• typedef int integer; variables will be assigned to 21 and 22 respectively by default */
enum Cars{ Jeep = 1, BMW = 0, Mercedes_Benz = 0 }; /*Multiple enum
• integer roll_no; elements can have the same value*/
enum containers{ cont1 = 5, cont2 = 7, cont3 = 3, cont4 = 8 };
13
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 13 14
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 14

Data Types Data Types


#include <stdio.h> ▪ Structure Data Type
enum State {Todo = 0, Running = 1, In_Progress = 1}; ▪ C Structure is a collection of different data types which are grouped together and
int main() each element in a C structure is called member
{ ▪ Example:
printf("%d, %d, %d", Todo, Running, In_Progress); struct student
return 0; Output: 0, 1, 1 { int roll_no; char name[20]; char city[20]; };
}
▪ Union Data Type
#include <stdio.h>
▪ Union is another commonly used custom data type beside struct. Besides, it
enum day {sunday = 1, monday, tuesday = 20, provides some benefits on memory issue which structure does not provide.
wednesday, thursday = 10, friday, saturday};
▪ The memory required for union is less than structure in most of the cases.
int main()
▪ Declaration of union is like structure except the keyword.
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday, thursday, friday, saturday); ▪ Example:
return 0; union employee
} { char name[50]; char designation[50]; char dept[50]; int age; float salary; };
Output: 1 2 20 21 10 11 12

15
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 15 16
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 16
Data Types Storage Size of Data Types
Structure Vs. Union ▪ The char data type is usually 1 byte, because they are commonly used to store
struct employee single characters
{ int empId; char gender; float salary; } myEmployee; ▪ The size of the other types is dependent on the compiler/hardware of your
union employee computer
{ int empId; char gender; float salary; } myEmployee; ▪ On "32-bit" or ”64-bit" machines the int data type takes up 4 bytes
▪ Let us assume that memory consumption of int = 2 bytes, char = 1 byte, float = 4 ▪ The short is usually smaller, the long can be larger or the same size as an int and
byte finally the long long is for handling very large numbers
▪ In structure, total memory consumption = 2 + 1 + 4 = 7 bytes. In union, total int main() Output:
memory consumption is 4 bytes. { printf("sizeof(char) == %d\n", sizeof(char)); sizeof(char) == 1
▪ Union works in this concept: In some conditions, more than one variable is printf("sizeof(short) == %d\n", sizeof(short)); sizeof(short) == 2
needed actually, but all the variables do not work at the same time.
printf("sizeof(int) == %d\n", sizeof(int)); sizeof(int) == 4
▪ So the memory units needed to store the member that takes the maximum unit
of memory can be taken and reused for other members. printf("sizeof(long) == %d\n", sizeof(long)); sizeof(long) == 8
▪ In the above example, out of three members of union, float data type takes most return 0; }
memory which is 4 bytes ▪ signed, unsigned, long, short are known as modifiers

17
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 17 18
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 18

Storage Size of Data Types Modifiers


▪ Modifiers are used to modify the storage size and data range of a variable
▪ Should be written before or after the data type of a variable
▪ long int a = 50;

Modifier Data Type Variable name Value of the variable


long int a 50

▪ Modifier without a data type assumes integer type data:


• long a = 25;
• It is equivalent to: long int a = 25;
• signed a = 25;
• It is equivalent to: signed int a = 25;
▪ We cannot use two modifiers of same type of modification in any particular data type
of c.
• short long int i;
• static auto char c; Incorrect!
• signed unsigned int array[5];
• signed long int i; Correct!
19
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 19 20
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 20
Working with Int: Examples Working with Int: Examples
▪ Interchange two numbers: ▪ Convert height of a person:
– Given integers as input, can you interchange their content? • Given height in feet inch as input: convert it to inch
• Given height in inch as input: convert it to feet inch
#include <stdio.h>
▪ Time difference of two cities: Dhaka – 10:30, Colombo – 10:00
int main(){
int x, y, t;
▪ Think time as two separate integers: one quantity for hour and the other
scanf(“%d %d”,&x,&y); quantity for minute as input
t = x;
x = y;
y = t; ▪ To extract digits of a number:
printf(“%d %d”,x,y); • Given a 4-digit number as input, can you reverse it?
return 0; • Modulus (%) and division (/) operators are good enough
}

21
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 21 22
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 22

Input and Output in C Input and Output in C


▪ Input output functions in C programming falls into two categories, namely, Formatted input output functions Unformatted input output functions
formatted input output (I/O) functions and unformatted input output (I/O) #include<stdio.h>
functions. #include<stdio.h>
#include<conio.h>
#include<conio.h>
▪ A library of functions is supplied to perform these operations. The common I/O
library functions are listed the “header” file <stdio.h> void main(){
void main()
char ch ;
{ int a;
▪ Some common input and output functions are: clrscr();
clrscr();
printf(“Press any character:”);
• getch(), getche(), getchar(), putchar() printf(“Enter value of a:”);
ch = getchar();
scanf(“%d”, &a);
• gets(), puts() printf(“\nYou pressed :”);
printf(“ a = %d”, a); }
putchar(ch); }
• scanf(), printf() //formatted I/O functions Enter value of a: 9 Press any character: G
• getc(), putc(), fgets(), fputs(), fscanf(), fprintf() // for data file input and output a=9 You pressed: G
clrscr() --- It is a predefined function in "conio.h" (console input output header file) used to
clear the console screen. By using this function we can clear the data from console
(Monitor). Use of clrscr() function in C is always optional but it should be place after variable
or function declaration only
23
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 23 24
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 24
Input and Output in C getchar() and putchar()

25
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 25 26
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 26

gets() and puts getc() and putc


▪ gets() function can be used to take a string as input from standard input
▪ gets() function is used to take a string as input from standard input
▪ gets() function takes input until the function encounters a newline
▪ Warning: gets() function performs no check on the size of the input. It will keep on
accepting input until a newline is encountered irrespective of the size of the
variable in which the input is being stored. This can cause “buffer overflow” and
unexpected behavior in the code.

#include <stdio.h>
int main()
{ char c[10];
printf( "Enter string:");
gets(c);
printf( "\nYou entered: ");
puts(c);
return 0;}

27
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 27 28
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 28
fgets() scanf() and printf()
▪ fgets() reads a line from the specified stream and
stores it into the string pointed to by str. It stops when
either (n-1) characters are read, the newline character #include <stdio.h>
is read, or the end-of-file is reached, whichever comes #define MAX 15
first.
int main()
▪ Syntax: char *fgets (char *str, int n, FILE *stream); {
• str: Pointer to an array of chars where the string char buf[MAX];
read is copied. printf( "Enter string: ");
fgets(buf, MAX, stdin);
• n: Maximum number of characters to be copied Warning: taking string input with scanf() can
into str (including the terminating null character). printf(“String is: %s\n", buf);
be tricky and may cause buffer overflow.
• *stream: Pointer to a FILE object that identifies return 0; scanf() doesn’t allow whitespace while
an input stream. stdin can be used as argument } taking string input.
to read from the standard input.
▪ fgets() is safe to use because it checks the array bound Enter string: Mechanical Engineering
String is: Mechanical Eng
▪ It keeps on reading until a new line character is
encountered or the maximum limit of the character
array
29
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 29 30
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 30

Format Specifier Format Specifier: Examples

31
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 31 32
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 32
Format Specifier: Examples Printing with Field Widths and Precision

33
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 33 34
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 34

Printing with Field Widths and Precision Printing with Field Widths and Precision

Output of Integer Numbers % wd

Format Output
printf(“%d”, 9876); 9 8 7 6
printf(“%6d”, 9876); 9 8 7 6
printf(“%2d”, 9876); 9 8 7 6
printf(“%-6d”, 9876); 9 8 7 6
printf(“%06d”, 9876); 0 0 9 8 7 6

35
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 35 36
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 36
Printing with Field Widths and Precision Working with Characters
▪ Write down a program that prints ASCII value of a character given as input.
Output of Real Numbers % w.p f % w.p e (Hint: characters could be thought of as numbers)
Format (y = 98.7654) Output ▪ Write down a program that will take a small letter as input and will print its
printf(“%7.4f”, y); 9 8 . 7 6 5 4 previous letter. (Hint: as characters could be thought of as numbers, you are
allowed to subtract/add numbers with it)
printf(“%7.2f”, y); 9 8 . 7 7
printf(“%-7.2f”, y); 9 8 . 7 7 ▪ Write down a program that will take an uppercase letter as input and will
convert it to lower case letter.
printf(“%f”, y); 9 8 . 7 6 5 4
printf(“%10.2e”, y); 9 . 8 8 e + 0 1
printf(“%11.4e”, -y); - 9 . 8 7 6 5 e + 0 1
printf(“%-10.2e”, y); 9 . 8 8 e + 0 1
printf(“%e”, y); 9 . 8 7 6 5 4 0 e + 0 1

37
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 37 38
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 38

You might also like