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

Unit 1.2 C Notes by Prof. Shahid Masood

Uploaded by

yrfhj
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)
12 views

Unit 1.2 C Notes by Prof. Shahid Masood

Uploaded by

yrfhj
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/ 95

CABSMJ1001 [2024-25]

Data Types
In
C
CABSMJ1001 [2024-25]

Data Types in C
 A data type defines:
 a set of values and
 the operations that can be performed on these values.

 Every constant, variable etc. in a C program has a data type


associated with it, e.g. int m1 = 60; (here, data type of m1 is int).
 C also has a special data type called void, which denotes no
data type.
 There are three categories of data types in C: Predefined in
1. Primary (or fundamental) data types C language

2. Derived data types (arrays, pointers and functions)


3. User-defined data types (structure, union, enum, typedef)
CABSMJ1001 [2024-25]

Primary (or Fundamental or Built-in) data types

 There are FOUR basic data types in C:

1. Integer types

2. Character types

3. Floating point types

4. void type
CABSMJ1001 [2024-25]

Primary (or Fundamental or Built-in) data types


1. Integer types
 used to store whole numbers (integer values).
 C supports short, int and long data types (which can have
signed or unsigned form).
 Their memory size and range of values that can be stored are:

Data type Memory size Range


short (+ve or –ve values) 2 bytes -32768 to +32767
unsigned short 2 bytes 0 to 65535
int (+ve or –ve values) 2 bytes -32768 to +32767
or 4 bytes -2147,483648 to +2147,483647
unsigned int 2 bytes 0 to 65535
or 4 bytes 0 to 4294,967295
long (+ve or –ve values) 4 bytes -2147,483648 to +2147,483647
unsigned long 4 bytes 0 to 4294,967295
CABSMJ1001 [2024-25]

2. Character types
 char data type - used to store a single character.
 In C, every character is represented in memory by its ASCII
(American Standard Code for Information Interchange) value.

 For example:
 'A' is represented by 65, 'B' by 66, 'C' by 67
 'a' by 97, 'b' by 98, 'c' by 99.

 Memory size and range:


Data type Memory size Range
char (it means signed char) 1 byte -128 to +127
unsigned char 1 byte 0 to 255
CABSMJ1001 [2024-25]

Example: Printing ASCII Value of a Character

/* charexample.c */
#include<stdio.h>
main()
{ char c1='A', c2='a';
printf("ASCII value of %c is %d\n",c1,c1);
printf("ASCII value of %c is %d\n",c2,c2);
}
Output
ASCII value of A is 65
ASCII value of a is 97
CABSMJ1001 [2024-25]

C Characters and Their ASCII Values (in Decimal)


CABSMJ1001 [2024-25]

C Characters and Their ASCII Values

'
CABSMJ1001 [2024-25]

C Characters and Their ASCII Values

Back

DEL is also a
control character
CABSMJ1001 [2024-25]

3. Floating point types

 Used to store numbers with decimal point, e.g. 149.56, 2.3E+3

 C supports float, double and long double data types.

 Their memory size, range and precision are:


Data type Memory size Range Precision
float 4 bytes 3.4E-38 to 3.4E+38 6 decimal digits
double 8 bytes 1.7E-308 to 1.7E+308 15 "
long double 10 bytes 3.4E-4932 to 1.1E+4932 19 "
or 16 bytes 3.4E-49321 to 1.2E+49321
CABSMJ1001 [2024-25]

4. void type
 It denotes no data type.
 It can be used:
 to specify return type of a function (if a function’s return
type is void, it means it does not return any value).
 to specify that a functions’s argument list is empty, e.g.

void f1(void)
{ ……
……
}
 A pointer may also be of type void. Such a pointer may
contain the address of an object, but not its type.
Memory size of void type: Since void type means nothing,
hence it doesn’t have any memory size.
CABSMJ1001 [2024-25]

How to Get the Exact Size of Basic data types on your machine?
 To get the exact size of basic data types on a particular
machine, you can use the expression sizeof(data type) that
yields the memory size of the specified data type in bytes.
/* memorysize.c */
#include<stdio.h>
main()
{ printf("Memory size of char = %d\n",sizeof(char));
printf("Memory size of short = %d\n",sizeof(short));
printf("Memory size of int = %d\n",sizeof(int));
printf("Memory size of long = %d\n",sizeof(long));
printf("Memory size of float = %d\n",sizeof(float));
printf("Memory size of double= %d\n",sizeof(double));
printf("Memory size of long double= %d\n",sizeof(long double));
}
CABSMJ1001 [2024-25]

Memory size of different primary C data types


on DELL LATITUDE E5530 laptop
under Windows 10 OS and DEV C++ IDE
CABSMJ1001 [2024-25]

How to Declare Primary Type Variables in a C Program?

 Syntax for declaring a variable:


datatype var1, var2, ….., varn;
 Examples: If no value is assigned to a variable,
