Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Module 1

This document outlines the structure of a C program, detailing its six main sections: documentation, link, definition, global declaration, main function, and sub program. It also explains variables and constants in C, including naming rules, types of constants, and the use of keywords and identifiers. Additionally, it covers data types and qualifiers, emphasizing the importance of data types in memory allocation and operations.

Uploaded by

ksreehari0001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Module 1

This document outlines the structure of a C program, detailing its six main sections: documentation, link, definition, global declaration, main function, and sub program. It also explains variables and constants in C, including naming rules, types of constants, and the use of keywords and identifiers. Additionally, it covers data types and qualifiers, emphasizing the importance of data types in memory allocation and operations.

Uploaded by

ksreehari0001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Module I

Structure of a C Program
A C program is divided into different sections. There are six main sections to a basic c
program. The six sections are,

Figure: Basic Structure Of C Program


Sample Program
The C program here will find the area of a circle using a user-defined function and a global
variable PI holding the value of pi
/* File Name: areaofcircle.c
Author: Abhijith
date: 06/05/2021
description: a program to calculate area of circle
user enters the radius
*/
#include<stdio.h> //link section
#define PI 3.14;//definition section
float area(float r);//global declaration
/****************************/
int main()//main function
{
float r;
printf(" Enter the radius:\n");
scanf("%f",&r);
printf("the area is: %f",area(r));
return 0;
}
/**************************/
float area(float r)
{
return pi * r * r;//sub program
}

Documentation Section
The documentation section is the part of the program where the programmer gives the
details associated with the program. He usually gives the name of the program, the details
of the author and other details like the time of coding and description. It gives anyone
reading the code the overview of the code.
/* File Name: areaofcircle.c
Author: Abhijith
date: 06/05/2021
description: a program to calculate area of circle
user enters the radius
*/

Link Section
This part of the code is used to declare all the header files that will be used in the program.
This leads to the compiler being told to include the header files to the source program and
link the system libraries.
#include<stdio.h>

Definition Section
In this section, we define different constants. The keyword define is used in this part.
#define PI 3.14

Global Declaration Section


This part of the code is the part where the global variables are declared. All the global
variable used are declared in this part. The user-defined functions are also declared in this
part of the code.
float area(float r);
int a=7;
Main Function Section
Every C-programs needs to have the main function. Each main function contains 2 parts. A
declaration part and an Execution part. The declaration part is the part where all the
variables are declared. The execution part begins with the curly brackets and ends with the
curly close bracket. Both the declaration and execution part are inside the curly braces.
int main()//main function
{
float r;
printf(" Enter the radius:\n");
scanf("%f",&r);
printf("the area is: %f",area(r));
return 0;
}

Sub Program Section


All the user-defined functions are defined in this section of the program.
float area(float r)
{
return pi * r * r;//sub program
}

Variables and constants in C


Variables
In programming, a variable is a container (storage area) to hold data.To indicate the storage
area, each variable should be given a unique name (identifier). Variable names are just the
symbolic representation of a memory location. For example:
int playerScore = 95;
Here, playerScore is a variable of integer type. The variable is assigned value: 95.
The value of a variable can be changed, hence the name 'variable'.
In C programming, you have to declare a variable before you can use it.

Rules for naming a variable in C


A variable name can have letters (both uppercase and lowercase letters), digits and
underscore only.
The first letter of a variable should be either a letter or an underscore. However, it is
discouraged to start variable name with an underscore. It is because variable name that
starts with an underscore can conflict with system name and may cause error.
There is no rule on how long a variable can be. However, only the first 31 characters of a
variable are checked by the compiler. So, the first 31 letters of two variables in a program
should be different.
C is a strongly typed language. What this means it that, the type of a variable cannot be
changed.
Constants/Literals
A constant is a value or an identifier whose value cannot be altered in a program. For
example: 1, 2.5, "C programming is easy", etc.
As mentioned, an identifier also can be defined as a constant.
const double PI = 3.14
Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program.
There are four basic types of constants in C. They are
●​ integer constants
●​ floating-point constants
●​ character constants
●​ string constants
Integer and floating-point constants represent numbers. They are often referred to
collectively as numeric-type constants. The following rules apply to all numeric-type
constants.
1. Commas and blank spaces cannot be included within the constant.
2. The constant can be preceded by a minus (-) sign if desired. (Actually the minus sign is
an operator that changes the sign of a positive constant, though it can be thought of as a
part of the constant itself.)
3. The value of a constant cannot exceed specified minimum and maximum bounds. For
each type of constant, these bounds will vary from one C compiler to another.

1. Integer constants
An integer constant is a numeric constant (associated with number) without any fractional
or exponential part. There are three types of integer constants in C programming:
●​ decimal constant(base 10)
●​ octal constant(base 8)
●​ hexadecimal constant(base 16)
For example:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
In C programming, octal constant starts with a 0 and hexadecimal constant starts with a
0x(0X).
Unsigned integer constants may exceed the magnitude of ordinary integer constants by
approximately a factor of 2, though they may not be negative. An unsigned integer constant
can be identified by appending the letter U (either upper- or lowercase) to the end of the
constant.
Long integer constants may exceed the magnitude of ordinary integer constants, but require
more memory within the computer. With some computers (andor some compilers), a long
integer constant will automatically be generated simply by specifying a quantity that
exceeds the normal maximum value. It is always possible, however, to create a long integer
constant by appending the letter L (either upper- or lowercase) to the end of the constant.
An unsigned long integer may be specified by appending the letters UL to the end of the
constant. The
letters may be written in either upper- or lowercase. However, the U must precede the L.
Several unsigned and long integer constants are shown below
Constant​ ​ ​ ​ Number System
50000U ​ ​ ​ ​ decimal (unsigned)
123456789L ​ ​ decimal (long)
123456789UL ​ octal (long)
077777711​ ​ ​ ​ octal (unsigned)
0X50000U ​ ​ ​ hexadecimal (unsigned)
0XFFFFFUL ​ ​ hexadecimal (unsigned long)

