You are on page 1of 43

OCS752- Introduction to C Programming Department of CSE 2020-2021

UNIT I INTRODUCTION
Structure of C program – Basics: Data Types – Constants –Variables - Keywords –
Operators: Precedence and Associativity - Expressions - Input/Output statements,
Assignment statements – Decision-making statements - Switch statement - Looping
statements – Pre-processor directives - Compilation process – Exercise Programs:
Check whether the required amount can be withdrawn based on the available
amount – Menu-driven program to find the area of different shapes – Find the sum of
even numbers.

1.1 Introduction to C programming language


Programming languages
 Programming languages provide an abstraction from a computer‟s instruction set
architecture
 Low-level programming languages provide little or no abstraction, e.g., machine
code and assembly language
o
Difficult to use
o
Allows to program efficiently and with a low memory footprint
 High-level programming languages isolate the execution semantics of a
computer architecture from the specification of the program
o Simplifies program development.

Programming paradigms
 Programming languages can be categorized into programming paradigms
 Programming paradigms are the result of people‟s ideas about how computer
programs should be constructed.
 Once you have understood the general concepts of programming paradigms, it
becomes easier to learn new programming languages.
 Imperative
 Procedural
 Functional
 Object-Oriented
 Concurrent Logic
 Scripting
C is a high level programming language, General Purpose and Structured
programming.
 C is developed by Dennis Ritchie at AT & T Bell Laboratories in 1972 in USA.
 C is also called as procedure Oriented Programming Language and
“Compiled language”.
 Unix was the first OS written in C
 Later Microsoft Windows, Mac OS X, and GNU/Linux were all written in C.
 Perl, PHP, Python and Ruby are all written in C.

Most of the operating systems are written in C and C++ language. These include
Windows 95, 98, 2000, XP, Vista, Windows 7, Windows 8, Apple Mac OS X, Symbian
OS and Be-OS, Google Chrome OS, RIM BlackBerry OS 4.x, Apple iPhone iPod Touch
and iPad OS etc.
C is often chosen over interpreted languages because of its speed, stability, and near-
universal availability.

St. Joseph’s College of Engineering 1


OCS752- Introduction to C Programming Department of CSE 2020-2021

FEATURE OF C LANGUAGE

1.2 Structure of C Program


Basically, a C program involves the following sections:
 Documentations (Documentation Section)
 Preprocessor Statements (Link Section)
 Global Declarations (Definition Section)
 The main() function
 Local Declarations
o Program Statements & Expressions
 User Defined Functions

Sample Code of C “Hello World” Program


/* Writes the words "Hello, World!" on the screen */
#include<stdio.h>
int main()
{
printf("Hello, World!\n");
return 0;
}
Output:
Hello, World!

St. Joseph’s College of Engineering 2


OCS752- Introduction to C Programming Department of CSE 2020-2021
The example to be discussed illustrates how a simple C program looks like and how
the program segment works. A C program may contain one or more sections which
are shown in the following table.
Various parts of the above C program.
Comments are a way of explaining what makes a program.
Comments are ignored by the compiler and used by others to
/* Comments */ understand the code.
Or
This is a comment block, which is ignored by the compiler.
Comment can be used anywhere in the program to add info
about program or code block, which will be helpful for
developers to easily.
#include<stdio.h> stdio is standard for input / output, this allows us to use
some commands which includes a file called stdio.h.
Or
This is a preprocessor command that notify the compiler to
include the header file stdio.h in the program before
compiling the source-code.
int/void main() int/void is a return value, which will be explained in a while.
The main() is the main function where program execution
main() begins. Every C program must contain only one main function.
Or
This is a main function, which is the default entry point
for every C program and the void in front of it indicates
that it does not return a value.
Two curly brackets “{…}” are used to group all statements
Braces together.
Or
Curly braces which shows how much the main() function has
its scope.
printf() It is a function in C, which prints text on the screen.
Or
This is another pre-defined function of C which is used to
be displayed text string in the screen.
return 0 At the end of the main function returns value 0.
The Documentation section usually contains the collection of comment lines giving the
name of the program, author‟s or programmer‟s name and few other details.
The second part is the link-section which gives instruction to the compiler to connect to the
various functions from the system library.
The Definition section describes all the symbolic-constants.
The global declaration section is used to define those variables that are used globally
within the entire program and is used in more than one function. This section also declares
all the user-defined functions. Then comes the main().
All C programs must have a main() which contains two parts:
 Declaration part
 Execution part

St. Joseph’s College of Engineering 3


OCS752- Introduction to C Programming Department of CSE 2020-2021
The declaration part is used to declare all variables that will be used within the
program. There needs to be at least one statement in the executable part and these
two parts are declared within the opening and closing curly braces of the main().
The execution of program begins at the opening brace „{„ and ends with the closing
brace „}‟. Also it has to be noted that all the statements of these two parts needs to be
terminated with semi-colon.
The sub-program section deals with all user defined functions that are called from
the main(). These user defined functions are declared and defined usually after the
main() function.

1.3 Data Types


Each variable in C has an associated data type. Each data type requires different
amounts of memory and has some specific operations which can be performed over
it. Let us briefly describe them one by one:
Following are the examples of some very common data types used in C:
char: The most basic data type in C. It stores a single character and requires a single
byte of memory in almost all compilers.
int: An int variable is used to store an integer.
float: It is used to store decimal numbers (numbers with floating point value) with
single precision.
double: It is used to store decimal numbers (numbers with floating point value) with
double precision.