it contains some garbage value

int number1, number2; /* can be used to store int type values. */


int count = 0, sum = 0; /* variable declaration and assigning */
float price = 25.99; /* initial values. */
long x;
char c1, c2 = '*';
double d;
CABSMJ1001 [2024-25]
int a = 10;
a = a + 111;
Default Data Type of Integer Constants in C
 By default, integer constants are treated as int type data.
 We can override this default by appending to the number:
 u or U for unsigned int and
 l or L for long int as below:

Constant (Literal) Type Value


111 or +111 int 111
-222 int -222
45678U unsigned int 45678
-56789L long -56789
987654UL unsigned long 987654
CABSMJ1001 [2024-25]

Default Data Type of Floating Point Constants in C


 By default, floating point constants are treated as double
type data.
 We can override this default by appending to the number
 f or F for float and
 l or L for long double as below:

Literal Type Value


0. or .0 double 0.0
-12.0 double -12.0
1.234 double 1.234
12.0F float 12.0
1.23456789L long double 1.23456789
CABSMJ1001 [2024-25]

Managing
Input and Output
Operations
CABSMJ1001 [2024-25]

Inputting Data in a C Program from Keyboard and


Outputting Result on the Screen

 Inputting/reading means feeding some data into the program.


 Outputting means displaying/writing the result(s) on the
screen or in a file.
 C provides a set of built-in functions to perform I/O operations
(in a C program) - that can be used as per our requirements.
 Following standard library functions can be used to read input
from the keyboard and output results on the screen:
1. getchar(), getch(), getche() and putchar() functions
2. scanf() and printf() functions
3. gets() and puts() functions (discussed in Unit-III).
CABSMJ1001 [2024-25]

Streams in C Programming
 In C, all input and output is
handled with streams -
regardless of where input is
coming from, or where output
is going to.
 A stream is a sequence of characters (bytes of data) flowing
into a program or flowing out of a program.
 C has three predefined streams, known as (i) standard input
stream, (ii) standard output stream and (iii) standard error
stream.
 These streams are:
 automatically opened when a C program’s execution starts
 automatically closed when the program terminates.
CABSMJ1001 [2024-25]

Streams in C Programming
 The standard streams and the
devices they are connected
with:
Name Stream Device
stdin Standard Input Keyboard
stdout Standard Output Screen
stderr Standard Error Screen

 Whenever a program uses functions like scanf(), getchar(), gets()


etc. to read keyboard input, then stdin stream is used.
 Whenever a program uses functions like printf(), putchar(), puts()
etc. to display text on the screen, then stdout stream is used.
 Whenever a program statement faces an error at run-time, then
to print error message on the screen, stderr stream is used.
CABSMJ1001 [2024-25]

getchar() Function (Reading a character from the Keyboard)

 reads the next available character from the standard input


stream (stdin) i.e. keyboard and returns it as an integer.
 Reads the character when <ENTER> key is pressed and the
entered character is displayed on the screen.
 reads only a single character at a time.
Example:
char var1;
var1 = getchar(); /* it will read the next available char */
/* from stdin and return it */

 To read more than one character, we can use getchar() in a


loop.
CABSMJ1001 [2024-25]

getchar() Function - Example


#include<stdio.h>
main()
{ char var1;
printf("Enter a single character: ");
var1 = getchar();
printf("%c",var1);
}

 After entering the character, press <ENTER> key.


CABSMJ1001 [2024-25]

getch() Function (Reading a character from the Keyboard)

 It also reads a single character from the stdin i.e. keyboard.


 It reads the entered character immediately (without waiting
for the <ENTER> key to be pressed) and returns it.
 Entered character is not displayed on the screen.

Example:
char var1;
var1 = getch(); /* it will read the entered character */
/* from stdin and return it */
CABSMJ1001 [2024-25]

getch() Function - Example


#include<stdio.h>
main()
{ char var1;
printf("Enter a single character: ");
var1 = getch();
printf("\n"); Entered character
printf("%c",var1); is not displayed
}

 The character is read as soon as it is entered. No need to


press <ENTER> key.
CABSMJ1001 [2024-25]

getche() Function (Reading a character from the Keyboard)

 It also reads a single character from the stdin i.e. keyboard.


 It reads the entered character immediately (without waiting
for the <ENTER> key to be pressed) and returns it.
 Entered character is echoed on the screen.

Example:
char var1;
var1 = getche(); /* it will read the entered character */
/* from stdin and return it */
CABSMJ1001 [2024-25]

getche() Function - Example


#include<stdio.h>
main()
{ char var1;
printf("Enter a single character: ");
var1 = getche();
printf("\n"); Entered character
printf("%c",var1); is echoed
}

 The character is read as soon as it is entered. No need to


press <ENTER> key.
CABSMJ1001 [2024-25]

putchar() Function (Writing/displaying a character on the Screen)


 It writes (puts) the passed character on the standard output