2. Floating-point constants
Afloating-point constant is a base- 10 number that contains either a decimal point or an
exponent (or both).
Several valid floating-point constants are shown below.
0.​ 1 .​ ​ 0.2​ ​ 827.602
50000.​​ 0.000743​ ​ ​ 12.3​ ​ ​ ​ ​ 315.0066
2E-8​ ​ ​ 0.006e-3​ ​ ​ 1.6667E+8​ ​ .12121212e12
The interpretation of a floating-point constant with an exponent is essentially the same as
scientific notation, except that the base 10 is replaced by the letter E (or e). Thus, the
number 1.2 x 10^-3 would be written as 1 .2E-3 or 1 .2e-3. This is equivalent to 0.12e-2, or
12e-4, etc.
The quantity 3 x 10^5can be represented in C by any of the following floating-point constants.
300000.​ 3e5​ 3e+5​ 3E5​ ​ ​ 3.Oe+
.3e6​ ​ 0.3E6​ 30E4​ 30. E+4​ 300e3
Similarly, the quantity 5.026 x 10^-l7 can be represented by any of the following loating-point
constants. 5.026E-17 ​ .5026e-16 ​ 50.26e-18 ​ .0005026E-13
Floating-point constants are normally represented as double-precision quantities in C.
Hence, each floating-point constant will typically occupy 2 words (8 bytes) of memory.
Some versions of C permit the specification of a “single-precision,” floating-point constant,
by appending the letter F (in either upper- or lowercase) to the end of the constant (e.g.,
3E5F). Similarly, some versions of C permit the specification of a “long” floating-point
constant, by appending the letter L (upper- or lowercase) to the end of the constant
(e.g.,0.123456789E-33L).

3. Character constants
A character constant is a constant which uses single quotation around characters.A
character constant is a single character, enclosed in apostrophes (i.e., single quotation
marks). For example: 'a', 'l', 'm', 'F', ' '( blank space)
Most computers, and virtually all personal computers, make use of the ASCII (i.e., American
Standard Code for Information Interchange) character set, in which each individual
character is numerically encoded with its own unique 7-bit combination (hence a total of 2'
= 128 different characters).
Example:
Character ASCII value
'A' ​ ​ ​ 65
'a' ​ ​ ​ 97
'0' ​ ​ ​ 48

Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has special meaning
in C programming. For example: newline(enter), tab, question mark etc. In order to use
these characters, escape sequence is used.
For example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal
way the characters are interpreted by the compiler.

Escape Sequences Character

\b Backspace

\f Form feed

\n Newline

\r Return
\t Horizontal tab

\v Vertical tab

\\ Backslash

\' Single quotation mark

\" Double quotation mark

\? Question mark

\0 Null character

4. String constants
A string constant consists of any number of consecutive characters (including none),
enclosed in (double) quotation marks.
For example:
"good"​ //string constant
""​ ​ ​ //null string constant
"​ " //string constant of white spaces
"x" //string constant having single character
"Earth is round\n" //prints string with newline
The following string constant includes three special characters that are represented by their
corresponding escape sequences.
" \ t T o continue, press the \"RETURN\" key\n"
The special characters are \t (horizontal tab), \ " (double quotation marks, which appears
twice), and \ n (newline).
The compiler automatically places a null character (\0) at the end of every string constant,
as the last character within the string (before the closing double quotation mark). This
character is not visible when the string is displayed. However, we can easily examine the
individual characters within a string, and test to see whether or not each character is a null
character Thus, the end of every string can be readily identified. This is very helpful if the
string is scanned on a character-by-character basis, as is required in many applications.
Also, in many situations this end-of-string designation eliminates the need to specify a
maximum string length.

5. Enumeration constants
Keyword enum is used to define enumeration types.
For example:
enum color {yellow, green, black, white};
Here, color is a variable and yellow, green, black and white are the enumeration constants
having value 0, 1, 2 and 3 respectively. If we do not explicitly assign values to enum names,
the compiler by default assigns values starting from 0.
Symbolic Constants
A symbolic constant is a name that substitutes for a sequence of characters. The
characters may represent a numeric constant, a character constant or a string constant.
Thus, a symbolic constant allows a name to appear in place of a numeric constant, a
character constant or a string.
When a program is compiled, each occurrence of a symbolic constant is replaced by its
corresponding character sequence.Symbolic constants are usually defined at the beginning
of a program. The symbolic constants may then appear later in the program in place of the
numeric constants, character constants, etc. that the symbolic constants represent.
A symbolic constant is defined by writing
#define name text
where name represents a symbolic name, typically written in uppercase letters, and text
represents the sequence of characters that is associated with the symbolic name. Note that
text does not end with a semicolon, since a symbolic constant definition is not a true C
statement. Moreover, if text were to end with a semicolon, this semicolon would be treated
as though it were a part of the numeric constant, character constant or string constant that
is substituted for the symbolic name.
EXAMPLE
#define P I 3.141593
Now suppose that the program contains the statement
area = PI * radius * radius;
During the compilation process, each occurrence of a symbolic constant will be replaced by
its corresponding text. Thus,the above statement will become
area = 3.141593 * radius * radius;