Different data types also have different ranges upto which they can store numbers.
These ranges may vary from compiler to compiler. Below is list of ranges along with
the memory requirement and format specifiers on 32 bit gcc compiler.

We can use the sizeof() operator to check the size of a variable. See the following C
program for the usage of the various data types:
#include <stdio.h>
int main()
{
int a = 1;

St. Joseph’s College of Engineering 4


OCS752- Introduction to C Programming Department of CSE 2020-2021
char b ='G';
double c = 3.14;
printf("Hello World!\n");
//printing the variables defined above along with their sizes printf("Hello! I am a
character. My value is %c and my size is %lu byte.\n", b,sizeof(char));
//can use sizeof(b) above as well
printf("Hello! I am an integer. My value is %d and my size is %lu bytes.\n",
a,sizeof(int));
//can use sizeof(a) above as well
printf("Hello! I am a double floating point variable. My value is %lf and my size is
%lu bytes.\n",c,sizeof(double));
//can use sizeof(c) above as well
printf("Bye! See you soon. :)\n");
return 0;
}
Output:
Hello World!
Hello! I am a character. My value is G and my size is 1 byte.
Hello! I am an integer. My value is 1 and my size is 4 bytes.
Hello! I am a double floating point variable. My value is 3.140000
and my size i s 8 bytes.
Bye! See you soon. :)
1.4 Storage Class
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
a) 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.
b) The register Storage Class
The register storage class is used to define local variables that should be stored in a
register instead of RAM. This means that the variable has a maximum size equal to
the register size (usually one word) and can't have the unary '&' operator applied to
it (as it does not have a memory location).
{
register int miles;
}

St. Joseph’s College of Engineering 5


OCS752- Introduction to C Programming Department of CSE 2020-2021
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.

c) The static Storage Class


The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows
them to maintain their values between function calls.
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);
static int count = 5; /* global variable */
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
When the above code is compiled and executed, it produces the following result −
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

d) The extern Storage Class


The extern storage class is used to give a reference of a global variable that is visible
to ALL the program files. When you use 'extern', the variable cannot be initialized
however, it points the variable name at a storage location that has been previously
defined. 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.

St. Joseph’s College of Engineering 6


OCS752- Introduction to C Programming Department of CSE 2020-2021
First File: main.c
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Second File: support.c
#include <stdio.h>
extern int count;
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 -
$gcc main.c support.c
It will produce the executable program a.out. When this program is executed, it
produces the following result −
count is 5

1.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.
a) 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.
Here are some examples of integer literals −
212 /* Legal */
215u/* Legal */
0xFeeL /* Legal */
78 /* 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 */

St. Joseph’s College of Engineering 7


OCS752- Introduction to C Programming Department of CSE 2020-2021
30l/* long */
30ul/* unsigned long */
b) 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.
Here are some examples of floating-point literals −
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
c) 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).
Here, you have a list of such escape sequence codes –
\n- new line
\b- backspace
\t- horizontal tab
\”- Double quotes
\‟- Single Quotes
\\- Backslash
\v- Vertical tab
\?- Question mark
\r- Carriage return
\f- form feed
Following is the example to show a few escape sequence characters −
#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
d) 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. Examples of string literals: "hello, dear"

St. Joseph’s College of Engineering 8


OCS752- Introduction to C Programming Department of CSE 2020-2021
Defining Constants
There are two simple ways in C to define constants −
 Using #define preprocessor.
 Using const keyword.
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant −
#define identifier value
The following example explains it in detail −
#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
The const Keyword
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
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
Note that it is a good programming practice to define constants in CAPITALS.

1.6 Enumeration Constants


Enumeration (or enum) is a user defined data type in C. It is mainly used to assign
names to integral constants, the names make a program easy to read and maintain.
enum State {Working = 1, Failed = 0};
The keyword „enum‟ is used to declare new enumeration types in C and C++.

St. Joseph’s College of Engineering 9


OCS752- Introduction to C Programming Department of CSE 2020-2021
Following is an example of enum declaration.
/* The name of enumeration is "flag" and the constant are the values of the flag. By
default, the values of the constants are as follows: constant1 = 0, constant2 = 1,
constant3 = 2 and so on. */
enum flag{constant1, constant2, constant3, ....... };
Variables of type enum can also be defined. They can be defined in two ways:
// In both of the below cases, "day" is defined as the variable of type week.
enum week{Mon, Tue, Wed};
enum day;
// Or
enum week{Mon, Tue, Wed}day;
// An example program to demonstrate working of enum in C
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;

day = Wed;
printf("%d",day);
return 0;
}
Output:
2
In the above example, we declared “day” as the variable and the value of “Wed” is
allocated to day, which is 2. So as a result, 2 is printed. Another example of
enumeration is:
// Another example program to demonstrate working of enum in C
#include<stdio.h>
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}
Output:
01234567891011
In this example, the for loop will run from i = 0 to i = 11, as initially the value of i is
Jan which is 0 and the value of Dec is 11.

Interesting facts about initialization of enum.


1. Two enum names can have same value. For example, in the following C program
both „Failed‟ and „Freezed‟ have same value 0.
#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};

St. Joseph’s College of Engineering 10


OCS752- Introduction to C Programming Department of CSE 2020-2021
int main()
{
printf("%d, %d, %d", Working, Failed,
Freezed); return 0;
}
Output:
1,0,0

2. If we do not explicitly assign values to enum names, the compiler by default


