L2 - Variables and IO
L2 - Variables and IO
▪ All variables in C must have a type, which specifies what kind of data it will
hold
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
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
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
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
21
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 21 22
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 22
25
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 25 26
15-Sep-24 ME 171 Department of Mechanical Engineering, BUET 26
#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
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
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