stream (stdout) i.e. screen and returns the same character.
 It writes only a single character at a time.

Example: char var1 = 'A'; Output


putchar(var1); A
putchar('\n'); |
 Second line will display the character 'A' on the screen.
 Third line will cause the cursor on the screen to move to the
beginning of the next line.
 To display more than one character on the screen, we can use
putchar() in a loop.
CABSMJ1001 [2024-25]

C program to illustrate the use of getchar() and putchar()


functions
/* getcharex.c */
#include<stdio.h>
main()
{ char c1;
printf("Enter any character: ");
c1 = getchar();
printf("You entered: ");
putchar(c1);
putchar('\a'); /* it will produce a beep sound */
}
CABSMJ1001 [2024-25]

Character Library Functions


 C provides a set of standard library functions that work on
characters (char type data).
 These functions are defined in ctype.h header file:
Returns true (nonzero int value), if c is an
isalnum(c)
alphanumeric character.
isalpha(c) Returns true, if c is an alphabetic character.

isdigit(c) Returns true, if c is a digit.

islower(c) Returns true, if c is a lowercase letter.

isupper(c) Returns true, if c is an uppercase letter.


CABSMJ1001 [2024-25]

Character Library Functions

Returns true, if c is a punctuation mark like ( ) { }


ispunct(c)
[],;:*=#

Returns true, if c is a whitespace character


isspace(c)
like ' ', '\t', '\v', '\n', '\f' , '\r' characters.
Returns true, if c is a printable character.
isprint(c) (ASCII value 0 – 31: nonprintable characters) View
(ASCII value 32 – 126 : printable characters)
Converts the character c to its corresponding
tolower(c)
lowercase character and returns it.

Converts the character c to its corresponding


toupper(c)
uppercase character and returns it.
CABSMJ1001 [2024-25]

Prob

Write a C program that reads a lowercase alphabet and


converts it to uppercase.
CABSMJ1001 [2024-25]
/* lowertoupper.c */
#include<stdio.h>
#include<ctype.h>
main()
{ char c;
printf("Enter a lowercase alphabet: ");
c = getchar();
printf("Inputted character is: ");
putchar(c);
putchar('\n');
c = toupper(c);
printf("This alphabet in uppercase is: %c",c);
}
Enter a lowercase alphabet: t
Inputted character is: t
This alphabet in uppercase is: T
CABSMJ1001 [2024-25]

scanf() Function (Reading Data in a C Program from Keyboard)

 used to read formatted input from stdin (standard input


device) i.e. keyboard.

General form:
scanf("format string",&var1,&var2,…..);

 Format string contains format specifiers which specify what


type of data is to be read and assigned to each variable.

 Ampersand symbol ( & ) specifies variable’s memory address.

 It returns the number of items successfully read.


CABSMJ1001 [2024-25]

scanf() Function (Reading Data in a C Program from Keyboard)

Example-1: int num1, num2;


printf("Enter two integer numbers: ");
scanf("%d %d",&num1,&num2); /* input: 10 20 */
.........

 Format specifier %d specifies that an int value is to be read.

 Once the input values are typed and <Enter> key is pressed,
the values are read in the variables num1, num2 and the
computer proceeds to the next statement.
CABSMJ1001 [2024-25]

scanf() Function (Reading Data in a C Program from Keyboard)


Whitespace acts as delimiter
for scanf() by default
Example-2: float n1, n2;
printf("Enter two float numbers: ");
scanf("%f %f",&n1,&n2); /* 25.120 43.150 */
/* 25.120 43.150 */
/* 25.120
43.150 */
Whitespace causes scanf() to read input values and ignore all the whitespaces
appearing in the input and search for a non-whitespace character to read next
value.

Input can be entered in any of the three ways as shown above.


CABSMJ1001 [2024-25]

C Format Specifiers (or Type Conversion Characters)


Format
specifier Explanation Example

char ch;
%c A single character scanf("%c",&ch); /* input: A */
printf("%c",ch); /* output: A */
int x;
A decimal integer
%d scanf("%d",&x); /* input: -32526 */
(signed)
printf("%d",x); /* output: -32526 */
unsigned int x;
A decimal integer
%u scanf("%u",&x); /* input: 40501 */
(unsigned)
printf("%u",x); /* output: 40501 */
long int x;
A long decimal
%ld scanf("%ld",&x); /* input: -4535075 */
integer (signed)
printf("%ld",x); /* output: -4535075 */
CABSMJ1001 [2024-25]

C Format Specifiers (or Type Conversion Characters)


Format
specifier Explanation Example

unsigned long int x;