assigns values starting from 0. For example, in the following C program, sunday gets
value 0, monday gets 1, and so on.
#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday,
saturday};
int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}
Output:
The day number stored in d is 4
3. We can assign values to some name in any order. All unassigned names get value
as value of previous name plus one.
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5, wednesday, thursday = 10, friday,
saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday,
thursday, friday, saturday);
return 0;
}
Output:
1 2 5 6 10 11 12
4. The value assigned to enum names must be some integeral constant,
i.e., the value must be in range from minimum possible integer value to
maximum possible integer value.
5. All enum constants must be unique in their scope. For example, the
following program fails in compilation.
enum state {working, failed};
enum result {failed, passed};
int main() { return 0; }
Output:
Compile Error: 'failed' has a previous declaration as 'state failed'.
1.7 Keywords
Keywords in C Programming Language :

St. Joseph’s College of Engineering 11


OCS752- Introduction to C Programming Department of CSE 2020-2021
1. Keywords are those words whose meaning is already defined by
Compiler
2. Cannot be used as Variable Name
3. There are 32 Keywords in C
4. C Keywords are also called as Reserved words .
32 Keywords in C Programming Language
Auto else long switch

Break enum register typedef

Case extern return union

Char float short unsigned

Const for signed void

Continue goto sizeof volatile

Default if static while

Do int struct _Packed

Double

1.8 Operator
An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following
types of operators −
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
We
a will look into the way each operator works.
a)Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable Bholds 20 then − Show Examples
Operator Description Example
+ Adds two operands. A+B= 30
− Subtracts second operand from the first. A−B=- 10
* Multiplies both operands. A*B= 200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of after an B%A=0
integer division.

St. Joseph’s College of Engineering 12


OCS752- Introduction to C Programming Department of CSE 2020-2021
++ Increment operator increases the integer A++ =11
value by one.
-- Decrement operator decreases the integer A--=9
value by one.

b)Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20.
Operator Description Example
== Checks if the values of two operands are (A == B)
equal or not. If yes, then the condition is Not
becomes true. true.
!= Checks if the values of two operands are (A != B)
equal or not. If the values are not equal, then is true.
the condition becomes true.
> Checks if the value of left operand is greater (A > B)
than the value of right operand. If yes, then is not
the condition becomes true. true.
< Checks if the value of left operand is less (A < B)
than the value of right operand. If yes, then is true.
the condition becomes true.
>= Checks if the value of left operand is greater (A >= B)
than or equal to the value of right operand. If is not
yes, then the condition becomes true. true.
<= Checks if the value of left operand is less (A <= B)
than or equal to the value of right operand. If is true.
yes, then the condition becomes true.

b) Logical Operators
Following table shows all the logical operators supported by C language.
Assume variable A holds 1 and variable B holds 0.
Operator Description Example
&& Called Logical AND operator. If both the (A &&
operands are non-zero, then the condition B) is
becomes true. false.
|| Called Logical OR Operator. If any of the two (A || B)
operands is non-zero, then the condition is true.
becomes true.
! Called Logical NOT Operator. It is used to !(A &&
reverse the logical state of its operand. If a B) is
condition is true, then Logical NOT operator true.
will make it false.

St. Joseph’s College of Engineering 13


OCS752- Introduction to C Programming Department of CSE 2020-2021
c)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
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~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,
result if it exists in both operands. i.e., 0000 1100
| Binary OR Operator copies a bit if it exists (A|B)=61,
in either operand. i.e., 0011 1101
^ Binary XOR Operator copies the bit if it is (A^B)=49,
set in one operand but not both. i.e., 0011 0001
~ 1100 0011 in 1's
Binary Ones Complement Operator is Complement form.
unary and has the effect of 'flipping' bits. i.e,. (~A ) = -61
<< Binary Left Shift Operator. The left
A << 2 =240
operands value is moved left by the
i.e.,
number of bits specified by the right
1111 0000
operand.
>> Binary Right Shift Operator. The left A>>2=15

operands value is moved right by the


i.e., 0000
number of bits specified by the right
1111
operand.

St. Joseph’s College of Engineering 14


OCS752- Introduction to C Programming Department of CSE 2020-2021
d)Assignment Operators
The following table lists the assignment operators supported by the C language −

Operator Description Example


= Simple assignment operator. Assigns C=A+B
values from right side operands to left side will
Operand assign the
value of A
+ B to C
+= Add AND assignment operator. It adds the C += A is
right operand to the left operand and equivalent
assign the result to the left operand. to C = C +
A
-= Subtract AND assignment operator. It C -= A is
subtracts the right operand from the left equivalent
operand and assigns the result to the left to C = C -
operand. A
*= Multiply AND assignment operator. It C *= A is
multiplies the right operand with the left equivalent
operand and assigns the result to the left to C = C *
operand. A
/= Divide AND assignment operator. It C /= A is
divides the left operand with the right equivalent
operand and assigns the result to the left to C = C /
operand. A
%= Modulus AND assignment operator. It C %= A is
takes modulus using two operands and equivalent
assigns the result to the left operand. to C =
%A
<<= Left shift AND assignment operator. C <<= 2 is
same as C
=C<<2
>>= Right shift AND assignment operator. C >>= 2 is
same as C
=C>>2
&= Bitwise AND assignment operator. C &= 2 is
same as C
=C&2
^= Bitwise exclusive OR and assignment C ^= 2 is
operator. same as C
=C^2
|= Bitwise inclusive OR and assignment C |= 2 is
same as C
operator. =C|2

St. Joseph’s College of Engineering 15