Keywords and Identifiers in C


C Keywords
Keywords are predefined, reserved words used in programming that have special meanings
to the compiler. Keywords are part of the syntax and they cannot be used as an identifier.
There are 32 keywords.
Keywords In C

C Identifiers
Identifier refers to name given to entities such as variables, functions, structures etc.
Identifier must be unique. They are created to give unique name to a entity to identify it
during the execution of the program. For example:
int money;
double accountBalance;
Here, money and accountBalance are identifiers.
Rules for writing an identifier
●​ A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
●​ The first letter of an identifier should be either a letter or an underscore. However, it
is discouraged to start an identifier name with an underscore.
●​ There is no rule on length of an identifier. However, the first 31 characters of
identifiers are discriminated by the compiler.
●​ Identifiers are case sensitive ie; X is different from x.
●​ Keywords should not be used as identifiers.
The following are valid identifiers
x y12 sum_1 _temperature​ names​ area​ tax_rate TABLE
The following names are not valid identifiers for the reasons stated.
2csbmec The first character must be a letter.
mec#cs2b ​ Illegal character #.
order-no​ ​ Illegal character (-).
mec cs2b Illegal character (blank space)

Example: University Question


State proper reasons to identify whether the given identifiers are valid or not.
i) 9marks
ii) Mark 2020
iii) v4vote
iv) _csdept
v) @cse
vi) AxB

Data Types and Qualifiers in C


There are four data types in C language. They are,
Types Data Types
Basic data types int, char, float, double
Enumeration data type enum
Derived data type pointer, array, structure, union
Void data type void
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.Following are
the examples of some very common primitive 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: As the name suggests, 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.
void:value less
Qualifiers are used to qualify the data type.The following are the qualifiers used with
primitive data type.
unsigned, signed(default)
short,long
const
volatile
The unsigned qualifier avoids sign bit.
short and long :All store integers, but consume different memory and have different ranges.
For eg: short int consumes 16bits, long int consumes 32bits and long long int consumes
64bits. The maximum value of short int is 32767. So of you need to store big values you
need to use long int .
The qualifier const can be applied to the declaration of any variable to specify that its value
will not be changed directly.Value of any variable can be changed either by program or
external device.
The volatile qualifier is applied to a variable when we declare it. It is used to tell the
compiler, that the value may change at any time. These are some properties of volatile.
The volatile keyword cannot remove the memory assignment
It cannot cache the variables in register.
The value cannot change in order of assignment.

Data Type Memory(bytes) Range Format Specifier


short int 2 -32,768 to 32,767 %hd
unsigned short int 2 0 to 65,535 %hu
unsigned int 4 0 to 4,294,967,295 %u
int 4 -2,147,483,648 to 2,147,483,647 %d or %i
long int 4 -2,147,483,648 to 2,147,483,647 %ld
unsigned long int 4 0 to 4,294,967,295 %lu
long long int 8 -(2^63) to (2^63)-1 %lld
unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu
signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
float 4 3.4E-38 to 3.4E+38 %f
double 8 1.7E-308 to 1.7E-30 %lf
long double 12 3.4E-4932 to 1.1E+4932 %Lf

Data type- size in byte


char -1
short int -2
int -2
long int or long -4
float -4 (6 decimal places of precision)
double -8 (15 decimal places of precision)
long double -10 (19 decimal places of precision)

Preprocessor Directives
In a C program, all lines that start with # are processed by preprocessor which is a special
program invoked by the compiler. In a very basic term, preprocessor takes a C program and
produces another C program without any #.
There are 4 main types of preprocessor directives:
●​ Macros
●​ File Inclusion
●​ Conditional Compilation
●​ Other directives
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

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.
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.

1) When we use include directive, the contents of included header file (after preprocessing)
are copied to the current file.
Angular brackets < and > instruct the preprocessor to look in the standard folder where all
header files are held. Double quotes “ and “ instruct the preprocessor to look into the
current folder and if the file is not present in current folder, then in standard folder of all
header files.
Eg:
#include <math.h>
#include "yourheaderfile.h"

2) When we use define for a constant, the preprocessor produces a C program where the
defined constant is searched and matching tokens are replaced with the given expression.
For example in the following program max is defined as 100.
#include<stdio.h>
#define max 100
int main()
{
printf("max is %d", max);
return 0;
}
Output:
max is 100

A macro can also be defined using #define.A macro is a segment of code which is replaced
by the value of macro. Macro is defined by #define directive
#include <stdio.h>
#define MULTIPLY(a, b) a*b
int main()
{
printf("%d", MULTIPLY(2, 3));
return 0;
}

Input Output - printf() and scanf() functions


printf() and scanf() functions are inbuilt library functions in C programming language which
are available in C library by default.These functions are declared and related macros are
defined in “stdio.h” which is a header file in C language.

We have to include “stdio.h” file as shown in below to make use of these printf() and scanf()
library functions in C program.
#include <stdio.h>

printf() function in C
In C programming language, printf() function is used to print the “character, string, float,
integer, octal and hexadecimal values” onto the output screen.
Here’s a quick summary of the available printf format specifiers:
%c ​ character
%d ​ decimal (integer) number (base 10)
%ld ​ Long integer
%e ​ exponential floating-point number
%f floating-point number
%lf double number
%i integer (base 10)
%o octal number (base 8)
%s a string of characters
%u unsigned decimal (integer) number
%x number in hexadecimal (base 16)
%% print a percent sign
\% ​ print a percent sign

Controlling integer width with printf