A long decimal
%lu scanf("%lu",&x); /* input: 4535075 */
integer (unsigned)
printf("%lu",x); /* output: 4535075 */
%o An octal integer int x;
(unsigned) scanf("%o",&x); /* input: 12 */
printf("%o",x); /* output: 12 */
printf("%#o",x); /* output: 012 */
printf("%d",x); /* output: 10 */
%h short integer (signed) unsigned short x;
%hu Short integer scanf("%hu",&x); /* input: 65535 */
(unsigned) printf("%hu",x); /* output: 65535 */
CABSMJ1001 [2024-25]

C Format Specifiers (or Type Conversion Characters)


Format
Explanation Example
specifier
%x or A hexadecimal int int h;
%X (unsigned) scanf("%X",&h); /* input: A */
printf("%X",h); /*output: A */
printf("%#x",h); /*output: 0xa */
printf("%d",h); /*output: 10 */
%f A floating point float x;
number scanf("%f",&x); /*input: 36.750 */
or printf("%f",x); /*output: 36.750000 */
%e or %E Scientific notation printf("%e",x); /*output: 3.675000e+001 */
or
printf("%g",x); /*output: 36.75 */
%g or %G %g uses %f or %e
whichever is shorter.
%G uses %f or %E %e, %E, %g and %G can be used
whichever is shorter. in printf() only.
Format CABSMJ1001 [2024-25]
specifier Explanation Example

%lf A double type double x;


number scanf("%lf",&x); /*input: 36.75432150 */
%le or %lE Scientific notation
printf("%lf",x); /*output: 36.754322 */
%lg or %lG %lg uses %lf or %le printf("%11.8lf",x);
whichever is shorter. /*output: 36.75432150 */
%lG uses %lf or %lE printf("%lE",x);
whichever is shorter. /* output: 3.675432E+001 */
%Lf A long double type long double x; /* input: 36.7546543 */
or number __mingw_scanf("%Lf",&x);
%Le,%LE, (they work same as __mingw_printf("%Lf",x);
%Lg,%LG above) /* output: 36.7546543 */
%s A string char city[21];
scanf("%s",city); /*input: Hyderabad */
printf("%s",city); /*output: Hyderabad */
%le, %lE, %lg and %lG can be
used in printf() only.
CABSMJ1001 [2024-25]

printf() Function (Outputting Results at the Screen)


 used to print formatted output at the standard output device
(stdout) i.e. computer screen.

General form:
printf("format string",var1,var2,…..);

 Format string:
 contains format specifiers which specify what type of data
(stored in the specified variables) is to be printed.
 may also optionally contain string constants that are
printed as they appear in the format string.
 It returns the total number of characters written, if successful.
On failure, a negative number is returned.
CABSMJ1001 [2024-25]

printf() Function
Following flags can also be included in the format specification:

Flag Description Example


- Used for left-justified printing within the %-6d
specified field width %-30s
(right-justification is the default)
+ Used to print the number preceded with a + %+d
or – sign (by default, only negative numbers
are preceded with a minus sign)
0 Used to print leading blanks as zeros within %06d
the specified field width
# Octal values to be preceded by 0 and %#o
Hex values to be preceded by 0x %#x
CABSMJ1001 [2024-25]

Outputting Integer Numbers Using printf()


Field width

 In the format specification, field width can also be specified.


 Format specification for inputting/outputting an integer: %wd
Examples: int i = 9876;
printf("%d", i); 9 8 7 6

printf("%6d", i); 9 8 7 6

printf("%2d", i); 9 8 7 6

printf("%-6d", i); 9 8 7 6

printf("%06d", i); 0 0 9 8 7 6

printf("%#X", i); 0 X 2 6 9 4
CABSMJ1001 [2024-25]

Outputting Float Type Numbers Using printf()


precision

 Format specification for printing in decimal notation: %w.pf


 Format specification for printing in sc. notation: %w.pe
Examples: float y=98.7654;
printf("%7.4f",y); 9 8 . 7 6 5 4

printf("%7.2f",y) ; 9 8 . 7 7

printf("%-7.2f",y); 9 8 . 7 7

printf("%f",y); 9 8 . 7 6 5 4 0 0

printf("%11.3E",y); 9 . 8 7 7 E + 0 0 1

printf("%g",y); 9 8 . 7 6 5 4
CABSMJ1001 [2024-25]

Outputting Double Type Numbers Using printf()


precision

 Format specification for printing in decimal notation: %w.plf


 Format specification for printing in sc. notation: %w.ple
Examples: double z=98.7654;
printf("%lf",z) 9 8 . 7 6 5 4 0 0

printf("%7.2lf",z) 9 8 . 7 7

printf("%le",z) 9 . 8 7 6 5 4 0 e + 0 0 1

printf("%lE",z) 9 . 8 7 6 5 4 0 E + 0 0 1

printf("%lg",z) 9 8 . 7 6 5 4

printf("%lG",z) 9 8 . 7 6 5 4
CABSMJ1001 [2024-25]

Prob

Write a C program that reads two integers and prints their sum
and average.
CABSMJ1001 [2024-25]