OCS752- Introduction to C Programming Department of CSE 2020-2021
e) Misc Operators ↦ sizeof & ternary
Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.
Operator Description Example
sizeof() sizeof(a), where a is
Returns the size of a variable. integer, will return 4.
& &a; returns the
Returns the address of a variable. actual address of
the variable.
* Pointer to a variable. *a;
?: If Condition is true
Conditional Expression. ? then value X :
otherwise value Y
1.8.1 Operators Precedence
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.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a
higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
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.
Category Operator Associativity
Postfix ()[]->.++-- Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right

Relational <<=>>= Left to right


Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
If two operators of same precedence (priority) is present in an expression,
Associativity of operators indicate the order in which they execute.

St. Joseph’s College of Engineering 16


OCS752- Introduction to C Programming Department of CSE 2020-2021
Example of associativity
1==2!=3 Here, operators == and != have same precedence. The associativity of both
== and != is left to right, i.e, the expression on the left is executed first and moves
towards the right.
Thus, the expression above is equivalent to :
((1 == 2) != 3) i.e, (1 == 2) executes first resulting into 0 (false)
then, (0 != 3) executes resulting into 1 (true)
Output
1
The table below shows all the operators in C with precedence and associativity.
Note: Precedence of operators decreases from top to bottom in the given table.
Summary of C operators with precedence and associativity
++ Increment
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion)
* Multiply
/ Divide Left to right
% Remainder
+ Binary plus(Addition)
Left to right
- Binary minus(subtraction)
<< Left shift
Left to right
>> Right shift
< Less than
<= Less than or equal
Left to right
> Greater than
>= Greater than or equal
== Equal to
Left to right
!= Not equal to
& Bitwise AND Left to right
^ Bitwise exclusive OR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional Operator Right to left
= Simple assignment Right to left

St. Joseph’s College of Engineering 17


OCS752- Introduction to C Programming Department of CSE 2020-2021

*= Assign product
/= Assign quotient
%= Assign remainder
-= Assign sum
&= Assign difference
^= Assign bitwise AND
|= Assign bitwise XOR
<<= Assign bitwise OR
>>= Assign left Shift
Assign right shift
, Separator of expressions Left to right
1.9 Expression
1. In programming, an expression is any legal combination of
symbols that represents a value.
2. 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.
3. Every expression consists of at least one operand and can
have one or more operators.
4. Operands are values and Operators are symbols that
represent particular actions. Valid C Programming Expression :
C Programming code gets compiled firstly before execution. In the different
phases of compiler, c programming expression is checked for its validity.
Expressions

Validity

Expression is valid since it contain + operator


a+b
which is binary operator

++a+b Invalid Expression

Priority and Expression :


In order to solve any expression we should have knowledge of C
Programming Operators and their priorities. 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 –
Type Explanation Example

Expression in which Operator


Infix a+b
is written between Operands

St. Joseph’s College of Engineering 18


OCS752- Introduction to C Programming Department of CSE 2020-2021

Expression in which Operator is written


Prefix +ab
before Operands

Expression in which Operator is written


Postfix ab+
after Operands

These expressions are solved using the stack.


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
Expression Examples, 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

1.10 Input Output Statements(I/O)


When we say Input, it means to feed some data into a program. An input can be
given in the form of a file or from the command line. C programming provides a set
of built-in functions to read the given input and feed it to the program as per
requirement.
When we say Output, it means to display some data on screen, printer, or in any file.
C programming provides a set of built-in functions to output the data on the
computer screen as well as to save it in text or binary files. The Standard Files C
programming treats all the devices as files. So devices such as the display are
addressed in the same way as files and the following three files are automatically
opened when a program executes to provide access to the keyboard and screen.
Standard File File Pointer Device
Standard input stdin Keyboard

Standard output stdout Screen

Standard error stderr Your screen

The file pointers are the means to access the file for reading and writing
purpose. This section explains how to read values from the screen and how
to print the result on the screen.

St. Joseph’s College of Engineering 19


OCS752- Introduction to C Programming Department of CSE 2020-2021
The getchar() and putchar() Functions
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 character 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;

printf( "Enter a value :");


c = getchar( );

printf( "\nYou entered: ");


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 the program proceeds and reads only a
single character and displays it as follows −
$./a.out
Enter a value : this is test
You entered: t
The gets() and puts() Functions
The char *gets(char *s) function reads a line from stdin into the buffer pointed to
by s until either a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline
to stdout.
#include <stdio.h>
int main( ) {

char str[100];

printf( "Enter a value :");


gets( str );

printf( "\nYou entered: ");


puts( str );

return 0;
}

St. Joseph’s College of Engineering 20