The %3d specifier is used with integers, and means a minimum width of three spaces,
which, by default, will be right-justified:
Left-justifying printf integer output To left-justify integer output with printf, just add a minus
sign (-) after the % symbol,
printf integer zero fill option To zero-fill your printf integer output, just add a zero (0) after
the % symbol,

printf integer formatting


As a summary of printf integer formatting, here’s a little collection of integer formatting
examples. Several different options are shown, including a minimum width specification,
left-justified, zero-filled, and also a plus sign for positive numbers.
Formatting floating point numbers with printf
Here are several examples showing how to format floating-point numbers with printf:

printf string formatting


Here are several examples that show how to format string output with printf:
printf special characters
The following character sequences have a special meaning when used as printf format
specifiers:

\a Audible alert
\b Backspace
\f Form feed
\r Carriage return
\? Question mark
\n New Line
\t Tab
\v Vertical tab
\\ Back slash
\0 ASCII null character
\’ Single quotes
\”” Double quotes
\o Octal Constant
\x Hexadecimal constant
scanf() function in C language:
In C programming language, scanf() function is used to read character, string, numeric data
from keyboard.
The examples show various syntax for reading different data types
int x; scanf(“%i”,&x); or scanf(“%d”,&x);
float x;scanf(“%f”,&x);
char x; scanf(“%c”,&c);
long int x; scanf(“%ld”,&x);
char str[100];scanf(“%s”,str);

C – Operators and Expressions

●​ The symbols which are used to perform logical and mathematical operations in a C
program are called C operators.
●​ These C operators join individual constants and variables to form expressions.
●​ Operators, functions, constants and variables are combined together to form
expressions.
●​ Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is
constant and A + B * 5 is an expression.

Types of C operators:
C language offers many types of operators. They are,
Types of Operators Description
Arithmetic operators These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus
Assignmentoperators These are used to assign the values for the variables in C programs.
Relational operators These operators are used to compare the value of two variables.
Logical operators These operators are used to perform logical operations on the given two
variables.
Bit wise operators These operators are used to perform bit operations on given two
variables.
Conditional (ternary) Conditional operators return one value if condition is true and returns
operators another value is condition is false.
Increment/decrement These operators are used to either increase or decrease the value of
operators the variable by one.
Special operators &, *, sizeof( ) and ternary operators.

Arithmetic Operators in C:
C Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs.
Arithmetic Operators/Operation Example
+ (Addition) A+B
– (Subtraction) A-B
* (multiplication) A*B
/ (Division) A/B
% (Modulus) A%B

Assignment operators in C:

●​ In C programs, values for the variables are assigned using assignment operators.
●​ For example, if the value “10” is to be assigned for the variable “sum”, it can be assigned
as “sum = 10;”
●​ There are 2 categories of assignment operators in C language. They are,​
1.Simple assignment operator ( Example: = )​
2. Compound assignment operators ( Example:+=, -=, *=, /=, %=, &=, ^= )

Operators Example/Description
= sum = 10;
10 is assigned to variable sum
+= sum += 10;
This is same as sum = sum + 10
-= sum -= 10;
This is same as sum = sum – 10
*= sum *= 10;
This is same as sum = sum * 10
/= sum /= 10;
This is same as sum = sum / 10
%= sum %= 10;
This is same as sum = sum % 10
&= sum&=10;
This is same as sum = sum & 10
^= sum ^= 10;
This is same as sum = sum ^ 10

Relational operators in C:
Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a C program.
Operators Example/Description
> x > y (x is greater than y)
< x < y (x is less than y)
>= x >= y (x is greater than or equal to y)
<= x <= y (x is less than or equal to y)
== x == y (x is equal to y)
!= x != y (x is not equal to y)

Logical operators in C:

●​ These operators are used to perform logical operations on the given expressions.
●​ There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||)
and logical NOT (!).

Operators Example/Description
&& (logical AND) (x>5)&&(y<5)
It returns true when both conditions are true
|| (logical OR) (x>=10)||(y>=10)
It returns true when at-least one of the condition is true
! (logical NOT) !((x>5)&&(y<5))
It reverses the state of the operand “((x>5) && (y<5))”
If “((x>5) && (y<5))” is true, logical NOT operator makes it false

Bit wise operators in C:

●​ These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.

Below are the bit-wise operators in C language.

●​ & – Bitwise AND


●​ | – Bitwise OR
●​ ~ – Bitwise NOT
●​ ^ – XOR
●​ << – Left Shift
●​ >> – Right Shift

Truth table for bit wise operations ( OR, AND, EX-OR)

Conditional or ternary operators in C:

●​ Conditional operators return one value if condition is true and returns another value is
condition is false.
●​ This operator is also called as ternary operator.

Syntax : (Condition? true_value: false_value);


Example : (A > 100 ? 0 : 1);

●​ In above example, if A is greater than 100, 0 is returned else 1 is returned.This is equal


to if else conditional statements.

Example: ( university question)


Write a program for evaluating the function Y using ternary operator.
Y=1 x >5
Y=0 x <=5
#include <stdio.h>
int main()
{
int x=6;
int Y=(x>5)?1:0;
printf("%d",Y);
}
Example : University Question
Convert the following if-else code into conditional operator
if (first_check)
{
"access denied";
}
else
{
if (second_check)
{
"access denied";
}
else
{
"access granted";
}
}