/* C program to read two integers and print their sum and average */
/*add2int.c */
#include<stdio.h>
main()
{ int num1, num2, sum;
float avg;
printf("Enter two integer numbers\n");
scanf("%d %d",&num1,&num2);
What will be the value of avg
sum = num1+num2;
if we write 2 instead of 2.0?
avg = sum/2.0;
printf("Sum= %d, Average= %f",sum,avg);
}
CABSMJ1001 [2024-25]

Prob

Write a C program that reads two numbers in variables a and b


and interchanges (swaps) their values.
CABSMJ1001 [2024-25]

/* swap.c */
#include<stdio.h>
main()
{ int a, b, temp;
printf("Enter two integer numbers: ");
scanf("%d %d",&a,&b);
temp = a;
a = b;
b = temp;
printf("Values of a and b after swapping\n");
printf("a = %d and b = %d",a,b);
}
CABSMJ1001 [2024-25]

Prob

Write a C program that reads two numbers in variables a and b


and interchanges (swaps) their values without using third
variable.
CABSMJ1001 [2024-25]

/* swap2.c */
#include<stdio.h>
main()
{ int a, b;
printf("Enter two integer numbers: ");
scanf("%d %d",&a,&b);
a = a + b;
b = a - b;
a = a - b;
printf("Values of a and b after swapping\n");
printf("a = %d and b = %d",a,b);
}
CABSMJ1001 [2024-25]

Prob

Write a C program that reads temperature in fahrenheit and


converts it into celsius.

C = ( F – 32 ) / 1.8
CABSMJ1001 [2024-25]

/* ftocelsius.c */
#include<stdio.h>
main()
{ float fahrenheit, celsius;
printf("Enter temperature in fahreheit\n");
scanf("%f",&fahrenheit);
celsius = (fahrenheit-32)/1.8;
printf("Temp. in Celsius = %6.2f",celsius);
}
CABSMJ1001 [2024-25]

Skipping An Input Field While Reading Using scanf()


 While reading, we can skip an input field.
 For this, a * is included in the corresponding field specification.

Example: skip
Input data: 123 456 789 int type variables
Input stat1: scanf("%d %*d %d",&num1,&num2);
or Input stat2: scanf("%3d %*3d %3d",&num1,&num2);

will assign
123 to num1
456 skipped (because of *)
789 to num2
CABSMJ1001 [2024-25]

Reading Integer Input Using scanf()


Note 1: While reading integers, field width can also be
specified.

Example: num1 num2

Input data: 31426518

scanf() statement to read above two int values:


int num1, num2;
scanf("%5d%3d",&num1,&num2);

will assign:
31426 to num1
518 to num2.
CABSMJ1001 [2024-25]

Reading Floating Point Input Using scanf()


Note 2: While reading float/double/long double type
numbers, field width is not to be specified.
scanf() reads them using the simple %f, %lf and %Lf format
specification for both the notations (decimal & exponential notation).
Example: Input data: 475.8943 4.3215E+2 678
scanf() statement to read above 3 values:
float x, y, z;
scanf("%f %f %f",&x, &y, &z);
will assign Field width can’t be specified
475.8943 to x
432.15 to y
678.0 to z
CABSMJ1001 [2024-25]

Reading Input Using scanf()


Note 3: Non-whitespace character:
 can be used between field specifications
 but a matching character must be there in the input data.
Examples:
Input data: 123-456-318 int type variables
scanf("%d-%d-%d",&num1,&num2,&num3);
or
scanf("%3d-%3d-%3d",&num1,&num2,&num3);

Input data: 150.5,160.5,170.5 float type variables


scanf("%f,%f,%f",&n1,&n2,&n3);
CABSMJ1001 [2024-25]

Note 4: When reading in numbers of any type and strings:


 scanf() treats white spaces (blanks, tabs, newlines,
carriage returns, form feeds and newlines) appearing in
the input as delimiters and
 skips them.
Examples:
scanf() statements Input (valid for both Contents of
the statements) variables
int i, j, k; i=10
scanf("%d %d %d",&i,&j,&k); 10 20 30 j=20
or or k=30
scanf("%d%d%d",&i,&j,&k); 10 20 30
or
10
20
30
CABSMJ1001 [2024-25]

Note 5: When reading in characters using scanf():


(i). white space(s) in the input are not skipped, if a space
character is not included in the format specification at that
position.
(ii). white space(s) in the input are skipped, if a space character
is included in the format specification at that position.
scanf() statement Input Contents of variables
char a,b,c,d; ARIF  a='A', b='R', c='I', d='F'
scanf("%c%c%c%c",&a,&b,&c,&d); or
A R I F  a='A', b=' ', c='R', d=' '
or
A  a='A',b='\n' ,c='R',d='\n'
R
I
F
CABSMJ1001 [2024-25]

Note 5: When reading in characters using scanf():


