Unit II - Notes
Unit II - Notes
Introduction to C Programming
Contents :
2.1 Features of C
C is a procedural programming language. It was initially developed by Dennis Ritchie in
the year 1972. It was mainly developed as a system programming language to write an
operating system. The main features of C language include low-level access to memory, a
simple set of keywords, and clean style, these features make C language suitable for
system programming like an operating system or compiler development.
Preprocesso
Syntax/Description
r
Syntax: #define
Macro This macro defines constant value and can be any of the basic
data types.
Global Variables
Global variables are defined outside a function, usually on top of the program. Global
variables hold their values throughout the lifetime of your program and they can be
accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available
for use throughout your entire program after its declaration. The following program
show how global and local variables are used in a program.
Local Variables
Local Variable is defined as a type of variable declared within programming block or
subroutines. It can only be used inside the subroutine or code block in which it is
declared. The local variable exists until the block of the function is under execution. After
that, it will be destroyed automatically.
#include <stdio.h>
/* global variable declaration */
int g;
int main () {
/* actual initialization */
a = 10;
b = 20;
g = a + b;
return 0;
}
A program can have same name for local and global variables but the value of local
variable inside a function will take preference. Here is an example –
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result –
value of g = 10
There are three places where variables you can declare variable programming language:
● You can access the global variable from all the functions or modules in a program
● You only require to declare global variable single time outside the modules.
● It is ideally used for storing "constants" as it helps you keep the consistency.
● A Global variable is useful when multiple functions are accessing the same data.
Advantages of using Local Variables
● The use of local variables offer a guarantee that the values of variables will
remain intact while the task is running
● If several tasks change a single variable that is running simultaneously, then the
result may be unpredictable. But declaring it as local variable solves this issue as
each task will create its own instance of the local variable.
● You can give local variables the same name in different functions because they
are only recognized by the function they are declared in.
● Local variables are deleted as soon as any function is over and release the
memory space which it occupies.
● Too many variables declared as global, then they remain in the memory till
program execution is completed. This can cause of Out of Memory issue.
● Data can be modified by any function. Any statement written in the program can
change the value of the global variable. This may give unpredictable results in
multi-tasking environments.
● If global variables are discontinued due to code refactoring, you will need to
change all the modules where they are called.
int 0
char '\0'
float 0
double 0
pointer NULL
void main()
……
…..
In above syntax;
Suppose, you need to create a circle and color it depending upon the radius and color.
You can create two functions to solve this problem:
● createCircle() function
● color() function
Note : You may refer the reference book to read more about the user defined
functions.
A program in C language involves into different processes. Below diagram will help you
to understand all the processes that a C program comes across.
The compilation is a process of converting the source code into object code. It is done
with the help of the compiler. The compiler checks the source code for the syntactical or
structural errors, and if the source code is error-free, then it generates the object code.
sample.c
1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello javaTpoint");
5. return 0;
6. }
DO YOU KNOW DIFFERENCE BETWEEN STACK & HEAP MEMORY IN C LANGUAGE?
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable
in C has a specific type, which determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of operations that can be applied to the
variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive.
Based on the basic types explained in the previous chapter, there will be the following basic variable data
types −
1
char
Typically a single octet(one byte). It is an integer type.
2
int
The most natural size of integer for the machine.
3
float
A single-precision floating point value.
4
double
A double-precision floating point value.
5
void
Represents the absence of type.
C programming language also allows to define various other types of variables, like Enumeration,
Pointer, Array, Structure, Union.
A variable declaration tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of one or more
variables of that type as follows –
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined
object; and variable_list may consist of one or more identifier names separated by commas. Some valid
declarations are shown here –
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the
compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The
initializer consists of an equal sign followed by a constant expression as follows –
type variable_name = value;
Ex .
int d = 3, f = 5; // definition and initializing d
and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value
'x'.
Variable declaration refers to the part where a variable is first declared or introduced
before its first use. Variable definition is the part where the variable is assigned a
memory location and a value. Most of the times, variable declaration and definition are
done together.
Rules for defining variables
1. A variable can have alphabets, digits, and underscore.
2. A variable name can start with the alphabet, and underscore only. It can’t start with a
digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or keyword, e.g. int, goto , etc.
C Keywords and Identifiers
Character set
A character set is a set of alphabets, letters and some special characters that are valid in
C language.
Alphabets
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
0123456789
Special Characters
, < > . _
( ) ; $ :
% [ ] # ?
^ ! * / |
- \ ~ +
C Keywords
Keywords are predefined, reserved words used in programming that have special
meanings to the compiler. Keywords are part of the syntax and they cannot be used as an
identifier. For example:
int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list
of all keywords allowed in ANSI C.
C Keywords
auto double int struct
do if static while
C Identifiers
Identifier refers to names given to entities such as variables, functions, structures etc.
Identifiers must be unique. They are created to give a unique name to an entity to
identify it during the execution of the program. For example:
int money
double accountBalance
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
1. Arithmetic Operators:
Arithmetic
Operators/Operation Example
+ (Addition) A+B
– (Subtraction) A-B
* (multiplication) A*B
/ (Division) A/B
% (Modulus) A%B
2. Assignment operators :
In C programs, values for the variables are assigned using assignment operators.
For example, if the value “10” is to be assigned for the variable “sum”, it can be assigned
as “sum = 10;”
Operators Example/Description
sum = 10;
= 10 is assigned to variable sum
sum += 10;
+= This is same as sum = sum + 10
sum -= 10;
-= This is same as sum = sum – 10
sum *= 10;
*= This is same as sum = sum * 10
sum /= 10;
/= This is same as sum = sum / 10
sum %= 10;
%= This is same as sum = sum % 10
sum&=10;
&= This is same as sum = sum & 10
sum ^= 10;
^= This is same as sum = sum ^ 10
3. Relational operators
Relational operators are used to find the relation between two variables. i.e. to
compare the values of two variables in a C program.
Operators Example/Description
== x == y (x is equal to y)
!= x != y (x is not equal to y)
#include<stdio.h>
int main()
{
m = 40, n =20;
if (m==n)
{
printf(“\n m and n are equal”);
}
else
{
printf(“m and n are not equal”);
}
}
Output:
m and n are not equal
4. Logical operators
These operators are used to perform logical operations on the given expressions.
● There are 3 logical operators in C language. They are, logical AND (&&), logical OR
(||) and logical NOT (!).
Operators Example/Description
(x>=10)||(y>=10)
|| (logical OR) It returns true when at-least one of the condition is true
! (logical !((x>5)&&(y<5))
NOT) It reverses the state of the operand “((x>5) && (y<5))”
If “((x>5) && (y<5))” is true, logical NOT operator makes it
false
Example
#include <stdio.h>
int main()
{
int m=40,n=20;
int o=20,p=30;
if (m>n && m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true.
But, status is inverted as false\n");
}
}
Output :
● Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise
NOT), ^ (XOR), << (left shift) and >> (right shift).
TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:
BELOW ARE THE BIT-WISE OPERATORS AND THEIR NAME IN C LANGUAGE.
1. & – Bitwise AND
2. | – Bitwise OR
3. ~ – Bitwise NOT
4. ^ – XOR
5. << – Left Shift
6. >> – Right Shift
Consider x=40 and y=80. Binary form of these values are given below.
x=00101000
y= 01010000
#include <stdio.h>
int main()
{
int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );
printf("NOT_opr value = %d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}
Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
int main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}
OUTPUT:
x value is 1
y value is 2
7. Increment/decrement operators
● Increment operators are used to increase the value of the variable by one and
decrement operators are used to decrease the value of the variable by one in C
programs.
● Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
● Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
EXAMPLE PROGRAM FOR INCREMENT OPERATORS IN C:
In this program, value of “i” is incremented one by one from 1 up to 9 using “i++”
operator and output is displayed as “1 2 3 4 5 6 7 8 9”.
//Example for increment operators
#include <stdio.h>
int main()
{
int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}
OUTPUT:
123456789
EXAMPLE PROGRAM FOR DECREMENT OPERATORS IN C:
In this program, value of “i” is decremented one by one from 20 up to 11 using “i–”
operator and output is displayed as “20 19 18 17 16 15 14 13 12 11”.
//Example for decrement operators
#include <stdio.h>
int main()
{
int i=20;
while(i>10)
{
printf("%d ",i);
i--;
}
}
OUTPUT:
20 19 18 17 16 15 14 13 12 11
Note : You may skip the examples if you are not aware of looping construct.
EXAMPLE PROGRAM FOR PRE – INCREMENT OPERATORS IN C:
//Example for increment operators
#include <stdio.h>
int main()
{
int i=0;
while(++i < 5 )
{
printf("%d ",i);
}
return 0;
}
OUTPUT:
1234
● Step 1 : In above program, value of “i” is incremented from 0 to 1 using pre-
increment operator.
● Step 2 : This incremented value “1” is compared with 5 in while expression.
● Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
● Above 3 steps are continued until while expression becomes false and output is
displayed as “1 2 3 4”.
8. Special operators
Below are some of the special operators that the C programming language offers.
Operators Description
Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
#include <stdio.h>
main()
int a =
// ( 30 * 15 ) /
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) /
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = a + (b * c) / // 20 +
printf("Value of a + (b * c) / d is : %d\n" , e
);
}
When you compile and execute the above program, it produces the following result:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
2.6 type conversions/ Casting
Type casting is a way to convert a variable from one data type to another data type. For
example, if you want to store a long value into a simple integer then you can type cast long
to int. You can convert values from one type to another explicitly using the cast operator
as follows:
(type_name) expression
Consider the following example where the cast operator causes the division of one integer
variable by another to be performed as a floating-point operation:
#include <stdio.h>
main()
When the above code is compiled and executed, it produces the following result:
It should be noted here that the cast operator has precedence over division, so the value of
sum is first converted to type double and finally it gets divided by count yielding a double
value.
The Integer promotion is the process by which values of integer type "smaller" than int or
unsigned int are converted either to int or unsigned int. Consider an example of adding a character
in an int:
#include <stdio.h>
main()
int i = 17;
When the above code is compiled and executed, it produces the following result:
Here, value of sum is coming as 116 because compiler is doing integer promotion and converting the
value of 'c' to ascii before performing actual addition operation.
The usual arithmetic conversions are implicitly performed to cast their values in a common type.
Compiler first performs integer promotion, if operands still have different types then they are
converted to the type that appears highest in the following hierarchy:
The usual arithmetic conversions
are not performed for the
assignment operators, nor for the
logical operators && and ||. Let us
take following example to
understand the concept:
#include <stdio.h>
main()
int i = 17;
sum = i + c;
When we are saying Input that means to feed some data into program. This can be
given in the form of file or from command line. C programming language provides a
set of built-in functions to read given input and feed it to the program as per
requirement.
When we are saying Output that means to display some data on screen, printer or in
any file. C programming language provides a set of built-in functions to output the
data on the computer screen as well as you can save that data in text or binary files.
C programming language treats all the devices as files. So devices such as the display
are addressed in the same way as files and following three file are automatically
opened when a program executes to provide access to the keyboard and screen.
The file points are the means to access the file for reading and writing purpose. This
section will explain you how to read values from the screen and how to print the
result on the screen.
The int getchar(void) function reads the next available character from the screen and
returns it as an integer. This function reads only single character at a time. You can
use this method in the loop in case you want to read more than one characters from
the screen.
The int putchar(int c) function puts the passed character on the screen and returns the
same character. This function puts only single character at a time. You can use this
method
in the loop in case you want to display more than one character on the screen. Check
the following example:
#include <stdio.h>
int main( )
int c;
putchar(c);
return 0;
When the above code is compiled and executed, it waits for you to input some text when you
enter a text and press enter then program proceeds and reads only a single character and displays
it as follows:
$./a.out
#include <stdio.h>
int main( )
char str[100];
return 0;
The int puts(const char *s) function writes the string s and a trailing newline to stdout.
When the above code is compiled and executed, it waits for you to input some text
when you enter a text and press enter then program proceeds and reads the complete
line till end and displays it as follows:
$./a.out
The int scanf(const char *format, ...) function reads input from the standard input
stream stdin and scans that input according to format provided.
The int printf(const char *format, ...) function writes output to the standard output
stream stdout and produces output according to a format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc.,
to print or read strings, integer, character or float respectively. There are many other
formatting options available which can be used based on requirements. For a
complete detail you can refer to a man page for these function. For now let us proceed
with a simple example which makes things clear:
#include <stdio.h>
int main( )
return 0;
When the above code is compiled and executed, it waits for you to input some text
when you enter a text and press enter then program proceeds and reads the input and
displays it as follows:
$./a.out
Here, it should be noted that scanf() expect input in the same format as you provided
%s and %d, which means you have to provide valid input like "string integer", if you
provide "string string" or "integer integer" then it will be assumed as wrong input.
Second, while reading a string scanf() stops reading as soon as it encounters a space
so "this is test" are three strings for scanf().
Case Study: Exchanging the values of two variables, summation of a set of numbers.