#include <stdio.h>
int main() {
int first_check = 1; // Example value (1 means true, 0 means false)
int second_check = 0; // Example value (1 means true, 0 means false)

printf("%s\n", first_check ? "access denied" : (second_check ? "access denied" : "access


granted"));

return 0;
}

Increment/decrement operators in C:

●​ Increment operators are used to increase the value of the variable by one and
decrement operators are used to decrease the value of the variable by one in C
programs.
●​ Syntax:​
Increment operator: ++var_name; (or) var_name++;​
Decrement operator: – -var_name; (or) var_name – -;
●​ Example:​
Increment operator :++ i ; i ++ ;​
Decrement operator : – – i ; i – – ;

Special Operators in C:
Below are some of the special operators that the C programming language offers.
Operators Description
& This is used to get the address of the variable.
Example : &a will give address of a.
* This is used as pointer to a variable.
Example : * a where, * is pointer to the variable a.
sizeof () This gives the size of the variable.
Example : sizeof (char) will give us 1.
Operator 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.

Precedence Operator Description Associativity

1 ++ -- Suffix/postfix increment and decrement Left-to-right

() Function call

[] Array subscripting

. Structure and union member access

-> Structure and union member access through pointer

(type){list} Compound literal(C99)

2 ++ -- Prefix increment and decrement Right-to-left

+- Unary plus and minus

!~ Logical NOT and bitwise NOT

(type) Type cast

* Indirection (dereference)

& Address-of
sizeof Size-of[note 1]

_Alignof Alignment requirement(C11)

3 */% Multiplication, division, and remainder Left-to-right

4 +- Addition and subtraction

5 << >> Bitwise left shift and right shift

6 < <= For relational operators < and ≤ respectively

> >= For relational operators > and ≥ respectively

7 == != For relational = and ≠ respectively

8 & Bitwise AND

9 ^ Bitwise XOR (exclusive or)

10 | Bitwise OR (inclusive or)

11 && Logical AND

12 || Logical OR

13 ?: Ternary conditional Right-to-Left

14 = Simple assignment

+= -= Assignment by sum and difference

*= /= %= Assignment by product, quotient, and remainder


<<= >>= Assignment by bitwise left shift and right shift

&= ^= |= Assignment by bitwise AND, XOR, and OR

15 , Comma Left-to-right

Example:
#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); // (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;
}
Output:
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

Largest among 3 numbers using ternary(conditional) operator (university question)


#include <stdio.h>
int main ()
{
​ int a,b,c,larg;
​ printf("Enter the three numbers.... !\n");
​ scanf("%d%d%d",&a,&b,&c);
​ larg=a>b?(a>c?a:c):(b>c?b:c);
​ printf("Largest=%d\n",larg);
}

Output:
Enter the three numbers.... !
235
Largest=5

Bitwise Operators in C
Bit level operators make C useful for many low level applications. Bitwise operations allow
one to read and manipulate bits in variables of certain types. The bit wise operators only
work on int and char types. The following are the bitwise operators in C
Operator Description
~ Bitwise Complement
<< Bitwise Shift Left
>> Bitwise Shift Right
& Bitwise AND
^ Bitwise EX-OR
| Bitwise OR
Bitwise operations helps to work on Boolean variable, which needs only one bit.Set
membership can be represented with Boolean variables ( 1 means element in the set 0
means not in the set) and the Bitwise-AND can be used to implement set-intersection and
Bitwise-OR to implement set union.
The bitwise AND(&) is true only if both bits are set. The bitwise OR(|) is false only when both
the bits are false. The bitwise EX-OR operation returns 1 if the input bits are different.
The following chart defines these bitwise binary operations
Variable Decimal B3 B2 B1 B0
Equivalent
x 12 1 1 0 0
y 10 1 0 1 0
x&y 8 1 0 0 0
x|y 14 1 1 1 0
x^y 6 0 1 1 0
Bitwise NOT operation is the unary operator which flips the bits. It is also known as 1’s
complement operator. This changes each 1 to 0 and 0 to 1.
Variable Decimal B3 B2 B1 B0
Equivalent
x 12 1 1 0 0
~x 3 0 0 1 1
Bitwise SHIFT operators << and >> perform left and right shifts of their left operand by the
number of bit positions given by the right operand, which must be non negative.
When we shift left , the most significant bits are lost and the vacated least significant bits
are zero. Similarly when we shift right least significant bits are lost and the most significant
bits become zero.
Eg:
int x=5 // 0000 0000 0000 0101
y=x<<2; // x is shifted left two times and the result is stored in y.
so y become 20 //0000 0000 0001 0100
z=x>>2;// x is shifted right two times and the result is stored in z
so z become 1 // 0000 0000 0000 0001

Simple Programs to Begin with


1) area of the circle given the diameter.
2)area of the circle given the circumference.
3)area of the circle given center point (x1,y1) and one point on the perimeter (x2,y2).
(Hint: input the two points and compute the distance between them as radius)
4)area of a triangle given three sides a,b,c.( assume they form a triangle)
5)area and perimeter of a right angled triangle given width(w) and height(h).
6)volume and surface area of a sphere given the radius.
7)area of an equilateral triangle given one side (s).
8) volume and surface area of the cylinder given radius(r) and height(h).
9) volume and surface area of a cube given one side ( s).
10)hypotenuse of a right-angled triangle, given the length of the other two sides.
Note: assume uniform input values( eg: cm)
11) Find A, the Final Investment Value, using the simple interest formula:
A = P(1 + rt) where P is the Principal amount of money to be invested at an Interest Rate R%
per period for t Number of Time Periods. Where r is in decimal form; r=R/100;
12)Compute the compound interest(CI)
CI=A-P
Where, A = future amount
A=P(1+r/n)^(nt)
P = principal
r = rate of interest
n = number of times interest is compounded per year
t = time (in years)