OCS752- Introduction to C Programming Department of CSE 2020-2021

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 the program proceeds and reads the
complete line till end, and displays it as follows −
$./a.out
Enter a value : this is test
You entered: this is test
The scanf() and printf() Functions
The int scanf(const char *format, ...) function reads the input from the standard
input stream stdin and scans that input according to the format provided.
The int printf(const char *format, ...) function writes the output to the standard
output stream stdout and produces the output according to the 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, and character or float respectively.
There are many other formatting options available which can be used based on
requirements. Let us proceed with a example to understand the concepts better −
#include <stdio.h>
int main( ) {
char str[100];
int i;
printf( "Enter a value :");
scanf("%s%d", str, &i);
printf( "\nYou entered: %s, %d ", str, i);
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
Enter a value : seven 7
You entered: seven, 7
Here, it should be noted that scanf() expects input in the same format as you
provided %s and %d, which means you have to provide valid inputs like "string
integer". If you provide "string string" or "integer integer", then it will be assumed as
wrong input. Secondly, while reading a string, scanf() stops reading as soon as it
encounters a space, so "this is test" are three strings for scanf().

1.11 Assignment Statements


An assignment statement gives a value to a variable. For example,
x = 5; gives x the value 5.
The value of a variable may be changed. For example, if x has the value 5, then
the assignment statement x = x + 1; will give x the value 6.
The general syntax of an assignment statement is

variable = expression;

St. Joseph’s College of Engineering 21


OCS752- Introduction to C Programming Department of CSE 2020-2021
where:
 the variable must be declared;
 the variable may be a simple name, or an indexed location in an array, or a
field (instance variable) of an object, or a static field of a class; and
 the expression must result in a value that is compatible with the type of the
variable. In other words, it must be possible to cast the expression to the type
of the variable.
Examples:
int i = 0;
price[itemNumber] = 0.80 * price[itemNumber];
myDog.name = "Fido";
Intermediate:
An assignment "statement" is not really a statement (although it is typically used
that way), but is an expression. The value of the expression is the value that is
assigned to the variable. For example, the expression i = j = k = 0;
sets all of i, j, and k to zero.

1.12 Decision making statements


Decision making is about deciding the order of execution of statements based on
certain conditions or repeat a group of statements until certain specified conditions
are met. C language handles decision-making by supporting the following
statements, if statement, switch statement, conditional operator statement (? :
operator) and goto statement.
a)Decision making with if statement
The if statement may be implemented in different forms depending on the
complexity of conditions to be tested. The different forms are,
1. Simple if statement
2. if....else statement
3. Nested if....else statement
4. Using else if statement
i)Simple if statement
The general form of a simple if statement is,
if(expression)
{
statement inside;
statement outside;
}
If the expression returns true, then the statement-inside will be executed, otherwise
statement-inside is skipped and only the statement-outside is executed.
Example:
#include <stdio.h>
void main( )
{ int x, y;
x = 15;
y = 13;
if (x > y )
printf("x is greater than y");
}

St. Joseph’s College of Engineering 22


OCS752- Introduction to C Programming Department of CSE 2020-2021
Output:}
x is greater than y
ii) if...else statement
The general form of a simple if...else statement is,
if(expression)
{
statement block1;
}
else
{
statement block2;
}
If the expression is true, the statement-block1 is executed, else statement-block1 is
skipped and statement-block2 is executed.
Example:
#include <stdio.h>

void main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
Output:
y is greater than x

iii) Nested if....else statement


The general form of a nested if...else statement is,
if( expression )
{
if( expression1 )
{
statement block1;
}
else
{
statement block2;
}
} //first if

St. Joseph’s College of Engineering 23


OCS752- Introduction to C Programming Department of CSE 2020-2021
else
{
statement block3;
}
if expression is false then statement-block3 will be executed, otherwise the execution
continues and enters inside the first if to perform the check for the next if block,
where if expression 1 is true the statement-block1 is executed otherwise statement-
block2 is executed.
Example:
#include <stdio.h>

void main( )
{
int a, b, c;
printf("Enter 3 numbers...");
scanf("%d%d%d",&a, &
if(a > b)
{
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}

iv) else if ladder


The general form of else-if ladder is,
if(expression1)
{
statement block1;
}
else if(expression2)
{

St. Joseph’s College of Engineering 24


OCS752- Introduction to C Programming Department of CSE 2020-2021
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as a true
condition is found, the statement associated with it is executed.
Example :
#include <stdio.h>
void main( )
{
int a;
printf("Enter a number...");
scanf("%d", &a);
if(a%5 == 0 && a%8 == 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{
printf("Divisible by 8");
}
else if(a%5 == 0)
{
printf("Divisible by 5");
}
else
{
printf("Divisible by none");
}
}

Points to Remember
1. In if statement, a single statement can be included without enclosing it into curly
braces { ... }
int a = 5;
if(a > 4)
printf("success");
No curly braces are required in the above case, but if we have more than one
statement inside if condition, then we must enclose them inside curly braces.
2. == must be used for comparison in the expression of if condition, if you use = the
expression will always return true, because it performs assignment not
comparison.
3. Other than 0(zero), all other values are considered as true.

St. Joseph’s College of Engineering 25


OCS752- Introduction to C Programming Department of CSE 2020-2021

if(27)
printf("hello");
In above example, hello will be printed.

1.13 Switch Statement


Switch case statements are a substitute for long if statements that compare a variable
to several integral values
 The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
 Switch is a control statement that allows a value to change control of execution.
Syntax:
switch (n)
{
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
default: // code to be executed if n doesn't match any cases
}

Important Points about Switch Case Statements:


1. The expression provided in the switch should result in a constant value
otherwise it would not be valid.
Valid expressions for switch:
Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)

St. Joseph’s College of Engineering 26


OCS752- Introduction to C Programming Department of CSE 2020-2021
Invalid switch expressions for switch:
Variable expression not allowed
switch(ab+cd)
switch(a+b+c)
2. Duplicate case values are not allowed.
3. The default statement is optional.Even if the switch case statement do not have a
default statement, it would run without any problem.
4. The break statement is used inside the switch to terminate a statement sequence.
When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
5. The break statement is optional. If omitted, execution will continue on into the
next case. The flow of control will fall through to subsequent cases until a break is
reached.
6. Nesting of switch statements are allowed, which means you can have switch
statements inside another switch. However nested switch statements should be
avoided as it makes program more complex and less readable.

Example:
// Following is a simple program to demonstrate
// syntax of switch.
#include <stdio.h>
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
case 3: printf("Choice is 3");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}
Output:
Choice is 2
1.14 Looping statements
Looping statements are the statements execute one or more statement repeatedly
several number of times. In C programming language there are three types of loops;
while, for and do-while.

Why use loop?


When you need to execute a block of code several number of times then you need to
use looping concept in C language.

St. Joseph’s College of Engineering 27


OCS752- Introduction to C Programming Department of CSE 2020-2021
Advantage with looping statement
 Reduce length of Code
 Take less memory space.
 Burden on the developer is reducing.
 Time consuming process to execute the program is reduced.

Types of Loops.
There are three type of Loops available in 'C' programming language.
 while loop
 for loop
 do..while
Difference between conditional and looping statement:
Conditional statement executes only once in the program where as looping
statements executes repeatedly several number of time.
a)While loop
In while loop First check the condition if condition is true then control goes inside
the loop body otherwise goes outside the body. while loop will be repeats in clock
wise direction.

