CDS Unit - 1
CDS Unit - 1
What is a Computer?
Definition : Computer is an advanced electronic device that takes raw data as an input from
the user and processes it under the control of a set of instructions (called program), produces
a result (output), and saves it for future use
Functionalities of a Computer:
If we look at it in a very broad sense, any digital computer carries out the following five
functions −
Step 1 − Takes data as input.
Step 2 − Stores the data/instructions in its memory and uses them as required.
Step 3 − Processes the data and converts it into useful information.
Step 4 − Generates the output.
Step 5 − Controls all the above four steps.
Block Diagram of a computer:
Input Unit:
This unit contains devices with the help of which we enter data into the computer. This unit
creates a link between the user and the computer. The input devices translate the information
into a form understandable by the computer.
Data entered into computer is sent to RAM, from where it is then sent to ALU, where rest of
data processing takes place. All types of processing, such as comparisons, decision-making
and processing of non-numeric information takes place here and once again data is moved to
RAM.
Control Unit:
As name indicates, this part of CPU extracts instructions, performs execution, maintains and
directs operations of entire system.
Functions of Control Unit
Control unit performs following functions −
It controls all activities of computer
Supervises flow of data within CPU
Directs flow of data within CPU
Transfers data to Arithmetic and Logic Unit
Transfers results to memory
Fetches results from memory to output devices
Memory Unit:
This is unit in which data and instructions given to computer as well as results given by
computer are stored. Unit of memory is "Byte".
1 Byte = 8 Bits
Output Unit:
The output unit consists of devices with the help of which we get the information from the
computer. This unit is a link between the computer and the users. Output devices translate
the computer's output into a form understandable by the users.
Structure of C Program
The structure of a C program can be mainly divided into six parts, each having its purpose.
It makes the program easy to read, easy to modify, easy to document, and makes it
consistent in format.
Sect Description
ion
Consists of the description of the program, programmer's
Doc name, and creation date. These are generally written in
ume the form of comments.
ntati
on
All header files are included in this section which
Lin contains different functions from the libraries. A copy of
k these header files is inserted into your code before
compilation.
Includes preprocessor directive, which contains
Defi symbolic constants. E.g.: #define allows us to use
nitio constants in our code.
n It replaces all the constants with its value in the code.
Glo Includes declaration of global variables, function
bal declarations, static global variables, and functions.
Dec
larat
ion
Mai For every C program, the execution starts from the
n() main() function. It is mandatory to include a main()
Fun function in every C program.
ctio
n
Includes all user-defined functions (functions the user
Sub provides). They can contain the inbuilt functions and the
prog function definitions declared in the Global Declaration
ram section. These are called in the main() function.
s
Code:
/** //Documentation
file: age.c
author: you
description: program to find our age.
*/
#define BORN //
2000 Definition
Output
Age: 24 Let's
Different sections of the above code Documentation
In a C program, single-line comments can be written using two forward slashes i.e., //, and
we can create multi- line comments using /* */. Here, we've used multi-line comments.
/**
* file: age.c
* author: you
* description: program to find our age.
*/
Link
A preprocessor directive in C is any statement that begins with the "#" symbol. The #define
is a preprocessor compiler directive used to create constants. In simple terms, #define
basically allows the macro definition, which allows the use of constants in our code.
We've created a constant BORN which is assigned a value of 2000. Generally, uppercase
letters are preferred for defining the constants. The above constant BORN will be replaced
by 2000 throughout our code wherever used.
#define is typically used to make a source program easy to modify and compile in different
execution environments.
The define statement does not ends with a semicolon.
Global Declaration
This section includes all global variables, function declarations, and static variables. The
variables declared in this section can be used anywhere in the program. They're accessible to
all the functions of the program. Hence, they are called global variables.
int age(int current); We've declared our age function, which takes one integer argument and
returns an integer.
Main() Function
In the structure of a C program, this section contains the main function of the code. The
compiler starts execution from the main() function. It can use global variables, static
variables, inbuilt functions, and user-defined functions. The return type of the main()
int main(void)
{
int current = 2022;
printf("Age: %d",
age(current)); return
0;
}
function can be void and also not necessarily int.
Here, we've declared a variable named current and assigned the value as 2022. Then we've
called the printf() function, with calls the age() function, which takes only one parameter.
Subprograms
This includes the user-defined functions called in the main() function. User-defined
functions are generally written after the main() function irrespective of their order.
When the user-defined function is called from the main() function, the control of the
program shifts to the called function, and when it encounters a return statement, it returns to
the main() function. In this case, we've defined the age() function, which takes one
parameter, i.e., the current year.
int age(int
current)
{ return
current -
This function is called in the main function. It returns an integer to the main function.
Conclusion
To conclude, the structure of a C program can be divided into six sections, namely -
Documentation, Link, Definition, Global Declaration, Main() Function, and Subprograms.
The main() function is compulsory to include in every C program, whereas the rest
are optional.
A well-structured C program makes debugging easier and increases the readability
and modularity of the code.
Character Set: In Real world to communicate with people we use language like Hindi
English Urdu extra which is constructed and Defined by some characters, words extra.
Similarly in C programming language we have various characters to communicate with the
computer in order to produce a meaningful program and can produce an output.
Character Set in C Language
Type Set
Lowercase a-z
Uppercase A-Z
Digits 0-9
special !,@,#,$,%
characters
White space space, tab, and new lines
Keywords:
1) they are those elements of C language whose meaning has already being defined
or explained.
2) keyword are called pre-defined words.
32 keywords in C language
A D G s u B
u o o i n r
t t g s e
o o n i a
e g k
d n
e
d
V E C s D
o l I a t o
i s n s a u
d e t e t b
i l
c e
S E L s c I
i n o t h f
z u n r a
e m g u r
o c
f t
W C e r c V
h o x e o o
i n t g n l
l s e i t a
e t r s i t
n t n i
e u l
r e e
d t F s R
e F y l h e
f o p o o t
u r e a r u
a o t t r
l d n
t e
f
U C
n o
i n
o s
n t
Data types: In every language we have to perform some operations means some task on
some values of variables.
Example:
Like 'Suhaan' Here suhaan is a set of alphabets all characters.
like '290' here 290 is a Numerical value.
So here Ramesh and 290 are different types and they are allotted to some variables. So in
order to recognize each variables and its type we have to specify their types and their types
are called 'data types' of that
variable.
So the real Example is:
int a=6;
here a is a variable of int datatype
6 is a value assigned to the variable ‘a’ using assignment operator Every data type in C
language has Storage Size and Value Ranges.
Constants: Symbolic name or an entity that does not change its value during the execution
of a program.
There are two major categories of a constant:
Constants are classified into two types they are:
1. Primary Constant
2. Secondary Constant
Primary Constant: This category consist basic constants of C language like integer
constant, float or real integer constant, character constant.
Secondary Constant: This category consist arrays, pointers, structure, union, enum etc.
We will discuss only primary constants :
a) Integer Constant:
const int rate= 50;
In this const is a keyword, int is a data type, rate is a value , = is a assignment operator,
50 is a value, ; is a terminate operator to terminate the statement
In this value of variable rate'' will not be changed throughout the program .
b) const float or real integer:
const float pi= 3.1415;---> this is called the declaration with complete statement .
c) Character Constant:
const char ch= 'A';
a character data type value is always assigned with ''quotes.
C – Variables
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and layout of
the variable's memory; the range of values that can be stored within that memory; and the set
of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character.
It must begin with either a letter or an underscore. Upper and lowercase letters are distinct
because C is case-sensitive
Variable Definition in C:
A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of one or more
variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, int, float, double, bool, or any user-
defined object; and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here −
int i, j, k; char c, ch; float f, salary; double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler
to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
datatype variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f. byte z = 22; // definition and
initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables are
undefined.
Variable Declaration in C:
A variable declaration provides assurance to the compiler that there exists a variable with
the given type and name so that the compiler can proceed for further compilation without
requiring the complete detail about the variable. A variable definition has its meaning at the
time of compilation only, the compiler needs actual variable definition at the time of linking
the program.
Example:
Try the following example, where variables have been declared at the top, but they have
been defined and initialized inside the main function −
#include <stdio.h>
int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces the following result − value of c
: 30
value of f : 23.333334
Datatypes in C language:
Integer Types:
The integer data type in C is used to store the whole numbers without decimal values. Octal
values, hexadecimal values, and decimal values can be stored in int data type in C. We can
determine the size of the int data type by using the sizeof operator in C. Unsigned int data
type in C is used to store the data values from zero to positive numbers but it can’t store
negative values like signed int. Unsigned int is larger in size than signed int and it uses
“%u” as a format specifier in C programming language. Below is the programming
implementation of the int data type in C.
Character Types
Character data type allows its variable to store only a single character. The storage size of
the character is 1. It is the most basic data type in C. It stores a single character and requires
a single byte of memory in almost all compilers.
Range: (-128 to 127) or (0 to 255)
Size: 1 byte
Format Specifier: %c
Floating-Point Types
In C programming float data type is used to store floating-point values. Float in C is used
to store decimal and exponential values. It is used to store decimal numbers (numbers with
floating point values) with single precision.
Range: 1.2E-38 to 3.4E+38
Size: 4 bytes
Format Specifier: %f
Double Types:
A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers with
decimal values in C. Double data type is basically a precision sort of data type that is
capable of holding 64 bits of decimal numbers or floating points. Since double has more
precision as compared to that float then it is much more obvious that it occupies twice the
memory as occupied by the floating-point type. It can easily accommodate about 16 to 17
digits after or before a decimal point.
Range: 1.7E-308 to 1.7E+308
Size: 8 bytes
Format Specifier: %lf
C Programming Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. 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
• Increment and decrement operators
• Conditional operators
• Misc Operators
Arithmetic operator:
These are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus.
Following table shows all the arithmetic operators supported by C language. Assume
variable A holds 10 and variable B holds 20 then:
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A – B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
%
Modulus Operator and remainder of after an integer division
B % A will give 0
++ Increments operator increases integer value by one A++ will give 11
-- Decrements operator decreases integer value by one A–will give 9
Relational Operators:
These operators are used to compare the value of two variables.
Following table shows all the relational operators supported by C language. Assume variable
A holds 10 and variable B holds 20, then:
Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes
true.
(A == B) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true.
Logical Operators:
These operators are used to perform logical operations on the given two variables.
Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then:
Operator Description Example
&&
Called Logical AND operator. If both the operands are nonzero, then condition becomes
true.
(A && B) is false.
||
Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes
true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition
is true then Logical NOT operator will make false.
!(A && B) is true.
Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. Bitwise operators are used
in bit level programming. These operators can operate upon int and char but not on float and
double.
Showbits( ) function can be used to display the binary representation of any integer or
character value.
Bit wise operators in C language are; & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^
(XOR), << (left shift) and >> (right shift).
The Bitwise operators supported by C language are explained in the following table.
Assume variable A holds 60 (00111100) and variable B holds 13 (00001101), then:
Operator Description Example
& - Binary AND Operator copies a bit to the result if it exists in both operands.
(A & B) will give 12, which is 0000 1100
| - Binary OR Operator copies a bit if it exists in either operand.
(A | B) will give 61, which is 0011 1101
^ - Binary XOR Operator copies the bit if it is set in one operand but not both.
(A ^ B) will give 49, which is 0011 0001
~ - Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits.
(~A ) will give -61, which is 1100 0011 in 2’s complement form.
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits
specified by the right operand.
A << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of
bits specified by the right operand.
A >> 2 will give 15 which is 0000 1111
Assignment Operators:
In C programs, values for the variables are assigned using assignment operators.
There are following assignment operators supported by C language:
Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assign value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the
int c=2,d=2;
printf(“%d\n”,c++); //this statement displays 2 then, only c incremented by 1 to 3.
Printf(“%d”,++c); //this statement increments 1 to c then, only c is displayed.
Return 0;
}
Output
2
4
Conditional Operators (? :)
Conditional operators are used in decision making in C programming, i.e, executes different
statements according to test condition whether it is either true or false.
Syntax of conditional operators;
conditional_expression?expression1:expression2
If the test condition is true (that is, if its value is non-zero), expression1 is returned and if
false expression2 is returned.
Let us understand this with the help of a few examples:
int x, y ;
scanf ( “%d”, &x ) ;
y = ( x> 5 ? 3 : 4 ) ;
This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.
The equivalent if statement will be,
if ( x > 5 )
y=3;
else
y=4;
Misc Operators:
There are few other operators supported by c language.
Operator Description Example
sizeof() It is a unary operator which is used in finding the size of data type, constant, arrays,
structure etc.
sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; will give actual address of the variable.
* Pointer to a variable. *a; will pointer to a variable.
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has 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.
DECISION STATEMENTS :
The selection statements are also known as Branching or Decision Control Statements.
Introduction to Decision Control Statements
Sometime we come across situations where we have to make a decision. E.g. If the weather
is sunny, I will go out & play, else I will be at home. Here my course of action is governed
by the kind of weather. If it’s sunny, I can go out & play, else I have to stay indoors. I
choose an option out of 2 alternate options. Likewise, we can find ourselves in situations
where we have to select among several alternatives. We have decision control statements to
implement this logic in computer programming.
Decision making structures require that the programmer specify one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be executed if
the condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
if Statement The keyword if tells the compiler that what follows is a decision control
instruction. The if statement allows us to put some decision -making into our programs. The
general form of the if statement is shown Fig 2:
Multiple statements may be grouped by putting them inside curly braces {}. For example:
if (total_purchase>=1000)
{
gift_count++;
printf("You are gifted a pen drive.\n");
}
For readability, the statements enclosed in {} are usually indented. This allows the
programmer to quickly tell which statements are to be conditionally executed. As we will
see later, mistakes in indentation can result in programs that are misleading and hard to read.
Programs:
1. //Write a program to print a message if negative no is entered.
2. #include<stdio.h>
3. int main()
4. {
5. int no;
6. printf("Enter a no : ");
scanf("%d", &no);
if(no<0)
{
printf("no entered is negative");
no = -no;
}
printf("value of no is %d \n",no);
return 0; }
Output:
Enter a no: 6
value of no is 6
Output:
Enter a no: -2
value of no is 2
2. Write a program to check whether the given no is even or odd
#include<stdio.h>
int main()
{
int n;
printf("Enter an integer\n");
scanf("%d",&n);
if ( n%2 == 0 )
printf("Even\n");
else
printf("Odd\n");
return 0;
}
Output: Enter an integer 3 Odd
Output: Enter an integer 4 Even
3. Write a program to check whether a given year is leap year or not
#include <stdio.h>
int main()
{
int year;
printf("Enter a year to check if it is a leap year\n");
scanf("%d", &year);
if ( (year%4 == 0) && (( year%100 != 0) || ( year%400 == 0 ))
printf("%d is a leap year.\n", year);
else
printf("%d is not a leap year.\n", year);
return 0;
}
Output: Enter a year to check if it is a leap year 1996 1996 is a leap year
Output: Enter a year to check if it is a leap year 2015 2015 is not a leap year
Nested if-else
An entire if-else construct can be written within either the body of the if statement or the
body of an else statement. This is called ‘nesting’ of ifs. This is shown in the following
structure.
if (n > 0)
{
if (a > b)
z = a;
}
else
z = b;
The second if construct is nested in the first if statement. If the condition in the first if
statement is true, then the condition in the second if statement is checked. If it is false, then
the else statement is executed. Program: 5. Write a program to check for the relation
between 2 nos
#include <stdio.h>
int main()
{
int m=40,n=20;
if ((m >0 ) && (n>0))
{
printf("nos are positive");
if (m>n)
{
printf("m is greater than n");
}
else
{
printf("m is less than n");
}
}
else
{
printf("nos are negative");
}
return 0;
}
Output 40 is greater than 20
else-if Statement: This sequence of if statements is the most general way of writing a
multi−way decision. The expressions are evaluated in order; if an expression is true, the
statement associated with it is executed, and this terminates the whole chain. As always, the
code for each statement is either a single statement, or a group of them in braces.
If (expression)
statement
else if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
The last else part handles the ``none of the above'' or default case where none of the other
conditions is satisfied. Sometimes there is no explicit action for the default; in that case the
trailing can be omitted, or it may be used for error checking to catch an “impossible”
condition.
Program:
7. The above program can be used as an eg here.
#include <stdio.h>
int main() {
int m=40,n=20;
if (m>n)
{
printf("m is greater than n");
}
else if(m<n)
{
printf("m is less than n");
}
else
{
printf("m is equal to n");
}
}
Output: m is greater than n
switch case: This structure helps to make a decision from the number of choices. The
switch statement is a multi−way decision that tests whether an expression matches one of a
number of constant integer values, and branches accordingly [3].
switch( integer expression)
{
case constant 1 :
do this;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}
The integer expression following the keyword switch is any C expression that will yield an
integer value. It could be an integer constant like 1, 2 or 3, or an expression that evaluates to
an integer. If a case matches the expression value, execution starts at that case. All case
expressions must be different. The case labelled default is executed if none of the other
cases are satisfied. A default is optional; if it isn't there and if none of the cases match, no
action at all takes place. Cases and the default clause can occur in any order.
Consider the following program:
main( )
{
int i = 2;
switch ( i )
{
case 1:
printf ( "I am in case 1 \n" ) ;
case 2:
printf ( "I am in case 2 \n" ) ;
case 3:
printf ( "I am in case 3 \n" ) ;
default :
printf ( "I am in default \n" ) ;
}
}
The output of this program would be:
I am in case 2
I am in case 3
I am in default
Here the program prints case 2 and 3 and the default case. If you want that only case 2
should get executed, it is up to you to get out of the switch then and there by using a break
statement.
main( )
{
int i = 2 ;
switch ( i )
{
case 1:
printf ( "I am in case 1 \n" ) ;
break ;
case 2:
printf ( "I am in case 2 \n" ) ;
break ;
case 3:
printf ( "I am in case 3 \n" ) ;
break ;
default:
printf ( "I am in default \n" ) ;
}
}
The output of this program would be:
I am in case 2
WAP to enter a grade & check its corresponding remarks.
#include <stdio.h>
int main ()
{
char grade;
count = 1;
while ( count <= 3 )
{
printf ( "\nEnter values of p, n and r " ) ;
scanf(“%d %d %f", &p, &n, &r ) ;
si=p * n * r / 100 ;
printf ( "Simple interest = Rs. %f", si ) ;
count = count+1;
}
}
Some outputs of this program:
Enter values of p, n and r 1000 5 13.5
Simple Interest = Rs. 675.000000
Enter values of p, n and r 2000 5 13.5
Simple Interest = Rs. 1350.000000
Enter values of p, n and r 3500 5 13.5
Simple Interest = Rs. 612.000000
The program executes all statements after the while 3 times. These statements form what is
called the ‘body’ of the while loop. The parentheses after the while contain a condition. As
long as this condition remains true all statements within the body of the while loop keep
getting executed repeatedly. Consider the following program;
/* This program checks whether a given number is a palindrome or not */
#include <stdio.h>
int main()
{
int n, reverse = 0, temp;
printf("Enter a number to check if it is a palindrome or not\n");
scanf("%d",&n);
temp = n;
while( temp != 0 )
{
reverse = reverse * 10;
reverse = reverse +temp%10;
temp = temp/10;
}
if ( n == reverse )
printf("%d is a palindrome number.\n", n);
else
printf("%d is not a palindrome number.\n", n);
return 0;
}
Output: Enter a number to check if it is a palindrome or not
12321
12321 is a palindrome
Enter a number to check if it is a palindrome or not
12000
12000 is not a palindrome
do-while Loop
The body of the do-while executes at least once. The do-while structure is similar to the
while loop except the relational test occurs at the bottom (rather than top) of the loop. This
ensures that the body of the loop executes at least once. The do-while tests for a positive
relational test; that is, as long as the test is True, the body of the loop continues to execute.
The format of the do-while is
do
{
block of one or more C statements;
} while (test expression);
The test expression must be enclosed within parentheses, just as it does with a while
statement. Consider the following program
// C program to add all the numbers entered by a user until user enters 0.
#include <stdio.h>
int main()
{
int sum=0,num;
do /* Codes inside the body of do...while loops are at least executed once. */
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}while(num!=0);
printf("sum=%d",sum);
return 0;
}
Output:
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
Program to count the no of digits in a number
#include <stdio.h>
int main()
{
int n,count=0;
printf("Enter an integer: ");
scanf("%d", &n);
do
{
n/=10; /* n=n/10 */
count++;
} while(n!=0);
printf("Number of digits: %d",count);
}
Output
Enter an integer: 34523
Number of digits: 5
for Loop
The for is the most popular looping instruction. The general form of for statement is as
under:
for ( initialise counter ; test counter ; Updating counter )
{
do this;
and this;
and this;
}
The for allows us to specify three things about a loop in a single line:
(a) Setting a loop counter to an initial value.
(b) Testing the loop counter to determine whether its value has reached the number of
repetitions desired.
(c) Updating the value of loop counter either increment or decrement.
Consider the following program
int main(void)
{
int num;
printf(" n n cubed\n");
for (num = 1; num <= 6; num++)
printf("%5d %5d\n", num, num*num*num);
return 0;
}
The program prints the integers 1 through 6 and their cubes.
n n cubed
11
28
3 27
4 64
5 125
6 216
The first line of the for loop tells us immediately all the information about the loop
parameters: the starting value of num, the final value of num, and the amount that num
increases on each looping [5]. Grammatically, the three components of a for loop are
expressions. Any of the three parts can be omitted, although the semicolons must remain.
Consider the following program:
main( )
{
int i ;
for ( i = 1 ; i <= 10 ; )
{
printf ( "%d\n", i ) ;
i=i+1;
}
}
Here, the increment is done within the body of the for loop and not in the for statement.
Note that in spite of this the semicolon after the condition is necessary.
NESTING OF LOOPS
C programming language allows using one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax:
The syntax for a nested for loop statement in C is as follows:
for ( init; condition; increment ) {
for ( init; condition; increment)
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows:
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside of any other type of
loop. For example, a for loop can be inside a while loop or vice versa.
Programs: program using a nested for loop to find the prime numbers from 2 to 20:
#include <stdio.h>
int main ()
{
/* local variable definition */
int i, j;
for(i=2; i<20; i++)
{
for(j=2; j <= (i/j); j++)
if(!(i%j))
break; // if factor found, not prime
if(j > (i/j))
printf("%d is prime\n", i);
}
return 0;
}
Output
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
Program:. *
***
*****
*******
*********
#include <stdio.h>
int main()
{
int row, c, n,I, temp;
printf("Enter the number of rows in pyramid of stars you wish to see ");
scanf("%d",&n);
temp = n;
for ( row = 1 ; row <= n ; row++ )
{
for ( i= 1 ; i < temp ; i++ )
{
printf(" "); temp--;
for ( c = 1 ; c <= 2*row - 1 ; c++ )
{
printf("*"); printf("\n");
}
}
}
return 0;
}
JUMP STATEMENTS
The break Statement
The break statement provides an early exit from for, while, and do, just as from switch. A
break causes the innermost enclosing loop or switch to be exited immediately. When break
is encountered inside any loop, control automatically passes to the first statement after the
loop.
Consider the following example;
main( )
{
int i = 1 , j = 1 ;
while ( i++ <= 100 )
{
while ( j++ <= 200 )
{
if ( j == 150 )
break ;
else
printf ( "%d %d\n", i, j );
}
}
}
In this program when j equals 150, break takes the control outside the inner while only,
since it is placed inside the inner while.
The continue Statement
The continue statement is related to break, but less often used; it causes the next iteration of
the enclosing for, while, or do loop to begin. In the while and do, this means that the test part
is executed immediately; in the for, control passes to the increment step. The continue
statement applies only to loops, not to switch. Consider the following program:
main( ) {
int i, j ;
for ( i = 1 ; i <= 2 ; i++ )
{
for ( j = 1 ; j <= 2 ; j++ )
{
if ( i == j)
continue ;
printf ( "\n%d %d\n", i, j ) ;
}
}
}
The output of the above program would be...
12
21
Note that when the value of I equals that of j, the continue statement takes the control to the
for loop (inner) by passing rest of the statements pending execution in the for loop (inner).
The goto statement
Kernighan and Ritchie refer to the goto statement as "infinitely abusable" and suggest that
it "be used sparingly, if at all. The goto statement causes your program to jump to a
different location, rather than execute the next statement in sequence. The format of the goto
statement is;
goto statement label;
Consider the following program fragment
if (size > 12)
goto a;
goto b;
a: cost = cost * 1.05;
flag = 2;
b: bill = cost * flag;
ss Here, if the if conditions satisfies the program jumps to block labelled as a: if not then it
jumps to block labelled as b:.
9.500000
- 11.500000
Functions
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be
called multiple times to provide reusability and modularity to the C program. In other words,
we can say that the collection of functions creates a program. The function is also known as
procedure or subroutine in other programming languages.
Advantage of functions in C
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
Function Aspects
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and optimizes
the code.
Return Value
A C function may or may not return a value from the function. If you don't have to
return any value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the function.
void hello()
{
printf("hello c");
}
If you want to return any value from the function, you need to use any data type such as
int, long, char, etc. The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the function.
Example with return value: int get()
{
return 10;
}
In the above example, we have to return 10 as a value, so the return type is int. If you want
to return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return
type of the method.
1. float get(){
2. return 10.2; 3. }
Now, you need to call the function, to get the value of the function.
Example 1
1. #include<stdio.h>
2. void printName();
3. void main () 4. {
5. printf("Hello ");
6. printName(); 7. }
8. void printName() 9. {
10. printf("welcome");
11. }
Output
Hello welcome
Example 2
#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:"); sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers"); scanf("%d %d",&a,&b); printf("The sum is %d",a+b);
}
Output
The sum is 34
#include<stdio.h>
1. int sum();
2. void main()
3. {
4. int result;
5. printf("\nGoing to calculate the sum of two numbers:");
6. result = sum();
7. printf("%d",result); 8. }
9. int sum()
10. {
11. int a,b;
12. printf("\nEnter two numbers");
13. scanf("%d %d",&a,&b);
14. return a+b;
15. }
Outputu
calculate the su Going to calculate the sum of two numbers:
Going to calculate the sum of two numbers:
The sum is 34
Example 2: program to calculate the area of the square
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area); 8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
13. scanf("%f",&side);
14. return side * side;
15. }
Output
1. #include<stdio.h>
2. void sum(int, int);
3. void main() 4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }
Output
The sum is 34
1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main() 4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }
Output
1. #include<stdio.h>
2. int sum(int, int);
3. void main() 4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }
Output
Going to calculate the sum of two
numbers: Enter two numbers:10
20
The sum is : 30
1. #include<stdio.h>
2. int even_odd(int);
3. void main() 4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("%d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18. }
19. int even_odd(int n)
20. {
21. if(n%2 == 0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }
Output
Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common
place called the library. Such functions are used to perform some specific operations. For
example, printf is a library function used to print
on the console. The library functions are created by the designers of compilers. All C
standard library functions are defined inside the different header files saved with the
extension .h.
We need to include these header files in our program to make use of the library functions
defined in such header files. For example, To use the library functions such as printf/scanf
we need to include stdio.h in our program which is a header file that contains all the library
functions regarding standard input/output.
The list of mostly used header files is given in the following table.
Call by value in C:
o In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the function
call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter by the
formal parameter.
o In call by value, different memory is allocated for actual and formal parameters since the
value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given
below:
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num); 6. }
7. int main() { 8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num); 4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num); 6. }
7. int main() { 8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main() 4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value
of a and b in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual
parameters do change in c all by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal
parameters, a = 20, b = 10
18. }
Output
Before swapping the values in main a = 10, b =
20 After swapping values in function a = 20, b =
10 After swapping values in main a = 20, b = 10
Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and
such function calls are called recursive calls. Recursion involves several numbers of
recursive calls. However, it is important to impose a termination condition of recursion.
Recursion code is shorter than iterative code however it is difficult to understand.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting,
searching, and traversal problems.
Generally, iterative solutions are more efficient than recursion since function call is always
overhead. Any problem that can be solved recursively, can also be solved iteratively.
However, some problems are best suited to be solved by the recursion, for example, tower
of Hanoi, Fibonacci series, factorial finding, etc.
5.
6.
7.
4
.
{
OUTPUT:
Enter the number
whose factorial you
want to calculate?5
We can understand the above program of the recursive method call by the figure given
below:
Recursive Function:
A recursive function performs the tasks by dividing it into the subtasks. There is a
termination condition defined in the function which is satisfied by some specific subtask.
After this, the recursion stops and the final result is returned from the function.
The case at which the function doesn't recur is called the base case whereas the instances
where the function keeps calling itself to perform a subtask, is called the recursive case. All
the recursive functions can be written using this format.
1. #include<stdio.h>
2. int fibonacci(int);
3. void main () 4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. { return fibonacci(n-1)+fibonacci(n-2);
23. }
24. }
Output
Enter the value of n?
12 144
destroyed. Recursion involves so much complexity in resolving and tracking the values at
each recursive call. Therefore we need to maintain the stack and track the values of the
variables defined in the stack.
Let us consider the following example to understand the memory allocation of the recursive
functions.
Explanation
Let us examine this recursive function for n = 4. First, all the stacks are maintained which
prints the corresponding value of n until n becomes 0, Once the termination condition is
reached, the stacks get destroyed one by one by returning 0 to its calling stack. Consider the
following image for more information regarding the stack trace for the recursive functions.
Storage Classes in C
A storage class defines the scope (visibility) and life-time of variables and/or functions
within a C Program
Storage classes in C are used to determine the lifetime, visibility, memory location, and
initial value of a variable.
There are four types of storage classes in C
o Automatic
o External
o Static
o Register
Automatic
The scope of the automatic variables is limited to the block in which they are defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Example 1
1. #include <stdio.h>
2. int main() 3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and
c.
8. return 0;
9. }
Output:
garbage garbage garbage
Example 2
1. #include <stdio.h>
2. int main() 3. {
4. int a = 10,i;
5. printf("%d ",++a);
6. {
7. int a = 20;
8. for (i=0;i<3;i++)
9. {
10. printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
11. }
12. }
13. printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
14. }
Output:
11 20 20 20 11
Static
o The variables defined as static specifier can hold their value between the multiple
function calls.
o Static local variables are visible only to the function or the block in which they are
defined.
o A same static variable can be declared many times but can be assigned at only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.
Example 1
1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main () 7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }
Output:
0 0 0.000000 (null)
Example 2
1. #include<stdio.h>
2. void sum() 3. {
4. static int a = 10;
5. static int b = 24;
6. printf("%d %d \n",a,b); 7. a++;
8. b++;
9. }
10. void main()
11. {
12. int i;
13. for(i = 0; i< 3; i++)
14. {
15. sum(); // The static variables holds their value between multiple function calls.
16. }
17. }
Output:
10 24
11 25
12 26
Register
o The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the
register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU register.
However, it is compiler?s choice whether or not; the variables can be stored in the register.
o We can store pointers into the register, i.e., a register can store the address of a variable.
o Static variables can not be stored into the register since we can not use more than one
storage specifier for the same variable.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The initial default
value of a is 0.
5. printf("%d",a);
6.
7. .}
Output:
0
Example 2
1. #include <stdio.h>
2. int main() 3. {
4. register int a = 0;
5. printf("%u",&a); // This will give a compile time error since we can not access the
address of a register variable. 6. }
Output:
External
o The external storage class is used to tell the compiler that the variable defined as extern
is declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration
and intended to specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the external
variable within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be
initialized somewhere in the program which may be extern or static. If it is not, then the
compiler will show an error.
Example 1
1. #include <stdio.h>
2. int main() 3. {
4. extern int a;
5. printf("%d",a); 6. }
Output
Example 2
1. #include <stdio.h>
2. int a;
3. int main() 4. {
5. extern int a; // variable a is defined globally, the memory will not be allocated to a
6. printf("%d",a);
7. }Output
0
Example 3
1. #include <stdio.h>
2. int a;
3. int main() 4. {
5. extern int a = 0; // this will show a compiler error since we can not use extern and
initializer at same time
6. printf("%d",a); 7. }
Output
compile time error
main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
extern int a = 0;
Example 4
1. #include <stdio.h>
2. int main() 3. {
4. extern int a; // Compiler will search here for a variable a defined and initialized
somewhere in the pogram or not.
5. printf("%d",a); 6. }
7. int a = 20;
Output
20
Example 5
1. extern int a;
2. int a = 10;
3. #include <stdio.h>
4. int main() 5. {
6. printf("%d",a); 7. }
8. int a = 20; // compiler will show an error at this line
Output
compile time error
C Array
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc. It also has the capability
to store the collection of derived data types, such as pointers, structure, etc. The array is the
simplest data structure where each data element can be randomly accessed by using its index
number.
C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different variables for
the marks in the different subject. Instead of that, we can define an array which can store the
marks in each subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.
Properties of Array:
o Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
o Elements of the array are stored at contiguous memory locations where the first element
is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.
Advantage of C Array:
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array:
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will
learn later.
Types of Arrays:
Declaration of C Array
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of Array
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.
1. #include<stdio.h>
2. void main () 3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1]; 14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27. }
Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.
1. int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the
following code.
1. int marks[]={20,30,40,50,60};
1. #include<stdio.h>
2. int main(){ 3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array 6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
10. }//end of j
11. }//end of i
12. return 0;
13. } Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
Pointer Expressions
Arithmetic Operators:
We can perform arithmetic operations to pointer variables using arithmetic operators. We
can add an integer or subtract an integer using a pointer pointing to that integer variable.
The given table shows the arithmetic operators that can be performed on pointer
variables:
Examples:
*ptr1 + *ptr2
*ptr1 * *ptr2
*ptr1 + *ptr2 - *ptr3
We can also directly perform arithmetic expression using integers. Lets look at the
example given below where p1 and p2 are pointers.
p1+10, p2-5, p1-p2+10, p1/2
Below diagram represents how exactly the expression/operators work with pointers.
Let us understand pointer arithmetic expression better with given code:
#include <stdio.h>
int main()
{
// Integer variables
int a = 20, b = 10;
// Initialization of pointers
ptr_a = &a;
ptr_b = &b;
Output:
Addition = 30
Subtraction = 10
Multiplication = 200
Division = 2
Modulo = 0
Note: While performing division, make sure you put a blank space between ‘/’ and ‘*’ of
the pointer as together it would make a multi-line comment(‘/*’).
Example:
Incorrect: *ptr_a/*ptr_b;
Correct: *ptr_a / *ptr_b;
Correct: (*ptr_a)/(*ptr_b);
Relational Operators:
Relational operations are often used to compare the values of the variable based on which we
can take decisions. The given table shows the relational operators that can be performed on
pointer variables.
Example:
*ptr1 > *ptr2
*ptr1 < *ptr2
The value of the relational expression is either 0 or 1 that is false or true. The expression
will return value 1 if the expression is true and it’ll return value 0 if false.
Let us understand relational expression on pointer better with the code given below:
// Equal to
if (*ptr_a == *ptr_b) { printf( "%d is equal to %d.", *ptr_a, *ptr_b);
}
return 0;
}
Output:
20 is greater than 10.
Output:
20 is greater than 10.
Assignment Operators:
Assignment operators are used to assign values to the identifiers. There are multiple
shorthand operations available. A table is given below showing the actual assignment
statement with its shorthand statement.
Examples:
*a=10
*b+=20
*z=3.5
*s=4.56743
Let us understand assignment operator in better way with the help of code given below:
int* ptr_a;
return 0;
}
Output:
Value of variable a = 50
Conditional Operators
There is only one mostly used conditional operator in C known as Ternary operator.
Ternary operator first checks the expression and depending on its return value returns true
or false, which triggers/selects another expression.
Syntax:
expression1 ? expression2 : expression3;
Example:
c = (*ptr1 > *ptr2) ? *ptr1 : *ptr2;
As shown in example, assuming *ptr1=20 and *ptr2=10 then the condition here becomes
true for the expression, so it’ll return value of true expression i.e. *ptr1, so variable ‘c’
will now contain value of 20.
Considering same example, assume *ptr1=30 and *ptr2=50 then the condition is false for
the expression, so it’ll return value of false expression i.e. *ptr2, so variable ‘c’ will now
contain value 50.
Let us understand the concept through the given code:
// Program showing pointer expressions during Conditional Operations
#include <stdio.h>
int main()
{
// Initializing Integer variables
int a = 15, b = 20, result = 0;
// Declaring pointer
variables int *ptr_a, *ptr_b;
ptr_b = &b;
Output:
20 is the greatest.
Unary Operators:
There are mainly two operators which are given as follows.
Examples:
(*ptr1)++
(*ptr1)--
Let us understand the use of the unary operator through the given code:
// Value of a before
increment
printf("Increment:\
n");
printf(
‘”Before increment a = %d\n", *ptr_a);
// Unary increment
operation (*ptr_a)
++;
return 0;
}
Output:
Increment:
Before increment a = 34
After increment a = 35
Decrement:
Before decrement a = 35
After decrement a=34
Bitwise Operators:
Binary operators are also known as bitwise operators. It is used to manipulate data at bit
level. Bitwise operators can’t be used for float and double datatype. A table is shown
below with all bitwise operators:
Examples:
*ptr1 & *ptr2
*ptr1 | *ptr2
*ptr1 ^ *ptr2
Let us understand the concept through the given code:
// OR operation
or = a | b;
// EX-OR
peration
ex_or = a ^
b;
Output:
a AND b = 0
a OR b = 3
a Exclusive-OR b = 3
Structures
Arrays allow to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows to combine
data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in
a library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
Defining a Structure:
To define a structure, you must use the struct statement. The struct statement defines a new
data type, with more than one member. The format of the struct statement is as follows –
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables but it
is optional. Here is the way you would declare the Book structure –
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use the keyword struct to define variables of
structure type. The following example shows how to use a structure in a program –
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
To define a union, you must use the union statement in the same way as you did while
defining a structure. The union statement defines a new data type with more than one
member for your program. The format of the union statement is as follows –
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such
as int i; or float f; or any other valid variable definition. At the end of the union's definition,
before the final semicolon, you can specify one or more union variables but it is optional.
Here is the way you would define a union type named Data having three members i, f, and
str –
union data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store
multiple types of data. You can use any built-in or user defined data types inside a union
based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the
union. For example, in the above example, Data type will occupy 20 bytes of memory space
because this is the maximum space which can be occupied by a character string. The
following example displays the total memory size occupied by the above union .
#include <stdio.h>
#include <string.h>
union Data {
int i;
float
f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20
#include <stdio.h>
#include <string.h>
union collecton {
int i;
float f;
char str[20];
};
int main( ) {
union collection{
data; data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
};
int main( ) { union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a
time.
Enumeration
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.
3
Output:
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:
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer.
Consider the following example to define a pointer which stores the address of an integer.
1. int n = 10;
2. int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of
type integer.
Declaring a pointer:
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
1. int *a;//pointer to int
2. char *c;//pointer to char
Pointer Example
An example of using pointers to print the address and value is given below.
68M
1.3K
As you can see in the above figure, pointer variable stores the address of number variable,
i.e., fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p. Let's
see the pointer example as explained for the above figure.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %x \n",p); // p contains the address of the number
therefore printing p gives the ad dress of number.
7. printf("Value of p variable is %d \n",*p); /* As we know that * is used to dereference a
pointer therefore if we
8. print *p, we will get the value stored at the address contained by p. */
9. return 0;
10. }
Output
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees, etc. and used with arrays, structures, and functions.
2) We can return multiple values from a function using the pointer.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many applications of pointers in c language.
1) Dynamic memory allocation:
In c language, we can dynamically allocate memory using malloc() and calloc() functions
where the pointer is used.
2) Arrays, Functions, and Structures:
Pointers in c language are widely used in arrays, functions, and structures. It reduces the
code and improves the performance.
Address Of (&) Operator:
The address of operator '&' returns the address of a variable. But, we need to use %u to
display the address of a variable.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. printf("value of number is %d, address of number is %u",number,&number);
5. return 0;
6. } Output
value of number is 50, address of number is fff4
The C language supports two kinds of memory allocation through the variables in C
programs:
Static allocation is what happens when you declare a static or global variable. Each
static or global variable defines one block of space, of a fixed size. The space is allocated
once, when your program is started (part of the exec operation), and is never freed.
Automatic allocation happens when you declare an automatic variable, such as a
function argument or a local variable. The space for an automatic variable is allocated when
the compound statement containing the declaration is entered, and is freed when that
compound statement is exited.
In GNU C, the size of the automatic storage can be an expression that varies. In other C
implementations, it must be a constant.
A third important kind of memory allocation, dynamic allocation, is not supported by C
variables but is available via GNU C Library functions.
Let's understand the difference between static memory allocation and dynamic memory
allocation.
static memory allocation dynamic memory allocation
Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() allocates single block of requested memory.
The malloc() function allocates single block of requested memory. It returns NULL if
memory is not sufficient.
The syntax of malloc() function is given below:
1. ptr=(cast-type*)malloc(byte-size)
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: "); 14.for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
Output
calloc() function in C:
The calloc() function allocates multiple block of requested memory. It initially initialize all
bytes to zero.
It returns NULL if memory is not sufficient.
The syntax of calloc() function is given below:
ptr=(cast-type*)calloc(number, byte-size)
Let's see the example of calloc() function.
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
realloc() function in C:
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by
realloc() function. In short, it changes the memory size.
Let's see the syntax of realloc() function.
1. ptr=realloc(ptr, new-size)
free() function in C:
The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until program exit.
Let's see the syntax of free() function.
1. free(ptr)
Reading complex pointers:
There are several things which must be taken into the consideration while reading the
complex pointers in C. Lets see the precedence and associativity of the operators which are
used regarding pointers.
Data type 3 -
Here,we must notice that,
o (): This operator is a bracket operator used to declare and define the function.
o []: This operator is an array subscript operator
o * : This operator is a pointer operator.
o Identifier: It is the name of the pointer. The priority will always be assigned to this.
o Data type: Data type is the type of the variable to which the pointer is intended to point.
It also includes the modifier like signed int, long, etc).
C Function Pointer:
As we know that we can create a pointer of any data type such as int, char, float, we can also
create a pointer pointing to a function. The code of a function always resides in memory,
which means that the function has some address. We can get the address of memory by
using the function pointer.
Let's see a simple example.
1. #include <stdio.h>
2. int main() 3. {
4. printf("Address of main() function is %p",main);
5. return 0;
6. }
The above code prints the address of main() function.
Output
In the above output, we observe that the main() function has some address. Therefore, we
conclude that every function has some address.
Declaration of a function pointer:
Till now, we have seen that the functions have addresses, so we can create pointers that can
contain these addresses, and hence can point them.
Syntax of function pointer
1. return type (*ptr_name)(type1, type2…); For example:
1. int (*ip) (int);
In the above declaration, *ip is a pointer that points to a function which returns an int value
and accepts an integer value as an argument.
1. float (*fp) (float);
In the above declaration, *fp is a pointer that points to a function that returns a float value
and accepts a float value as an argument.
We can observe that the declaration of a function is similar to the declaration of a function
pointer except that the pointer is preceded by a '*'. So, in the above declaration, fp is
declared as a function rather than a pointer.
Till now, we have learnt how to declare the function pointer. Our next step is to assign the
address of a function to the function pointer.
1. float
(*fp) (int , int);// Declaration of a function pointer. 2.float func( int , int ); //
Declaration of function.
3.fp = func; // Assigning address of func to the fp pointer.
In the above declaration, 'fp' pointer contains the address of the 'func' function.
1. #include <stdio.h>
2. int add(int,int);
3. int main() 4. {
5. int a,b;
6. int (*ip)(int,int);
7. int result;
8. printf("Enter the values of a and b : ");
9. scanf("%d %d",&a,&b);
10. ip=add;
11. result=(*ip)(a,b);
12. printf("Value after addition is : %d",result);
13. return 0;
14. }
15. int add(int a,int b)
16. {
17. int c=a+b;
18. return c;
19. }
Output
Structures
Arrays allow to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows to combine
data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in
a library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
Defining a Structure:
To define a structure, you must use the struct statement. The struct statement defines a new
data type, with more than one member. The format of the struct statement is as follows –
struct [structure tag] {
The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables but it
is optional. Here is the way you would declare the Book structure –
struct Books { char title[50]; char author[50];
char subject[100]; int book_id;
} book;
Accessing Structure Members:
To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use the keyword struct to define variables of
structure type. The following example shows how to use a structure in a program –
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50]
char subject[100];
int book_id;
};
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
Union
A union is a user defined data type available in C that allows to store different data types in
the same memory location. You can define a union with many members, but only one
member can contain a value at any given time. Unions provide an efficient way of using the
same memory location for multiple-purpose.
Defining a Union:
To define a union, you must use the union statement in the same way as you did while
defining a structure. The union statement defines a new data type with more than one
member for your program. The format of the union statement is as follows –
union [union tag] { member definition; member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such
as int i; or float f; or any other valid variable definition. At the end of the union's definition,
before the final semicolon, you can specify one or more union variables but it is optional.
Here is the way you would define a union type named Data having three members i, f, and
str –
union Data { int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store
multiple types of data. You can use any built-in or user defined data types inside a union
based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the
union. For example, in the above example, Data type will occupy 20 bytes of memory space
because this is the maximum space which can be occupied by a character string. The
following example displays the total memory size occupied by the above union .
#include <stdio.h> #include <string.h> union Data {
int i; float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data)); return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final
value assigned to the variable has occupied the memory location and this is the reason that
the value of str member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time
which is the main purpose of having unions –
#include <stdio.h>
#include <string.h>
union Data {
int i; float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a
time.
Enumeration
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.
C Strings
The string can be defined as the one-dimensional array of characters terminated by a null
('\0'). The character array or the string is used to manipulate text such as word or sentences.
Each character in the array occupies one byte of memory, and the last character must
always be 0. The termination character ('\0') is important in a string since it is the only way
to identify where the string ends.
When we define a string as char s[10], the character s[10] is implicitly initialized
with the null in the memory.
There are two ways to declare a string in c language.
1. By char array
2. By string literal
Let's see the example of declaring string by char array in C language.
1. char ch[10]={'p', 'r', 'o', 'g', 'r', 'a', 'm', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given below.
p r o g r a m \0
While declaring string, size is not mandatory. So we can write the above code as given
below:
1. char ch[]={'p', 'r', 'o', 'g', 'r', 'a', 'm', '\0'};
We can also define the string by the string literal in C language. For example:
1. char ch[]="program";
In such case, '\0' will be appended at the end of the string by the compiler.
o The string literal cannot be reassigned to another set of characters whereas, we can
reassign the characters of the array.
String Example in C:
Let's see a simple example where a string is declared and being printed. The '%s' is used as
a format specifier for the string in c language.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[11]= {'p', 'r', 'o', 'g', 'r', 'a', 'm', '\0'};
5. char ch2[11]="program"; 6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10. }
Output
Char Array Value is: program
String Literal Value is: program
Traversing String:
Traversing string is somewhat different from the traversing an integer array. We need to
know the length of the array to traverse an integer array, whereas we may use the null
character in the case of string to identify the end the string and terminate the loop.
Hence, there are two ways to traverse a string.
o By using the length of string
o By using the null character. Let's discuss each one of them. Using the length of string:
Let's see an example of counting the number of vowels in a string.
1. #include<stdio.h>
2. void main () 3. {
4. char s[11] = "javatpoint";
5. int i = 0;
6. int count = 0;
7. while(i<11)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }
Output
The number of vowels 4
Using the null character:
Let's see the same example of counting the number of vowels by using the null character.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "javatpoint";
5. int i = 0;
6. int count = 0;
7. while(s[i] != NULL) 8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }
Output
The number of vowels 4
It is clear from the output that, the above code will not work for space separated strings. To
make this code working
for the space separated strings, the minor changed required in the scanf function, i.e., instead
of writing scanf("%s",s), we must write: scanf("%[^\n]s",s) which instructs the compiler to
store the string s while the new line (\n) is encountered. Let's consider the following
example to store
1. #include<stdio.h>
2. void main () 3. {
4. char s[20];
5. printf("Enter the string?"); 6. scanf("%[^\n]s",s);
7. printf("You entered %s",s); 8. }
Output
Enter the string? programing language
You entered programing language
Here we must also notice that we do not need to use address of (&) operator in scanf to store
a string since string s
is an array of characters and the name of the array, i.e., s indicates the base address of the
string (character array) therefore we need not use & with it.
The gets() and puts() are declared in the header file stdio.h. Both the functions are involved
in the input/output operations of the strings.
gets() function:
The gets() function enables the user to enter some characters followed by the enter key. All
the characters entered by the user get stored in a character array. The null character is added
to the array to make it a string. The gets() allows the user to enter the space-separated
strings. It returns the string entered by the user.
Declaration
1. char[] gets(char[]);
Reading string using gets()
1. #include<stdio.h>
2. void main () 3. {
4. char s[30];
5. printf("Enter the string? ");
6. gets(s);
Output
Enter the string? programing language
You entered programing language
The gets() function is risky to use since it doesn't perform any array bound checking and
keep reading the characters
until the new line (enter) is encountered. It suffers from buffer overflow, which can be
avoided by using fgets(). The fgets() makes sure that not more than the maximum limit of
characters are read. Consider the following example.
puts() function:
The puts() function is very much similar to printf() function. The puts() function is used to
print the string on the console which is previously read by using gets() or scanf() function.
The puts() function returns an integer value representing the number of characters being
printed on the console. Since, it prints an additional newline character with the string, which
moves the cursor to the new line on the console, the integer value returned by puts() will
always be equal to the number of characters present in the string plus 1.
Declaration
1. int puts(char[])
Let's see an example to read a string using gets() and print it on the console using puts().
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char name[50];
5. printf("Enter your name: ");
6. gets(name); //reads string from user
7. printf("Your name is: ");
8. puts(name); //displays string
9. return 0;
10. }
Output:
String Functions:
There are many important string functions defined in "string.h" library.
S.No Function Description
Enter string:
javatpoint String is:
javatpoint
Output:
String strstr():
The strstr() function returns pointer to the first occurrence of the matched string in the
given string. It is used to return substring from first match till the last character.
Syntax:
1. char *strstr(const char *string, const char *match)
a-b = 5
a*b = 36
a/b = 2