Control Statements in C
Control statements enable us to specify the flow of program control; ie, the order in which
the instructions in a program must be executed. They make it possible to make decisions,
to perform tasks repeatedly or to jump from one section of code to another.
There are four types of control statements in C:
1.Decision making statements
2.Selection statements
3.Iteration statements
4.Jump statements

1.Decision Making Statement: the if-else Statement


The if-else statement is used to carry out a logical test and then take one of two possible
actions depending on the outcome of the test (ie, whether the outcome is true or false).
Syntax:
if (condition)
{
statements
}
else
{
statements
}
If the condition specified in the if statement evaluates to true, the statements inside the
if-block are executed and then the control gets transferred to the statement immediately
after the if-block. Even if the condition is false and no else-block is present, control gets
transferred to the statement immediately after the if-block.
The else part is required only if a certain sequence of instructions needs to be executed if
the condition evaluates to false. It is important to note that the condition is always specified
in parentheses and that it is a good practice to enclose the statements in the if block or in
the else-block in braces, whether it is a single statement or a compound statement.

The following program checks whether the entered number is positive or negative.
#include<stdio.h>
int main( )
{
int a;
printf("n Enter a number:");
scanf("%d",&a);
if(a>0)
{
printf("n The number %d is positive.",a);
}
else
{
printf("The number %d is negative.",a);
}
return 0;
}

Nested if and if-else Statements


It is also possible to embed or to nest if-else statements one within the other. Nesting is
useful in situations where one of several different courses of action need to be selected.
The general format of a nested if-else statement is:
if(condition1)
{
// statement(s);
}
else if(condition2)
{
//statement(s);
}
else if (conditionN)
{
//statement(s);
}
else
{
//statement(s);
}
The above is also called the if-else ladder. During the execution of a nested if-else
statement, as soon as a condition is encountered which evaluates to true, the statements
associated with that particular if-block will be executed and the remainder of the nested
if-else statements will be bypassed. If neither of the conditions are true, either the last
else-block is executed or if the else-block is absent, the control gets transferred to the next
instruction present immediately after the else-if ladder. The following program makes use of
the nested if-else statement to find the greatest of three numbers.

#include<stdio.h>​
int main( )​
{​
int a, b,c;​
a=6,b=5, c=10;​
if(a>b)​
{​
if(a>c)​
{​
printf("Greatest is:%d " , a);​
}​
else if(c>a)​
{​
printf("Greatest is: %d", c);​
}​
}​
else if(b>c) //outermost if-else block​
{​
printf("Greatest is:%d" , b);​
}​
else​
{​
printf("Greatest is: %d" , c);​
}​
return 0;​
}

2.Selection Statement: the switch-case Statement


A switch statement is used for multiple way selections that will branch into different code
segments based on the value of a variable or expression. This expression or variable must
be of integer data type.
Syntax:
switch (expression)
{
case value1:
​ code segment1;
​ break;
case value2:
​ code segment2;
​ break;
case valueN:
​ code segmentN;
​ break;
default:
​default code segment;
}
The value of this expression is either generated during program execution or read in as user
input.The case whose value is the same as that of the expression is selected and executed.
The optional default label is used to specify the code segment to be executed when the vale
of the expression does not match with any of the case values.
The break statement is present at the end of every case. If it were not so, the execution
would continue on into the code segment of the next case without even checking the case
value.

Example: a program to print the day of the week.


#include<stdio.h>
int main( )
{
int day;
printf("\nEnter the number of the day:");
scanf("%d",&day);
switch(day)
{
case 1: printf("Sunday");
​ ​ break;
case 2:​ printf("Monday");
​ ​ break;
case 3:​ printf("Tuesday");
​ ​ break;
case 4:​ printf("Wednesday");
​ ​ break;
case 5:​ printf("Thursday");
​ ​ break;
case 6:​ printf("Friday");
​ ​ break;
case 7:​ printf("Saturday");
​ ​ break;
default:​ printf("Invalid choice");
}
return 0;
}
All programs written using the switch-case statement can also be written using the if-else
statement.However, If you need to select among a large group of values, a switch statement
will run much faster than a set of nested ifs. The switch differs from the if in that switch can
only test for equality, whereas if can evaluate any type of Boolean expression.The switch
statement must be used when one needs to make a choice from a given set of choices. The
switch case statement is generally used in menu-based applications.

3.Iteration Statement(loops)
Loops are used in programming to repeat a specific block until some end condition is met.
There are three loops in C programming:
for loop
while loop
do...while loop

for Loop
The syntax of for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// statements
}
The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression is false (0), for loop is
terminated. But if the test expression is true (nonzero), statements inside the body of for
loop is executed and the update expression is updated.
This process repeats until the test expression is false.
The for loop is commonly used when the number of iterations is known.

Example: for loop// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d",&num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum+= count;
}
printf("Sum= %d", sum);
return 0;
}

while loop
The syntax of a while loop is:
while (testExpression)
{
//codes
}
where, testExpression checks the condition is true or false before each loop.The while loop
evaluates the test expression.If the test expression is true (nonzero), codes inside the body
of while loop are executed. The test expression is evaluated again. The process goes on
until the test expression is false.When the test expression is false, the while loop is
terminated.

// Program to find factorial of a number


// For a positive integer n, factorial = 1*2*3...n
#include <stdio.h>
int main()
{
int number;
long factorial;
printf("Enter an integer: ");
scanf("%d",&number);
factorial= 1;
//loop terminates when number is less than or equal to 0
while(number > 0)
{
factorial*= number;
--number;
}
printf("Factorial=%lld", factorial);
return 0;
}

