CS8251 Programming in C
CS8251 Programming in C
Unit 1: PROGRAMMING IN C
Even though most new languages are multi-paradigm, they usually make it easiest to
program in a single paradigm; C programs can be written in a functional
programming style (instead of the orthodox procedural fashion) – it is just
extremely difficult. Ever wondered why classes are needed to add two numbers in
OOP Java?
Nearly every standard problem can be solved using any of the programming
paradigms however some problems are best solved using some paradigms (e.g.
recursion vs loops). Thus knowing many paradigms helps programmers in
producing very neat and elegant solutions; since they know different ways of solving
problems and modelling domains.
1. Imperative Programming
The imperative paradigm was quite popular until Dijkstra published his famous
‘GOTO considered harmful‘ letter. This fueled the adoption of the structured
programming paradigm (albeit at the detriment of imperative programming).
2. Structured Programming
Structured programming is somewhat similar to imperative programming however
control flow is defined in terms of loops, subroutines and conditionals; this
distinguishes it from the imperative model of jumping around at the heck and bequest
of every GOTO call.
The introduction of lexical scoping also helps to prevent the inadvertent overwriting
of variables in the global scope.
3. Declarative Programming
Declarative programs have implicit execution: programs say what they want but not
how the results should be gotten. SQL is a popular example, have you ever wondered
how the SQL engine is able to calculate sums, averages, max etc.
Pure functional programs are written as a combination of function calls which have
no side effects and return the same result every time they are called with the same
input no matter the environment. The elegance of FP comes from the use of higher-
order functions (functions which can accept/return other functions e.g.
differentiation/integration in the maths domain), referential transparency and high
levels of abstraction.
OOP allows the creation of abstract models that mirror real-life objects’ interactions
and behaviour. This enables the creation of huge complex software systems having
intricate interactions such as state preservation, communication exchanges and
behaviour handling.
There are two flavours: classical (where objects are defined and share their
characteristics and behaviour based on a class’ blueprint) and prototypical (objects
get their behaviour and characteristics from an original prototype object).
Conclusion
Some other paradigms include the event-driven where program respond to events
(think web apps) while the logical programming paradigm tries to infer the solution
when it is given a set of constraints and or conditions.
Structure of C program
Before we study the basic building blocks of the C programming language, let us
look at a bare minimum C program structure so that we can take it as a reference in
the upcoming chapters.
A C program basically consists of the following parts −
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
Let us look at a simple code that would print the words "Hello World" −
#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
You have seen the basic structure of a C program, so it will be easy to understand
other basic building blocks of the C programming language.
Tokens in C
A C program consists of various tokens and a token is either a keyword, an
identifier, a constant, a string literal, or a symbol. For example, the following C
statement consists of five tokens −
printf("Hello, World! \n");
The individual tokens are −
printf
("Hello, World! \n"
)
;
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual
statement must be ended with a semicolon. It indicates the end of one logical entity.
Given below are two different statements −
printf("Hello, World! \n");
return 0;
Comments
Comments are like helping text in your C program and they are ignored by the
compiler. They start with /* and terminate with the characters */ as shown below −
/* my first program in C */
You cannot have comments within comments and they do not occur within a string
or character literals.
Identifiers
A C identifier is a name used to identify a variable, function, or any other user-
defined item. An identifier starts with a letter A to Z, a to z, or an underscore '_'
followed by zero or more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is
a case-sensitive programming language. Thus, Manpower and manpower are two
different identifiers in C. Here are some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
Keywords
The following list shows the reserved words in C. These reserved words may not be
used as constants or variables or any other identifier names.
double
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank
line, and a C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and
comments. Whitespace separates one part of a statement from another and
enables the compiler to identify where one element in a statement, such as int,
ends and the next element begins. Therefore, in the following statement −
int age;
there must be at least one whitespace character (usually a space) between int and
age for the compiler to be able to distinguish them. On the other hand, in the
following statement −
fruit = apples + oranges; // get the total fruit
no whitespace characters are necessary between fruit and =, or between = and
apples, although you are free to include some if you wish to increase readability.
C Programming:
Data Types
Data types in c refer to an extensive system used for declaring variables or functions
of different types. The type of a variable determines how much space it occupies in
storage and how the bit pattern stored is interpreted.
1 Basic Types
They are arithmetic types and are further classified into: (a) integer
types and (b) floating-point types.
2 Enumerated types
They are again arithmetic types and they are used to define variables
that can only assign certain discrete integer values throughout the
program.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types,
(d) Union types and (e) Function types.
The array types and structure types are referred collectively as the aggregate types.
The type of a function specifies the type of the function's return value. We will see
the basic types in the following section, where as other types will be covered in the
upcoming chapters.
Integer Types
The following table provides the details of standard integer types with their storage
sizes and value ranges −
Type Storage size Value range
To get the exact size of a type or a variable on a particular platform, you can use the
sizeof operator. The expressions sizeof(type) yields the storage size of the object or
type in bytes. Given below is an example to get the size of int type on any machine −
#include <stdio.h>
#include <limits.h>
int main() {
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}
When you compile and execute the above program, it produces the following result
on Linux −
Storage size for int : 4
Floating-Point Types
The following table provide the details of standard floating-point types with storage
sizes and value ranges and their precision −
The header file float.h defines macros that allow you to use these values and other
details about the binary representation of real numbers in your programs. The
following example prints the storage space taken by a float type and its range values
−
#include <stdio.h>
#include <float.h>
int main() {
printf("Storage size for float : %d \n", sizeof(float));
printf("Minimum float positive value: %E\n", FLT_MIN );
printf("Maximum float positive value: %E\n", FLT_MAX );
printf("Precision value: %d\n", FLT_DIG );
return 0;
}
When you compile and execute the above program, it produces the following result
on Linux −
Storage size for float : 4
Minimum float positive value: 1.175494E-38
Maximum float positive value: 3.402823E+38
Precision value: 6
3 Pointers to void
A pointer of type void * represents the address of an object, but not
its type. For example, a memory allocation function void
*malloc( size_t size ); returns a pointer to void which can be casted
to any data type.
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 types −
Sr.No. Type & Description
1 char
Typically a single octet(one byte). This 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.
Variable Definition in C
A variable definition 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;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
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'.
For definition without an initializer: variables with static storage duration are
implicitly initialized with NULL (all bytes have the value 0); the initial value of all
other variables are undefined.
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable
with the given type and name so that the compiler can proceed for further
compilation without requiring the complete detail about the variable. A variable
definition has its meaning at the time of compilation only, the compiler needs actual
variable definition at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define
your variable in one of the files which will be available at the time of linking of the
program. You will use the keyword extern to declare a variable at any place. Though
you can declare a variable multiple times in your C program, it can be defined only
once in a file, a function, or a block of code.
Example
Try the following example, where variables have been declared at the top, but they
have been defined and initialized inside the main function −
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of c : 30
value of f : 23.333334
The same concept applies on function declaration where you provide a function name
at the time of its declaration and its actual definition can be given anywhere else. For
example −
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}
lvalue − Expressions that refer to a memory location are called "lvalue" expressions.
An lvalue may appear as either the left-hand or right-hand side of an assignment.
rvalue − The term rvalue refers to a data value that is stored at some address in
memory. An rvalue is an expression that cannot have a value assigned to it which
means an rvalue may appear on the right-hand side but not on the left-hand side of an
assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment.
Numeric literals are rvalues and so they may not be assigned and cannot appear on
the left-hand side. Take a look at the following valid and invalid statements −
Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program. They precede the type that they modify. We have four
different storage classes in a C program −
auto
register
static
extern
The auto Storage Class
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can
only be used within functions, i.e., local variables.
{
register int miles;
}
The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the
variable will be stored in a register. It means that it MIGHT be stored in a register
depending on hardware and implementation restrictions.
The static modifier may also be applied to global variables. When this is done, it
causes that variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy
of that member to be shared by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
When you have multiple files and you define a global variable or function, which
will also be used in other files, then extern will be used in another file to provide the
reference of defined variable or function. Just for understanding, extern is used to
declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing
the same global variables or functions as explained below.
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Second File: support.c
#include <stdio.h>
void write_extern(void) {
printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, where as it has its
definition in the first file, main.c. Now, compile these two files as follows −
count is 5
Constants
Constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are enumeration constants as
well.
Constants are treated just like regular variables except that their values cannot be
modified after their definition.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies
the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for
unsigned and long, respectively. The suffix can be uppercase or lowercase and can be
in any order.
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of integer literals −
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an
exponent part. You can represent floating point literals either in decimal form or
exponential form.
While representing decimal form, you must include the decimal point, the exponent,
or both; and while representing exponential form, you must include the integer part,
the fractional part, or both. The signed exponent is introduced by e or E.
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple
variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or
a universal character (e.g., '\u02C0').
There are certain characters in C that represent special meaning when preceded by a
backslash for example, newline (\n) or tab (\t).
#include <stdio.h>
int main() {
printf("Hello\tWorld\n\n");
return 0;
}
When the above code is compiled and executed, it produces the following result −
Hello World
String Literals
String literals or constants are enclosed in double quotes "". A string contains
characters that are similar to character literals: plain characters, escape sequences,
and universal characters.
You can break a long line into multiple lines using string literals and separating them
using white spaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
Defining Constants
There are two simple ways in C to define constants −
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.
Enumeration Constants
An enumeration is a user-defined data type that consists of integral constants. To
define an enumeration, keyword enum is used.
By default, const1 is 0, const2 is 1 and so on. You can change default values of
enum elements during declaration (if necessary).
// Changing default values of enum
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3,
};
Enumerated Type Declaration
When you create an enumerated type, only blueprint for the variable is created.
Here's how you can create variables of enum type.
Here is another way to declare same check variable using different syntax.
enum boolean
{
false, true
} check;
int main()
{
enum week today;
today = wednesday;
printf("Day %d",today+1);
return 0;
}
Output
Day 4
Why enums are used in C programming?
Enum variable takes only one value out of many possible values. Example to
demonstrate it,
#include <stdio.h>
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;
int main()
{
card = club;
printf("Size of enum variable = %d bytes", sizeof(card));
return 0;
}
Output
You can accomplish the same task using structures. However, working with enums
gives you efficiency along with flexibility.
enum designFlags {
ITALICS = 1,
BOLD = 2,
UNDERLINE = 4
} button;
Suppose you are designing a button for Windows application. You can set flags
ITALICS, BOLD and UNDERLINE to work with text.
There is a reason why all the integral constants are power of 2 in above pseudocode.
// In binary
ITALICS = 00000001
BOLD = 00000010
UNDERLINE = 00000100
Since, the integral constants are power of 2, you can combine two or more flags at
once without overlapping using bitwise OR | operator. This allows you to choose two
or more flags at once. For example,
#include <stdio.h>
enum designFlags {
BOLD = 1,
ITALICS = 2,
UNDERLINE = 4
};
int main() {
int myDesign = BOLD | UNDERLINE;
// 00000001
// | 00000100
// ___________
// 00000101
printf("%d", myDesign);
return 0;
}
Output
5
When the output is 5, you always know that bold and underline is used.
Keywords
Keywords in C Programming
auto
The auto keyword declares automatic variables. For example:
Variables declared within function bodies are automatic by default. They are
recreated each time a function is executed.
Since, automatic variables are local to a function, they are also called local variables.
The continue statement skips the certain statements inside the loop.
for (i=1;i<=10;++i)
{
if (i==3)
continue;
if (i==7)
break;
printf("%d ",i);
}
Output
12456
When i is equal to 3, continue statement comes into effect and skips 3. When i is
equal to 7, break statement comes into effect and terminates the for loop.
switch(expression)
{
case '1':
//some statements to execute when 1
break;
case '5':
//some statements to execute when 5
break;
default:
//some statements to execute when default;
}
char
The char keyword declares a character variable. For example:
char alphabet;
Here, alphabet is a character type variable.
const
An identifier can be declared constant by using const keyword.
const int a = 5;
do...while
int i;
do
{
print("%d ",i);
i++;
}
while (i<10)
float number;
double longNumber;
Here, number is single precision floating type variable whereas, longNumber is a
double precision floating type variable.
if and else
In C programming, if and else are used to make decisions.
if (i == 1)
printf("i is 1.")
else
prinf("i is not 1.")
If value of i is other than 1, output will be :
i is not 1
enum
Enumeration types are declared in C programming using keyword enum. For
example:
enum suit
{
hearts;
spades;
clubs;
diamonds;
};
Here, a enumerated variable suit is created having tags: hearts, spades, clubs and
diamonds.
extern
The extern keyword declares that a variable or a function has external linkage outside
of the file it is declared.
for
There are three types of loops in C programming. The for loop is written in C
programming using keyword for. For example:
012345678
goto
The goto keyword is used for unconditional jump to a labeled statement inside a
function. For example:
for(i=1; i<5; ++i)
{
if (i==10)
goto error;
}
printf("i is not 10");
error:
printf("Error, count cannot be 10.");
Output
int
The int keyword declares integer type variable. For example:
int count;
Here, count is a integer variable.
return
The return keyword terminates the function and returns the value.
int func()
{
int b = 5;
return b;
}
This function func() returns 5 to the calling function.
sizeof
The sizeof keyword evaluates the size of data (a variable or a constant).
#include <stdio.h>
int main()
{
printf("%u bytes.",sizeof(char));
}
Output
1 bytes.
register
The register keyword creates register variables which are much faster than normal
variables.
static
The static keyword creates static variable. The value of the static variables persists
until the end of the program. For example:
struct
The struct keyword is used for declaring a structure. A structure can hold variables of
different types under a single name.
struct student{
char name[80];
float marks;
int age;
}s1, s2;
typedef
The typedef keyword is used to explicitly associate a type with an identifier.
union
A Union is used for grouping different types of variable under a single name.
union student
{
char name[80];
float marks;
int age;
}
void
The void keyword indicates that a function doesn't return any value.
void testFunction(int a)
{
.....
}
Here, function testFunction( ) cannot return a value because the return type is void.
volatile
The volatile keyword is used for creating volatile objects. A volatile object can be
modified in an unspecified way by the hardware.
Since, number is a constant variable, the program cannot change it. However,
hardware can change it since it is a volatile object.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
We will, in this chapter, look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable B holds 20 then −
Operator Description Example
Try the following example to understand all the arithmetic operators available in C −
Live Demo
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
When you compile and execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then −
Operator Description Example
Example
Try the following example to understand all the relational operators available in C −
Live Demo
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
printf("Line 1 - a is equal to b\n" );
} else {
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b ) {
printf("Line 2 - a is less than b\n" );
} else {
printf("Line 2 - a is not less than b\n" );
}
if ( a > b ) {
printf("Line 3 - a is greater than b\n" );
} else {
printf("Line 3 - a is not greater than b\n" );
}
if ( a <= b ) {
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a ) {
printf("Line 5 - b is either greater than or equal to b\n" );
}
}
When you compile and execute the above program, it produces the following result −
Example
Try the following example to understand all the logical operators available in C −
Live Demo
#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
printf("Line 1 - Condition is true\n" );
}
if ( a || b ) {
printf("Line 2 - Condition is true\n" );
}
if ( a && b ) {
printf("Line 3 - Condition is true\n" );
} else {
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) ) {
printf("Line 4 - Condition is true\n" );
}
}
When you compile and execute the above program, it produces the following result −
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for
&, |, and ^ is as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A'
holds 60 and variable 'B' holds 13, then −
Operator Description Example
& Binary AND Operator copies a bit to the (A & B) = 12, i.e.,
result if it exists in both operands. 0000 1100
| Binary OR Operator copies a bit if it (A | B) = 61, i.e.,
exists in either operand. 0011 1101
Example
Try the following example to understand all the bitwise operators available in C −
#include <stdio.h>
main() {
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Assignment Operators
The following table lists the assignment operators supported by the C language −
Operator Description Example
Example
Try the following example to understand all the assignment operators available in C
−
#include <stdio.h>
main() {
int a = 21;
int c ;
c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c );
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c );
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n", c );
c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );
c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );
c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %d\n", c );
c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
}
When you compile and execute the above program, it produces the following result −
Example
Try following example to understand all the miscellaneous operators available in C −
#include <stdio.h>
main() {
int a = 4;
short b;
double c;
int* ptr;
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides
how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has a higher precedence than the
addition operator.
Example
Try the following example to understand operator precedence in C −
#include <stdio.h>
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
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
Value of a + (b * c) / d is : 50
Expressions
In programming, an expression is any legal combination of symbols that represents a
value.
C Programming Provides its own rules of Expression, whether it is legal expression
or illegal expression. For example, in the C language x+5 is a legal expression.
Every expression consists of at least one operand and can have one or more
operators.
Operands are values and Operators are symbols that represent particular actions.
Expressions Validity
Types of Expression :
In Programming, different verities of expressions are given to the compiler.
Expressions can be classified on the basis of Position of Operators in an expression –
Examples of Expression :
Now we will be looking into some of the C Programming Expressions, Expression
can be created by combining the operators and operands
Each of the expression results into the some resultant output value. Consider few
expressions in below table
Expression Examples,Explanation
n1 + n2,This is an expression which is going to add two numbers and we can assign
the result of addition to another variable.
x = y,This is an expression which assigns the value of right hand side operand to left
side variable
v = u + a * t,We are multiplying two numbers and result is added to ‘u’ and total
result is assigned to v
x <= y,This expression will return Boolean value because comparison operator will
give us output either true or false ++j,This is expression having pre increment
operator\, it is used to increment the value of j before using it in expression [/table]
#include<stdio.h>
int main(){
int num;
num = 5;return(0);}
Below are some of the tips which are useful to make your concept about L-Value of
Expression more clear.
Lvalue cannot be a Constant
You cannot assign the value or any constant value to another constant value because
meaning of constant is already defined and it cannot be modified.
Lvalue cannot be a Constant Variable
Even we cannot assign a value to a constant variable. Constant variable should not be
used as L Value.
We know that macros gets expanded before processing source code by compiler. All
the macros will be replaced by defined value using pre-processor before compiling
program.
pre-processor will replace all the occurances of macros and hand over modified
source code to compiler. following code will be given to compiler after doing pre-
processor task
#define MAX 20
int main(){20 = 20;return(0);}
Causes of Error :
Solution :
Solution to this problem is very simple –
Variable Constant
Function Macro
#include<stdio.h>
int main(){int num;
num = 5;
return(0);}
In the above example, Constant Value 5 is assigned to the variable will be considered
as right Value of the variable.
Tips : R-Value of Expression
Tip 1 : R value may be constant or constant expression
If we have defined a MACRO then we can use MACRO as right value. In the above
example we have assigned the 20 to the variable “num”.
In case if we defined the MACRO value of different data type then it may results into
compile error.
Tip 3 : R Value may be variable
Input/Output Statements
There are some library functions which are available for transferring the information
between the computer and the standard input and output devices.
These functions are related to the symbolic constants and are available in the header
file.
i) printf
This function is used for displaying the output on the screen i.e the data is moved
from the computer memory to the output device.
Syntax:
printf(“format string”, arg1, arg2, …..);
In the above syntax, 'format string' will contain the information that is formatted.
They are the general characters which will be displayed as they are .
arg1, arg2 are the output data items.
Syntax:
scanf (“format string”, &arg1, &arg2, …..);
Example: Demonstrating scanf
int avg;
float per;
char grade;
scanf(“%d %f %c”,&avg, &per, &grade):
Syntax:
int getch(void);
ch=getch();
where,
ch - assigned the character that is returned by getch.
iv) putch
this function is a counterpart of getch. Which means that it will display a single
character on the screen. The character that is displayed is returned.
Syntax:
int putch(int);
putch(ch);
where,
ch - the character that is to be printed.
v) getche
This function is used to input a single character. The main difference between getch
and getche is that getche displays the (echoes) the character that we type on the
screen.
Syntax:
int getch(void);
ch=getche();
vi) getchar
This function is used to input a single character. The enter key is pressed which is
followed by the character that is typed. The character that is entered is echoed.
Syntax:
ch=getchar;
vii) putchar
This function is the other side of getchar. A single character is displayed on the
screen.
Syntax:
putchar(ch);
Example:
#include <stdio.h>
void main()
{
char line[30];
gets (line);
puts (line);
}
Assignment Statements
The assignment statement has the following form:
variable = expression
Its purpose is saving the result of the expression to the right of the assignment
operator to the variable on the left. Here are some rules:
The expression is evaluated first with the rules discussed in the single mode or the
mixed mode expressions pages.
If the type of the expression is identical to that of the variable, the result is saved in
the variable.
Otherwise, the result is converted to the type of the variable and saved there.
If the type of the variable is INTEGER while the type of the result is REAL, the
fractional part, including the decimal point, is removed making it an integer result.
If the type of the variable is REAL while the type of the result is INTEGER, then a
decimal point is appended to the integer making it a real number.
Once the variable receives a new value, the original one disappears and is no more
available.
CHARACTER assignment follows the rules stated in the discussion of the
PARAMETER attribute.
Examples:
The program segment below declares three INTEGER variables. The first
assignment statement saves an integer value to variable Unit. The second saves a real
number 100.99 into variable Amount. However, since Amount is an INTEGER
variable, the real value 100.99 is converted to an integer, 100, and saved into
Amount. Thus, after the second assignment completes, variable Amount holds 100.
The third assignment computes the single mode expression, yielding a result 500 =
5*100. Thus, variable Total receives 500.
INTEGER :: Total, Amount, Unit
Unit = 5
Amount = 100.99
Total = Unit * Amount
In the following, PI is a PARAMETER and is an alias of 3.1415926. The first
assignment statement puts integer value 5 into integer variable Radius. The
expression in the second assignment is first evaluated, yielding a result 78.539815,
which is then saved into REAL variable Area.
REAL, PARAMETER :: PI = 3.1415926
REAL :: Area
INTEGER :: Radius
Radius = 5
Area = (Radius ** 2) * PI
In the following, Counter is an INTEGER variable initialized to zero.
The meaning of the first assignment is computing the sum of the value in Counter
and 1, and saves it back to Counter. Since Counter's current value is zero, Counter +
1 is 1+0 = 1 and hence 1 is saved into Counter. Therefore, the new value of Counter
becomes 1 and its original value 0 disappears.
The second assignment statement computes the sum of Counter's current value and 3,
and saves the result back to Counter. Thus, the new value of Counter is 1+3=4.
INTEGER :: Counter = 0
Counter = Counter + 1
Counter = Counter + 3
The following swaps the values in A and B, with the help of C. That is, after
completing the following three assignment statements, A and B have 5 and 3,
respectively.
Initially, A and B are initialized to 3 and 5, respectively, while C is uninitialized. The
first assignment statement puts A's value into C, making A=3, B=5 and C=3.
The second assignment statements puts B's value into A. This destroys A's original
value 3. After this, A = 5, B = 5 and C = 3.
The third assignment statement puts C's value into B. This makes A=5, B=3 and
C=3. Therefore, the values in A and B are exchanged.
INTEGER :: A = 3, B = 5, C
C=A
A=B
B=C
The following is another possible solution; but, it uses one more variable.
INTEGER :: A = 3, B = 5, C, D
C=A
D=B
A=D
B=C
An Important Note:
A name declared with the PARAMETER attribute is an alias of a value and is not a
variable. Therefore, it cannot be used on the left-hand side of =, although it can be
used on the right-hand side. The following is wrong!
INTEGER, PARAMETER :: InchToCM = 2.54, factor = 123.45
INTEGER :: X = 15
InchToCM = factor * X
1 if statements
An if statement consists of a boolean expression followed by one or
more statements.
2 if...else statements
An if statement can be followed by an optional else statement,
which executes when the boolean expression is FALSE.
3 nested if statements
You can use one if or else if statement inside another if or else
ifstatement(s).
Let us go through each decision making briefly −
Single Statement Suites
If the suite of an if clause consists only of a single line, it may go on the same line as
the header statement.
Here is an example of a one-line if clause −
#!/usr/bin/python
var = 100if ( var == 100 ) : print "Value of expression is 100"print "Good bye!"