(i). white space(s) in the input are not skipped, if a space
character is not included in the format specification at that
position.
(ii). white space(s) in the input are skipped, if a space character
is included in the format specification at that position.
scanf() statement Input Contents of
variables
char a,b,c,d; ARIF  a= 'A'
scanf("%c %c %c %c",&a,&b,&c,&d); or b= 'R'
ARI F  c= 'I'
or d= 'F'
A 
R
I
F
CABSMJ1001 [2024-25]

Scope of
Variables
CABSMJ1001 [2024-25]

Scope of C Variables
 The scope of a C variable means:
 the section/region of the program where it has its
existence
 i.e. it cannot be used/accessed beyond that region.

 In C, variables can be declared at three places in a program:

Place in the program Type


1. Inside a function or inside a Local variables
block
2. Out of all functions Global variables
3. In the function parameters Formal parameters
Function CABSMJ1001 [2024-25]
body
1. Local Variables
 Variables declared inside a function
or block are called local variables. Block

 A function or block is a sequence of statements enclosed


within curly braces.

Local variables have local scope or block scope:


 Local variables can be used only by the statements that are
inside that function/block of code.
 So, variables declared within a block can be accessed:
 within that specific block and all other internal blocks of
that block
 but cannot be accessed outside the block.
CABSMJ1001 [2024-25]

Local Scope or Block Scope - Example


/* localvar.c */
#include<stdio.h>
main()
{ /* local variable declaration */
int a=10;
{ int b=20; Output:
{ int c=30; a=10, b=20 c=30 and d=60
int d = a + b + c;
printf ("a=%d, b=%d c=%d and d=%d\n",a,b,c,d);
}
/* c and d deleted from memory, not accessible here */
}
/* b deleted from memory, not accessible here */
}
CABSMJ1001 [2024-25]

2. Global Variables
 Variables declared outside of all functions (usually on top of
the program) and accessed inside the functions are called
global variables.

Global variables have global scope:


 A global variable is available for use till the end of program
from the point of its declaration.
 Any function can access global variables.
 Note: A program can have same name for local and global
variables but the value of local variable inside a function will
take preference.
CABSMJ1001 [2024-25]
Output:
Global Scope - Example Output of sum() function = 30
/* globalvar.c */ Output of subtract() function = -10
#include<stdio.h> a=10
int a=10; /* global variable - accessible till end of program */
int sum()
{ int b=20; /* local variable – accessible in function only */
return a+b;
}
int subtract() int a=30; /* what will be the output of a-b */
{ int b=20; /* local variable – accessible in function only */
return a-b;
}
main()
{ printf("Output of sum() function = %d\n",sum());
printf("Output of subtract() function = %d\n",subtract());
printf("a=%d",a);
}
CABSMJ1001 [2024-25]

Default Initial Values of Local Variables

 If a local variable is not assigned an initial value at the time of


its declaration, it takes the garbage value by default.
 For example:
Data type of Local variable Default Initial Value
int a; long l; Garbage value
char c; Garbage value
float f; double d; long double ld; Garbage value
int *p; /* p is a pointer variable */ Garbage value
CABSMJ1001 [2024-25]

Default Initial Values of Global Variables


 If a global variable is not initialized at the time of its
declaration:
 the compiler automatically initializes it
 based on its data type as below:

Data type of Global variable Default Initial Value


int a; long l; 0
char c; '\0' (null character is a built-in
constant that has a value of 0)
float f; double d; long double ld; 0.0
int *p; /* p is a pointer variable */ NULL (built-in pointer value that
does not point to any valid
data object)
Formal parameters
CABSMJ1001 [2024-25]

3. Formal Parameters int sum(int a,int b)


{ int sum = a+b;
return sum;
}

 They are treated as local variables within the function.

 Like local variables, they take precedence over global


variables within the function.
CABSMJ1001 [2024-25]

Formal Parameters - Example


/* formalparam.c */
#include<stdio.h>
int a = 50; /* global variable */
int sum(int a,int b) /* Formal parameters treated as local variables */
{ printf("value of a in sum() = %d\n",a); /* local a gets precedence */
return a+b;
}
main()
{ int a = 10; /* local a gets precedence over global a */
int b = 20;
int c = 0;
Output:
printf("value of a in main() = %d\n",a);
value of a in main() = 10
c = sum(a,b);
value of a in sum() = 10
printf("value of c in main() = %d\n",c);
value of c in main() = 30
}
CABSMJ1001 [2024-25]

#define
and
const keyword
CABSMJ1001 [2024-25]

#define Preprocessor Directive


 #define is used to define a symbolic constant (or macro
substitution).
 Macro substitution is a process where each occurrence of the
symbolic constant in the source program is replaced by the
string defined in the macro definition by the preprocessor.

General form: Symbolic constant


#define IDENTIFIER string

 If above statement (known as a macro definition or simply a macro):


 is included in a C program at the beginning,
 then the preprocessor replaces every occurrence of the