do...while loop
The do..while loop is similar to the while loop with one important difference. The body of
do...while loop is executed once, before checking the test expression. Hence, the do...while
loop is executed at least once.
Syntax: do...while loop
do
{
// codes
}
while (testExpression);
The code block (loop body) inside the braces is executed once.Then, the test expression is
evaluated. If the test expression is true, the loop body is executed again. This process goes
on until the test expression is evaluated to 0 (false). When the test expression is false
(nonzero), the do...while loop is terminated.
// Program to add numbers until user enters zero
#include <stdio.h>
int main()
{
double number, sum = 0;
//loop body is executed at least once
do
{
printf("Enter a number: ");
scanf("%lf",&number);
sum+= number;
}
while(number!= 0.0);
printf("Sum= %.2lf",sum);
return 0;
}

4.Jump statements
These statements cause the normal program control to jump to a different point. Normal jump
statements are.
break
continue
goto
It is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression.In such cases, break and continue
statements are used.

break Statement
The break statement terminates the loop (for, while and do...while loop) immediately when it
is encountered. The break statement is used with decision making statement such as
switch
Example : break statement
// Program to calculate the sum of maximum of 10 numbers
// Calculates sum until user enters positive number
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1;i <= 10; ++i)
{
printf("Entera n%d: ",i);
scanf("%lf",&number);
//If user enters negative number, loop is terminated
if(number< 0.0)
{
break;
}
sum+= number; // sum = sum + number;
}
printf("Sum= %.2lf",sum);
return 0;
}
This program calculates the sum of maximum of 10 numbers. It's because, when the user enters
negative number, the break statement is executed and loop is terminated.
In C programming, break statement is also used with switch...case statement.

continue Statement
The continue statement skips some statements inside the loop. The continue statement is
used with decision making statement such as if...else.
Example : continue statement
// Program to calculate sum of maximum of 10 numbers
// Negative numbers are skipped from calculation
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1;i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
//If user enters negative number, loop is terminated
if(number< 0.0)
{
continue;
}
sum+= number; // sum = sum + number;
}
printf("Sum= %.2lf",sum);
return 0;
}

goto
The goto statement is used to alter the normal sequence of a C program.
Syntax of goto statement
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;

The label is an identifier. When goto statement is encountered, control of the program
jumps to label: and starts executing the code.

Example: goto Statement


// Program to calculate the sum and average of maximum of 5 numbers
// If user enters negative number, the sum and average of previously entered positive
number is displayed
# include <stdio.h>
int main()
{
const int maxInput = 5;
int i;
doublenumber, average, sum=0.0;
for(i=1;i<=maxInput; ++i)
{
printf("%d.Enter a number: ", i);
scanf("%lf",&number);
//If user enters negative number, flow of program moves to label jump
if(number< 0.0)
goto label;
sum+= number; // sum = sum+number;
}
label: average=sum/(i-1);
printf("Sum= %.2f\n", sum);
printf("Average= %.2f", average);
return 0;
}
The use of goto statement may lead to code that is buggy and hard to follow.Also, goto
statement allows you to do bad stuff such as jump out of scope.If you think the use of goto
statement simplifies your program. By all means use it, otherwise avoid its use.

Sample Programs( all university questions)


1.Print factors of a number
#include <stdio.h>
main()
{
int n,i;
printf("Enter the number...\n");
scanf("%d",&n);
printf("Factors of the number\n");
for(i=1;i<=n;i++)
if(n%i==0)
printf("%d\n",i);
}
Note: an efficient way is to go up to n/2

2.Sum of the digits of a number


#include <stdio.h>
main()
{
int n,i,s=0,d;
printf("Enter the number...\n");
scanf("%d",&n);
while(n!=0)
{d=n%10;
s=s+d;
n=n/10;
}
printf("Sum of the digits of the number=%d\n",s);
}

3.Check for perfect number ( Eg: 6,28,496 etc..)


#include <stdio.h>
#include <string.h>
int main()
{
int n,i,s=0;
printf("Enter the number\n");
scanf("%d",&n);
for(i=1;i<=n/2;i++)
{
if(n%i==0)
s=s+i;
}
if(s==n)
printf("%d is a pefect number \n",n);
else
printf("%d is a not a pefect number \n",n);
}

4.Check for prime ( Eg:2,3,5,7,11 etc...)


#include <stdio.h>
#include <string.h>
int main()
{
int n,i,prime=1;
printf("Enter the number\n");
scanf("%d",&n);
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{prime=0;break;}
}
if(prime)
printf("%d is a prime number \n",n);
else
printf("%d is a not a prime number \n",n);
}

5.Fibonacci series up to 100(0 1 1 2 3 5 8 13.....)


#include <stdio.h>
#include <string.h>
int main()
{
int a=0,b=1,c;
printf("Fibonacci series up to 100\n");
printf("%4d%4d",a,b);
while(1)
{
c=a+b;
if(c>100) break;
a=b;
b=c;
printf("%4d",c);
}
}

Nesting of loops in C
We can write one loop inside another loop.A loop within another loop is called a nested
loop.
In C programming, nested loops are loops that are placed inside another loop. This allows
you to repeat a set of instructions multiple times, and inside each iteration of the outer loop,
the inner loop completes its full iteration. Nested loops are useful when you need to
perform repetitive tasks within repetitive tasks.
The following is the syntax of writing one for loop inside another for loop.There is no rule
that a loop must be nested inside its own type. In fact, there can be any type of loop nested
inside any type and to any level. Each inner (nested) loop must be completely embedded
within an outer loop, the loops cannot overlap.Here for each iteration of the outer loop, the
inner loop keep executing completely.
Nesting of for loop
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{ // statement of inside loop
}
// statement of outer loop
}