St. Joseph’s College of Engineering 28


OCS752- Introduction to C Programming Department of CSE 2020-2021
Syntax
Assignment;
while(condition)
{ Statements;
...... Increment/decrements (++ or --);
}
Note: If while loop condition never false then loop become infinite loop.
Example of while loop
#include<stdio.h>
#include<conio.h>
void main()
{ int i;
clrscr();
i=1;
while(i<5)
{ printf("\n%d",i);
i++;
}
getch();
}
Output
1
2
3
4

b) For loop
for loop is a statement which allows code to be repeatedly executed. For loop
contains 3 parts Initialization, Condition and Increment or Decrements.

St. Joseph’s College of Engineering 29


OCS752- Introduction to C Programming Department of CSE 2020-2021
Example of for loop
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<5;i++)
{
printf("\n%d",i);
}
getch();
}

Output
1
2
3
4

c)do-while
A do-while loop is similar to a while loop, except that a do-while loop is execute at
least one time. A do while loop is a control flow statement that executes a block of
code at least once, and then repeatedly executes the block, or not, depending on a
given condition at the end of the block (in while).

Syntax
do
{
Statements;
........
Increment/decrement (++ or --)
} while();
When use do..while Loop
When we need to repeat the statement block at least 1 time then we use do-while
loop.

St. Joseph’s College of Engineering 30


OCS752- Introduction to C Programming Department of CSE 2020-2021

Example of do..while loop


#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
i=1;
do
{
printf("\n%d",i);
i++;
}
while(i<5);
getch();
}
Output
1
2
3
4
Nested loop
In Nested loop one loop is place within another loop body. When we need to
repeated loop body itself n number of times use nested loops.
Nested loops can be designed up to 255 blocks.

1.15 Pre-processor directives


The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution tool
and it instructs the compiler to do required pre-processing before the actual
compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first
nonblank character, and for readability, a preprocessor directive should begin in the
first column. The following section lists down all the important preprocessor
directives −
Sr.No. Directive & Description
1 #define
Substitutes a preprocessor macro.
2 #include
Inserts a particular header from another file.
3 #undef
Undefines a preprocessor macro.
4 #ifdef
Returns true if this macro is defined.

St. Joseph’s College of Engineering 31


OCS752- Introduction to C Programming Department of CSE 2020-2021
5 #ifndef
Returns true if this macro is not defined.
6 #if
Tests if a compile time condition is true.
7 #else
The alternative for #if.
8 #elif
#else and #if in one statement.
9 #endif
Ends preprocessor conditional.
10 #error
Prints error message on stderr.
11 #pragma
Issues special commands to the compiler, using a standardized method.

Preprocessors Examples
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20.
Use #define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to
the current source file. The next line tells CPP to get myheader.h from the local
directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
It tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful
if you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This
will define DEBUG, so you can turn debugging on and off on the fly during
compilation.

Predefined Macros
ANSI C defines a number of macros. Although each one is available for use in
programming, the predefined macros should not be directly modified.

St. Joseph’s College of Engineering 32