IDENTIFIER in the source code by the string.
CABSMJ1001 [2024-25]

#define Preprocessor Directive

 Examples: Symbolic constant

#define MAX 10 /*all occurrences of MAX will be replaced by 10 */


#define PI 3.1415926
#define CAPITAL "New Delhi"
 It is a convention to write macros in capitals to identify them
as symbolic constants.

Source code statements After preprocessing


total = MAX * value; total = 10 * value;
printf("MAX = %d\n",MAX); printf("MAX = %d\n",10);
String left unchanged
CABSMJ1001 [2024-25]

Example: C Program that reads radius of a circle and


finds its area & perimeter (using #define).
/* areaofcircle.c */
#include<stdio.h>
#define PI 3.14159
main()
{ float r, area, peri;
printf("Enter radius of circle\n");
scanf("%f",&r); PI will be replaced by 3.14159
area = PI * r * r; during preprocessing
peri = 2 * PI * r;
printf("Area= %.2f, Perimeter= %.2f",area,peri);
}
CABSMJ1001 [2024-25]

const keyword - Declaring a Variable as Constant


 If we want to keep the value of a certain variable constant
during the program execution, then:
 we can use the qualifier const
 at the time of variable’s declaration and initialization, e.g.:

const int max = 10; /* initial value must be assigned at the */


const float pi = 3.14159; /* time of const variable declaration */

 const qualifier tells the compiler that:


 the value of const variable must not be modified by the
program
 after an initial value is assigned in its declaration.
CABSMJ1001 [2024-25]

Example: to illustrate the use of const keyword.


/* constex.c */
#include<stdio.h>
main()
Value of pi can’t be modified
{ float r, area, peri; later in the program
const float pi = 3.14159;
printf("Enter radius of circle\n");
scanf("%f",&r);
area = pi * r * r;
peri = 2 * pi * r;
printf("Area= %.2f, Perimeter= %.2f",area,peri);
}
CABSMJ1001 [2024-25]

C
Operators
CABSMJ1001 [2024-25]

C Operators
 Operators are symbols that perform different operations on
variables and values.
 C supports a rich set of built-in operators that can be divided
into following EIGHT groups:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment & Decrement operators
6. Ternary (or Conditional) operator
7. Bitwise operators
8. Special operators
CABSMJ1001 [2024-25]

1. Arithmetic Operators
 used to perform mathematical operations on numeric values.
 They are:

Operator Description Example: int a=10;


int b=20;
+ Addition - Adds left hand operand
with right hand operand a + b will give 30

- Subtraction - Subtracts right hand


operand from left hand operand a - b will give -10

* Multiplication - Multiplies left


hand operand with R.H. operand a * b will give 200

Contd...
CABSMJ1001 [2024-25]

Operator Description Example: int a=10;


int b=20;

Division - Divides L.H. operand by


/ R.H. operand
b / a will give 2

Modulus - Divides L.H. operand


% by R.H. operand & returns the b % a will give 0
remainder
CABSMJ1001 [2024-25]

Precedence of Arithmetic Operators


 Arithmetic expressions are evaluated using the following rules of
precedence of arithmetic operators:
Operator Associativity
1st priority () Left-to-right
2nd priority */% Left-to-right
3rd priority +- Left-to-right

Order of operations can be


changed using parentheses:
Example: x = 9 – 12 / 3 + 3 * 2 – 1 Example: x = 9–12/(3+3)*(2–1)
x=9–4 +6 –1 x = 9–12/6 *1
x = 10 x = 9–2
x =7
CABSMJ1001 [2024-25]

Example: Illustrates the use of Arithmetic Operators


/* arithopex.c */
#include<stdio.h>
main()
{ int num1 = 15;
int num2 = 18;
printf("The sum is: %d\n",(num1+num2));
printf("The difference is: %d\n",(num1-num2));
printf("The product is: %d\n",(num1*num2));
printf("The average is: %f\n",((num1+num2)/2.0));
} Output
The sum is: 33
The difference is: -3
The product is: 270
The average is: 16.500000
CABSMJ1001 [2024-25]

Prob
Write a C program that reads two integer values in variables
dividend and divisor and finds the quotient and remainder when
dividend is divided by divisor.

Quotient = Dividend / Divisor; /* int division */


Remainder = Dividend % Divisor;
CABSMJ1001 [2024-25]

/* quotientrem1.c */
#include<stdio.h>
main()
{ int dividend, divisor, quotient, rem;
printf("Enter dividend and divisor (integer values): ");
scanf("%d %d", &dividend, &divisor);
quotient = dividend / divisor;
rem = dividend % divisor;
printf("Quotient = %d\n", quotient);
printf("Remainder = %d", rem);
} Output
Enter dividend and divisor (integer values): 25 6
Quotient = 4
Remainder = 1
CABSMJ1001 [2024-25]

Prob

Write a C program that reads base and height of a triangle and


prints area of the triangle.
CABSMJ1001 [2024-25]

/* areaoftriangle.c */
#include<stdio.h>
main()
{ float base, height, area;
printf("Enter base and height of the triangle: ");
scanf("%f %f",&base,&height);
area = (base * height) / 2;
printf("Area of the triangle = %f",area);
}
Output
Enter base and height of the triangle: 10 5
Area of the triangle = 25.000000
CABSMJ1001 [2024-25]

Prob
Write a C program that reads time in seconds and converts it
into hours, minutes and seconds.

secs hrs mins


3740 (input)
secs/3600
i.e. 3740/3600 = 1
secs%3600
i.e. 3740%3600=140
secs/60
i.e. 140/60 = 2
secs%60
i.e. 140%60=20
CABSMJ1001 [2024-25]
secs hrs mins
/* seconds.c */ 3740
#include<stdio.h> 1
main() 140
{ int secs, hrs, mins; 2
printf("Enter time in seconds: "); 20
scanf("%d",&secs);
hrs = secs/3600; /* time in hours */
secs = secs % 3600; /* remaining secs */
mins = secs/60; /* time in mins */
secs = secs % 60; /* remaining secs */
printf("Time= %d hours %d minutes %d seconds",hrs,mins,secs);
}
Output
Enter time in seconds: 3740
Time= 1 hours 2 minutes 20 seconds
CABSMJ1001 [2024-25]

Prob
Write a C program to calculate the distance between two points
(x1,y1) and (x2,y2) on a x-y plane using the formula:
CABSMJ1001 [2024-25]
/* distance.c illustrates the use of sqrt() and pow() library functions */
#include<stdio.h>
#include<math.h>
main()
{ float x1, y1, x2, y2, dist;
printf("Input x1 and y1: ");
scanf("%f %f",&x1,&y1);
printf("Input x2 and y2: ");
scanf("%f %f",&x2,&y2);
/* Calculate the distance between the points */
dist = sqrt(pow((x2-x1),2)+pow((y2-y1),2));
printf("Distance between the points: %.2f",dist);
}
Output
Input x1 and y1: 5 6
Input x2 and y2: 15 16
Distance between the points: 14.14
CABSMJ1001 [2024-25]

Convert the following Algebraic Expressions into


C Expressions:
Algebraic expression C expression
(a x b) – c ( a * b ) - c or a * b - c
(m+n)(x+y) (m+n)*(x+y)
ab
 (a * b) / c or a*b/c
c
3x2+2x+1 3*x*x+2*x+1
or
3 * pow(x,2) + 2 * x + 1
x
 +c (x/y)+c or x / y + c
y
CABSMJ1001 [2024-25]
Exercise #1.
Write a C program that reads length and breadth of a rectangle
and prints its area.
Exercise #2.
Write a C program that reads temperature in Centigrade and
converts it to Fahrenheit. Temperature conversion formula is:
F = 1.8 * C + 32
Exercise #3.
Write a C program that reads principle, time and rate (P, T, R)
from user and finds Simple Interest. Simple interest formula is:
P*T*R
SI =    
100
For example, if principle= 1200, time= 2 years, rate= 5.4%
Then Simple Interest = 129.600006
Exercise #4.
Write a C program that reads an integer in the range 32 to 126
and prints the character represented by it.
CABSMJ1001 [2024-25]

Exercise #5.
Write a C program that reads weight in pounds and converts it
into kilograms. Weight conversion formula is:
kilogram = pound * 0.453592
Exercise #6.
Write a C program to read the following 4 numbers, round them
off to the nearest integers and print them in integer form:
35.7 50.21 -23.73 -46.45
Exercise #7.
Write a C program that reads number of days from the user and
converts it to years, weeks and days. Assume that:
1 year = 365 days (ignoring leap year)
1 week = 7 days
For example, 374 days = 1 year/s, 1 week/s and 2 day/s.
CABSMJ1001 [2024-25]

Exercise #8.
Write a C program to read the amount value and break it into
the smallest possible indian currency notes. Assume that 500,
200, 100, 50, 20, 10, 5, 2 and 1 rupee notes are in use.
For example, Rs.5888 should be broken as below:
500 note(s) = 11
200 note(s) = 1
100 note(s) = 1
50 note(s) = 1
20 note(s) = 1
10 note(s) = 1
5 note(s) =1
2 note(s) = 1
1 note(s) =1
CABSMJ1001 [2024-25]

Exercise #9.
Write a C program that reads a floating point number and then
displays the right-most digit of the integral part of the number.
Exercise #10.
Write a C program that reads a 4-digit integer number and
displays the number as follows:
First line : all digits
Second line : all except first digit
Third line : all except first two digits
Fourth line : the last digit.
For example, the 4-digit number 5678 should be displayed as:
5678
678
78
8
CABSMJ1001 [2024-25]

End of
Unit-I

You might also like