Nesting of while loop


while (condition)
{
while(condition)
​ {
​ } // inner loop
}//outer loop
we can also nest for loop inside while and also while inside for loop. The nesting can go to
any level also.

Example:
#include <stdio.h>
int main()
{
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<10;j++)
{
printf("* ");
}
printf("\n");
}
}
Output:
**********
**********
**********
**********
**********
Note: The outer loop executes 5 times.The inner loop executes 10 times and print 10 '*'
each time.

Example:
#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}
Output:n=3
1 2 3 4 5 ​ 6 7 8 9 10
2 4 6 8 10 12 14 ​ 16 18 20
3 6 9 12 15 18 21 24 27 30

Explanation of the above code


First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
The program control checks whether the condition 'i<=n' is true or not.
If the condition is true, then the program control passes to the inner loop.
The inner loop will get executed until the condition is true.
After the execution of the inner loop, the control moves back to the update of the outer loop,
i.e., i++.
After incrementing the value of the loop counter, the condition is checked again, i.e., i<=n.
If the condition is true, then the inner loop will be executed again.
This process will continue until the condition of the outer loop is true.
Example:
#include <stdio.h>
int main() {
int i, j, k;
// Outer loop controls the layers
for (i = 1; i <= 3; i++) {
// Middle loop controls the rows in each layer
for (j = 1; j <= 3; j++) {
// Inner loop controls the columns in each row
for (k = 1; k <= 3; k++) {
printf("* ");
}
// Move to the next line after each row is printed
printf("\n");
}
// Separate each layer with a newline
printf("\n");
}
return 0;
}
***
***
***

***
***
***

***
***
***

In this example, the outermost loop controls the layers, the middle loop controls the rows
within each layer, and the innermost loop controls the columns within each row. The
program prints a block of stars for each layer, with each block containing three rows and
three columns.
Remember that the indentation in the code helps to visualize the structure of the nested
loops. When working with nested loops, it's crucial to keep track of the loop indices and
their ranges to achieve the desired pattern or behavior.

Example programs
#include <stdio.h>
main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
}
o/p
*
**
***
****
*****
Here the inner for loop executes i times.when i=1 it execute 1 time and prints one *.when
i=2 it executes 2 times and it print * * . The outer loop repeats 5 times.

program to print multiplication table of numbers from 2-10


#include <stdio.h>
main()
{

int n,i;
​ for(n=2;n<=10;n++)
​ {
​ printf("Multiplication table of %d\n",n);
​ for(i=1;i<=15;i++)
​ ​ {printf("%2d * %2d = %2d\n",i,n,i*n);
​ }

​ }
}
Note: here the inner loop is used to print the multiplication table of a number upto 15 and
the outer loop will select the number from 2 -10.

Factorial of each digit of a number


#include <stdio.h>
main()
{
int i,n,f,dig;
printf("Enter the number...:);
scanf("%d",&n);
​ while(n!=0)
​ {
​ dig=n%10;
​ n=n/10;
​ f=1;
​ for(i=2;i<=dig;i++)
​ f=f*i;
​ printf("%d-fact= %d\n",dig,f);
​ }
}

Write a C Program to check if a given number is a strong number(Krishnamurti number) or


not. A strong number is a number in which the sum of the factorial of the digits is equal to
the number itself.
Eg:- 145=1!+4!+5!=1+24+120=145 ( university question)
#include <stdio.h>
main()
{

int i,n,f,dig,sum=0,t;
printf("Enter the number:");
scanf("%d",&n);
t=n;
while(n!=0)
{
dig=n%10;
n=n/10;
f=1;
for(i=2;i<=dig;i++)
f=f*i;
sum=sum+f;

}
if(t==sum)
printf("Strong number\n");
else
printf("Not a Strong number\n");
}

Write a C program to check whether the given number is Armstrong number or not. [Hint:
An Armstrong number is a number with the sum of digits raised to the power of number of
digits, returns the number. ( university question)
Example: 153 = 1^3 + 5^3+ 3^3=1+125+27=153
9474=9^4 + 4^4 + 7^4 + 4^4 = 6561 + 256 + 2401 + 256=9474
#include <stdio.h>
#include <math.h>
int main() {
int num, original, remainder, n = 0;
double result = 0.0;
printf("Enter a number: ");
scanf("%d", &num);
original = num;
// Count number of digits
int temp = num;
while (temp != 0) {
temp /= 10;
n++;
}
// Compute sum of digits raised to the power n
temp = num;
while (temp != 0) {
remainder = temp % 10;
result += pow(remainder, n);
temp /= 10;
}
// Check if it's an Armstrong number
if ((int)result == original)
printf("%d is an Armstrong number.\n", original);
else
printf("%d is not an Armstrong number.\n", original);
return 0;
}

break and continue Inside Nested Loops


When we use a break statement inside the inner loop, it terminates the inner loop but not
the outer loop.
Similarly, when we use a continue statement inside the inner loop, it skips the current
iteration of the inner loop only. The outer loop is unaffected.

The following program will find out all prime numbers less than 100
#include <stdio.h>
int main ()
{ /* local variable definition */
int i, j;
for(i = 2; i<100; i++)
{
for(j = 2; j <= (i/j); j++)
{if(i%j==0) break;} // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
return 0;
}
Note:Nested loops are widely used for matrix processing( reading, printing, matrix
arithmetic etc)

You might also like