OCS752- Introduction to C Programming Department of CSE 2020-2021
Sr.No. Macro & Description
1 __DATE__
The current date as a character literal in "MMM DD YYYY" format.
2 __TIME__
The current time as a character literal in "HH:MM:SS" format.
3 __FILE__
This contains the current filename as a string literal.
4 __LINE__
This contains the current line number as a decimal constant.
5 __STDC__
Defined as 1 when the compiler complies with the ANSI standard.
Let's try the following example −
#include <stdio.h>
main() {
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("ANSI :%d\n", __STDC__ );
}
When the above code in a file test.c is compiled and executed, it produces the
following result −
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1
Preprocessor Operators
The C preprocessor offers the following operators to help create macros − The Macro
Continuation (\) Operator. A macro is normally confined to a single line. The macro
continuation operator (\) is used to continue a macro that is too long for a single line.
For example −
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
a)The Stringize (#) Operator
The stringize or number-sign operator ('#' ), when used within a macro
definition, converts a macro parameter into a string constant. This operator
may be used only in a macro having a specified argument or parameter list.
For example −
#include <stdio.h>
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
int main(void) {
message_for(Carole, Debra);
return 0; }

St. Joseph’s College of Engineering 33


OCS752- Introduction to C Programming Department of CSE 2020-2021
When the above code is compiled and executed, it produces the following result −
Carole and Debra: We love you!

b)The Token Pasting (##) Operator


The token-pasting operator (##) within a macro definition combines two arguments.
It permits two separate tokens in the macro definition to be joined into a single token.
For example −
#include <stdio.h>
#define tokenpaster(n) printf ("token" #n " = %d", token##n)
int main(void) {
int token34 = 40;
tokenpaster(34);
return 0;
}
When the above code is compiled and executed, it produces the following result −
token34 = 40. It happened so because this example results in the following actual
output from the preprocessor −
printf ("token34 = %d", token34);
This example shows the concatenation of token##n into token34 and here we have
used both stringize and token-pasting.

c)The Defined() Operator


The preprocessor defined operator is used in constant expressions to determine if an
identifier is defined using #define. If the specified identifier is defined, the value is
true (non-zero). If the symbol is not defined, the value is false (zero). The defined
operator is specified as follows −
#include <stdio.h>
#if !defined (MESSAGE)
#define MESSAGE "You wish!"
#endif
int main(void) {
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Here is the message: You wish!
Parameterized Macros
One of the powerful functions of the CPP is the ability to simulate functions using
parameterized macros. For example, we might have some code to square a number
as follows −
int square(int x)
{
return x * x;
}

St. Joseph’s College of Engineering 34


OCS752- Introduction to C Programming Department of CSE 2020-2021
We can rewrite above the code using a macro as follows −
#define square(x) ((x) * (x))
Macros with arguments must be defined using the #definedirective before they can
be used. The argument list is enclosed in parentheses and must immediately follow
the macro name. Spaces are not allowed between the macro name and open
parenthesis. For example −
#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int main(void) {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Max between 20 and 10 is 20

1.16 Compilation process


C is a high level language and it needs a compiler to convert it into an executable
code so that the program can be run on our machine.
How do we compile and run a C program?
Below are the steps we use on an Ubuntu machine with gcc compiler.

We first create a C program using an editor and save the file as filename.c
$ vi filename.c
The diagram on right shows a simple program to add two numbers.

Then compile it using below command.


$ gcc –Wall filename.c –o filename
The option- Wall enables all compiler‟s warning messages. This option is
recommended to generate better code. The option -o is used to specify output file
name. If we do not use this option, then an output file with name a.out is generated.

St. Joseph’s College of Engineering 35


OCS752- Introduction to C Programming Department of CSE 2020-2021

After compilation executable is generated and we run the generated executable using
below command.
$ ./filename

What goes inside the compilation process?


Compiler converts a C program into an executable. There are four phases for a C
program to become an executable:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
By executing below command, We get the all intermediate files in the current
directory along with the executable.
$gcc –Wall –save-temps filename.c –o filename
The following screenshot shows all generated intermediate files.

Let us one by one see what these intermediate files contain.


Pre-processing
This is the first phase through which source code is passed. This phase include:
 Removal of Comments
 Expansion of Macros
 Expansion of the included files.
The preprocessed output is stored in the filename.i. Let‟s see what‟s inside filename.i:
using $vi filename.i
In the above output, source file is filled with lots and lots of info, but at the end our
Code is preserved.
Analysis:
 printf contains now a + b rather than add(a, b) that‟s because macros have
expanded.
 Comments are stripped off.

St. Joseph’s College of Engineering 36


OCS752- Introduction to C Programming Department of CSE 2020-2021
 #include<stdio.h> is missing instead we see lots of code. So header files has
been expanded and included in our source file.

Compiling
The next step is to compile filename.i and produce an; intermediate compiled output
file filename.s. This file is in assembly level instructions. Let‟s see through this file
using $vi filename.s.

The snapshot shows that it is in assembly language, which assembler can


understand.
Assembly: In this phase the filename.s is taken as input and turned into filename.o
by assembler. This file contain machine level instructions. At this phase, only
existing code is converted into machine language, the function calls like printf() are
not resolved. Let‟s view this file using $vi filename.o

St. Joseph’s College of Engineering 37


OCS752- Introduction to C Programming Department of CSE 2020-2021

Linking
This is the final phase in which all the linking of function calls with their definitions
are done. Linker knows where all these functions are implemented. Linker does some
extra work also, it adds some extra code to our program which is required when the
program starts and ends. For example, there is a code which is required for setting up
the environment like passing command line arguments. This task can be easily
verified by using $size filename.o and $size filename. Through these commands, we
know that how output file increases from an object file to an executable file. This is
because of the extra code that linker adds with our program.

Note that GCC by default does dynamic linking, so printf() is dynamically linked in
above program. Refer this, this and this for more details on static and dynamic
linkings.
C PROGRAMS

1) Check whether the required amount can be withdrawn based on the


available amount.
# include < stdio.h >
# include < conio.h >
void creation( ) ;

St. Joseph’s College of Engineering 38


OCS752- Introduction to C Programming Department of CSE 2020-2021
void deposit( ) ;
void withdraw( ) ;
void lowbal( ) ;
int a = 0 , i = 1001 ;
struct bank
{
int no ;
char name[20] ;
float bal ;
float dep ;
} s[100];

int main( )
{
int ch ;
do
{
printf(" \n**************************** ") ;
printf(" \nBANKING ") ;
printf(" \n**************************** ") ;
printf(" \n1. Create New Account ") ;
printf(" \n2. Cash Deposit ") ;
printf(" \n3. Cash Withdraw ") ;
printf(" \n4. Low Balance Enquiry ") ;
printf(" \n5. Exit ") ;
printf(" \nEnter your choice : ") ;
scanf("%d ",& ch) ;
switch ( ch)
{
case 1 : creation( ) ;
break ;
case 2 : deposit( ) ;
break ;
case 3 : withdraw( ) ;
break ;
case 4 : lowbal( ) ;
break ;
case 5 : ;
break ;
default : printf(" Choice a Valid option !! ") ;
break ;
getch( ) ;
}
} while( ch != 5 ) ;
}

St. Joseph’s College of Engineering 39


OCS752- Introduction to C Programming Department of CSE 2020-2021
void creation( )
{
printf(" \n**************************** ") ;
printf(" \nNEW ACCOUNT CREATION ") ;
printf(" \n**************************** ") ;
printf(" \nYour Account Number is :%d ",i) ;
s[a].no = i ;
printf(" \nEnter your Name : ") ;
scanf("%s ",& s[a].name) ;
printf(" \nYour Deposit is Minimum Rs.500") ;
s[a].dep=500 ;
a++ ;
i++ ;
getch( ) ;
}

void deposit( )
{
int no, b = 0, m = 0 ;
int aa ;
printf(" \n**************************** ") ;
printf(" \nCASH DEPOSIT ") ;
printf(" \n**************************** ") ;
printf(" \nEnter your Account Number : ") ;
scanf("%d ",& no) ;
for ( b = 0 ; b < i ; b++)
{
if ( s[b].no == no)
m=b;
}
if ( s[m].no == no)
{
printf("\n Account Number : %d ",s[m].no) ;
printf("\n Name : %s ",s[m].name) ;
printf("\n Deposit : %f ",s[m].dep) ;
printf(" \nDeposited Amount : ") ;
scanf("%f ",& &aa) ;
s[m].dep+=aa ;
printf("\nThe Balance in Account is : %f ",s[m].dep) ;
getch( ) ;
}
else
{
printf("\nACCOUNT NUMBER IS INVALID ") ;
getch( ) ;
}
}

St. Joseph’s College of Engineering 40


OCS752- Introduction to C Programming Department of CSE 2020-2021
void withdraw( )
{
int no, b = 0, m = 0 ;
int aa ;
printf(" \n**************************** ") ;
printf(" \nCASH WITHDRAW ") ;
printf(" \n**************************** ") ;
printf(" \nEnter your Account Number : ") ;
scanf("%d ",& no) ;
for ( b = 0 ; b < i ; b++)
{
if ( s[b].no == no)
m=b;
}
if ( s[m].no == no)
{
printf("\n Account Number : %d ",s[m].no) ;
printf("\n Name : %s ",s[m].name) ;
printf("\n Deposit : %f ",s[m].dep) ;
printf(" \nWithdraw Amount : ") ;
scanf("%f ",& aa) ;
if ( s[m].dep < aa+500)
{
printf("\nCANNOT WITHDRAW YOUR ACCOUNT HAS MINIMUM
BALANCE ") ;
getch( ) ;
}
else
{
s[m].dep-=aa ;
printf("\nThe Balance Amount in Account is : %f ",s[m].dep) ;
}
}
else
{
printf("\nACCOUNT NUMBER IS INVALID ") ;
getch( ) ;
}
getch( ) ;
} // withdraw( ) function

void lowbal( )
{
int no, b = 0, m = 0 ;
int aa ;
printf(" \n**************************** ") ;
printf(" \nFOLLOWING ACCOUNT HOLDER'S BALANCE IS LESS THAN 1000 ") ;
printf(" \n**************************** ") ;

St. Joseph’s College of Engineering 41


OCS752- Introduction to C Programming Department of CSE 2020-2021
for ( b = 0 ; b < a ; b++)
{
if ( s[b].dep < 1000))
{
printf("\n\n Account Number : %d ",s[b].no) ;
printf("\n Name : %s ",s[b].name) ;
}
}
getch( ) ;
} // lowbal( ) function

Output of Program:

2) Menu-driven program to find the area of different shapes:


#include <stdio.h>
void main ()
{ int choice,r,l,w,b,h;
float area;
printf("Input 1 for area of circle\n");
printf("Input 2 for area of rectangle\n");
printf("Input 3 for area of triangle\n");
printf("Input your choice : ");

St. Joseph’s College of Engineering 42


OCS752- Introduction to C Programming Department of CSE 2020-2021
scanf("%d",&choice);
switch(choice)
{ case 1:
printf("Input radius of the circle : ");
scanf("%d",&r);
area=3.14*r*r;
break;
case 2:
printf("Input length and width of the rectangle : ");
scanf("%d%d",&l,&w);
area=l*w;
break;
case 3:
printf("Input the base and height of the triangle :");
scanf("%d%d",&b,&h);
area=.5*b*h;
break;
}
printf("The area is : %f\n",area);
}
Sample Output:
Input 1 for area of circle
Input 2 for area of rectangle
Input 3 for area of triangle
Input your choice : 1
Input radius of the circle : 5
The area is : 78.500000

3) Find the sum of even numbers:


#include<stdio.h>
#include<conio.h>
void main()
{ int i,n,sum;
sum=0;
clrscr();
printf("Enter the Number : ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{ if(i%2==0)
sum=sum+i;
}
printf("Sum of all Even Integers is %d",sum);
getch();
}

OUTPUT:
Enter the Number : 10
Sum of all Even Integers is 30

St. Joseph’s College of Engineering 43

You might also like