Unit-2 Fundamentals of C
Unit-2 Fundamentals of C
1
Features of C Language
Features of C Language
▪ Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.
▪ Machine Independent or Portable
Unlike assembly language, c programs can be executed on different
machines with some machine specific changes. Therefore, C is a machine
independent language.
▪ Mid-level programming language
Although, C is intended to do low-level programming. It is used to develop
system applications such as kernel, driver, etc.
It also supports the features of a high-level language. That is why it is known
as mid-level language.
▪ Structured programming language
C is a structured programming language in the sense that we can break the
program into parts using functions.
So, it is easy to understand and modify. Functions also provide code reusability.
Features of C Language
▪ Rich Library
C provides a lot of inbuilt functions that make the development fast.
▪ Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free
the allocated memory at any time by calling the free() function.
▪ Speed
The compilation and execution time of C language is fast since there are lesser
inbuilt functions and hence the lesser overhead..
▪ Pointer
C provides the feature of pointers. We can directly interact with the memory by
using the pointers.
▪ Recursion
In C, we can call the function within the function. It provides code reusability for
every function. Recursion enables us to use the approach of backtracking.
▪ Extensible
C language is extensible because it can easily adopt new features.
Structure of C Program
n section // Program for addition of 2 nos
▪(Used for comments)
#include<stdio.h>
#define PI 3
void fun();
int a=10;
void main( )
{
printf("Value of a inside main
function: %d", a);
fun();
}
void fun()
Comments
▪ A comment is an explanation or description of the source code of the
program.
▪ It helps a programmer to explain logic of the code and improves program
readability.
▪ At run-time, a comment is ignored by the compiler.
▪ There are two types of comments in C:
▪ Single line comment
▪ Represented as // double forward slash
▪ It is used to denote a single line comment only.
▪ Example: // Single line comment
▪ Multi-line comment
▪ Represented as /* any_text */ start with forward slash and asterisk (/*) and end with
asterisk and forward slash (*/).
▪ It is used to denote single as well as multi-line comment.
▪ Example: /* multi line comment line -1
▪ multi line comment line -2 */
Header files
▪ In C language, header files contain the set of predefined standard
library functions.
▪ The “#include” preprocessing directive is used to include the
header files with “.h” extension in the program.
Header file Description
stdio.h Input/Output functions (printf and scanf)
conio.h Console Input/Output functions (getch and
clrscr)
Data types in C
int main()
{
int a=10; Example:: Example_data.c
float b=20.123456789; Example:: Example_data1.c
char c='a';
double d=45.12345678911225;
return 0;
}
ASCII value in C
▪ The full form of ASCII is the American Standard Code for
information interchange.
▪ It is a character encoding scheme used for electronics
communication. Each character or a special character is
represented by some ASCII code.
▪ In C programming language, a character variable does not contain
a character value itself rather the ascii value of the character
variable.
▪ The ascii value represents the character variable in numbers, and
each character variable is assigned with some number range from
0 to 127. For example, the ascii value of 'A' is 65.
▪ https://en.cppreference.com/w/cpp/language/ascii
Example of Ascii code and Charcter
#include <stdio.h>
int main()
{
char ch; // variable declaration
printf("Enter a character");
scanf("%c",&ch); // user input
printf("\n The ascii value of the ch variable %c is : %d",ch, ch);
return 0;
}
Example::Example_data2.c
Example::Example_data3.c
Constants in C
▪ A constant is a value assigned to the variable which will remain
the same throughout the program, i.e., the constant value cannot
be changed.
▪ There are two ways of declaring constant:
• Using const keyword
• Using #define pre-processor
Constant Example
Integer constant 10, 11, 34, etc.
Floating-point constant 45.6, 67.8, 11.2, etc.
Octal constant 011, 088, 022, etc.
Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.
Character constant 'a', 'b', 'c', etc.
String constant "java", "c++", ".net", etc.
Example (Constant_var.c)
/* Program illustarting use of declartion, assignment of value to variables. Also explains how to use
symbolic constants.
Program to calculate area and circumference of a circle */
#include <stdio.h>
#define PI 3.1415 /* no semicolon here */
int main()
{
float rad = 5; /* declaration and assignment */
float area, circum; /* declaration of variable */
// pi=500.4;
printf("Area of circle = %f\n",area);
printf("Circumference of circle =%f\n",circum);
return 0;
}
Strings in C
▪ Strings in C are always represented as an array of characters having null
character '\0' at the end of the string.
▪ This null character denotes the end of the string.
▪ Strings in C are enclosed within double quotes, while characters are
enclosed within single characters.
▪ The size of a string is a number of characters that the string contains.
▪ Example:
• char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a'
array.
• char a[] = "javatpoint"; // The compiler allocates the memory at the run time.
• char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the
form of characters.
Special characters in C
▪ Some special characters are used in C, and they have a special meaning which
cannot be used for another purpose.
▪ Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
▪ Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
▪ Curly braces { }: It is used in the opening and closing of the code. It is used in
the opening and closing of the loops.
▪ Comma (,): It is used for separating for more than one statement and for
example, separating function parameters in a function call, separating the
variable when printing the value of more than one variable using a single printf
statement.
▪ Hash/pre-processor (#): It is used for pre-processor directive. It basically
denotes that we are using the header file.
▪ Asterisk (*): This symbol is used to represent pointers and also used as an
operator for multiplication.
▪ Tilde (~): It is used as a destructor to free memory.
▪ Period (.): It is used to access a member of a structure or a union.
Operators
▪ Arithmetic operators (+, - , *, /, %)
▪ Relational operators (<, <=, >, >=, ==, !=)
▪ Logical operators (&&, ||, !)
▪ Assignment operators (+=, -=, *=, /=)
▪ Increment and decrement operators (++, --)
▪ Conditional operators (?:)
▪ Bitwise operators (&, |, ^, <<, >>)
▪ Special operators ()
Arithmetic Operators
▪ Arithmetic operators are used for mathematical calculation.
Program explaining Arithmetic operators
/* Program illustrating use of arithmetic operators. The numbers x and y are initialized in the program
itself with x = 25 and y =4 */
#include <stdio.h>
main()
{
int x=25;
int y=4;
printf("%d + %d = %d\n",x,y,x+y);
printf("%d - %d = %d\n",x,y,x-y);
printf("%d * %d = %d\n",x,y,x*y);
printf("%d / %d = %d\n",x,y,x/y);
printf("%d %% %d = %d\n",x,y,x%y);
}
Output
---------------------------------------------------------------------------------------------------------
25 + 4 = 29
25 - 4 = 21
25 * 4 = 100
25 / 4 = 6
25 % 4 = 1
---------------------------------------------------------------------------------------------------------
Relational Operators
▪ Relational operators are used to compare two numbers and taking
decisions based on their relation.
▪ Relational expressions are used in decision statements such as if, for,
while, etc…
return 0;
}
Logical Operators
▪ Logical operators are used to test more than one condition and
make decisions.
a b a&&b a||b
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
Assignment Operators
▪ Assignment operators (=) is used to assign the result of an
expression to a variable.
▪ Assignment operator stores a value in memory.
▪ C also supports shorthand assignment operators which simplify
operation with assignment.
Example Assignment operator
#include <stdio.h>
int main()
{
int a;
Example::
printf("Give the value of a\n");
scanf("%d",&a); assignment_op.c
a += 5; /* a= a +5 */
printf("a= %d\n",a);
a -= 5; /* a = a-5 */
printf("a= %d\n",a);
a *=5; /* a = a* 5 */
printf("a= %d\n",a);
a /=5; /* a= a /5 */
printf("a= %d\n",a);
a %= 5; /* a= a %5 */
printf("a= %d\n",a);
return 0;
}
Increment/Decrement operators
▪ Increment (++) operator used to increase the value of the variable
by one.
▪ Decrement (--) operator used to decrease the value of the variable
by one.
Example
▪ If a is a variable, then x=100;
x++;
++a is called prefix increment
Explanation
a++ is called postfix increment.
After the execution the
▪ Similarly, value of x will be 101.
Operator Description
Post increment operator (x++) value of x is incremented after assigning it to the
variable on the left
Example: Bitwise << (Shift Left) Example: Bitwise >> (Shift Right)
int a=8, b; int a=8, b;
b = a << 1; b = a >> 1;
printf("Output = %d", b); printf("Output = %d", b);
Output Output
16 (multiplying a by a power of 4 (dividing a by a power of
two) two)
Special Operators
Precedence and associativity of operators
▪ When arithmetic expressions are evaluated, the answer of that
expression depends on the value of operands, the operators used
and also on the precedence and associativity of the operators
used.
▪ Precedence of an operator is its priority in an expression for
evaluation.
▪ The operator with higher precedence is evaluated first and the
operator with the least precedence is evaluated last.
▪ Operator precedence is why the expression 5 + 3 * 2 is calculated
as 5 + (3 * 2), giving 11, and not as (5 + 3) * 2, giving 16.
▪ We say that the multiplication operator (*) has higher
"precedence" or "priority" than the addition operator (+), so the
multiplication must be performed first.
Operator associativity
▪ Associativity is the left-to-right or right-to-left order for grouping
operands to operators that have the same precedence.
▪ Operator associativity is why the expression 8 - 3 - 2 is calculated
as (8 - 3) - 2, giving 3, and not as 8 - (3 - 2), giving 7.
▪ We say that the subtraction operator (-) is "left associative", so
the left subtraction must be performed first.
▪ When we can't decide by operator precedence alone in which
order to calculate an expression, we must use associativity.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
5-3 * 4 + 6 /4
▼
5 - 12 + 6/4
▼
5 - 12 + 1
▼
-7 +1
▼
-6
Type conversion
▪ Whenever an expression involves two different types of operands,
‘C’ language applies the type conversion rules to evaluate an
expression.
▪ Type conversion is converting one type of data to another type.
• Implicit Type Conversion
• This type of conversion is usually performed by the compiler when
necessary without any commands by the user.
• It is also called Automatic Type Conversion.
• Explicit Type Conversion
• These conversions are done explicitly by users using the pre-defined
functions.
Implicit Type conversion
▪ If the operands are of different type, then the operand with a
lower type is upgraded to the higher type and then the operation
is performed.
▪ In the case of assignment,
• If float is assigned to integer, then fractional part is truncated as shown in
above program.
• If double is assigned to float, then rounding takes place.
• If long int is assigned to integer, then additional bits are dropped,
remember that long int requires 4 bytes while int requires only 2 bytes.
Program – Type Conversion (Example::typecast.c)
#include <stdio.h>
In the statement b = a *c +d /10,
main()
{
◻ a*c will be done first, here a will be upgraded
int a,b;
to float because other operand c is float.
float c; So, a*c will evaluate to 27.5.
double d;
a=5; ◻ Then, d/10 will be evaluated, 10 will be
c= 5.5; converted into 10.0 (double) because d is
d = 4.0; double. So, d/10 will evaluate to 0.4.
clrscr();
b = a *c +d /10; ◻ Then 27.5 + 0.4 evaluates to 27.9. This value is
printf("value of b = %d\n",b);
assigned to variable b, which is integer, so
truncated value of 27.9 will be the value of b
}
i.e 27 will be assigned to b.
Output
Type casting
▪ When user needs the type conversion explicitly, then type casting
is used.
▪ Type conversion is automatic while type casting is explicitly
specified by the programmer in the program.
▪ The type casting can be specified in following form
(typename) expression;
Program - Type casting
#include <stdio.h>
main()
{
int sum =47;
Example:: typecast1.c
int n = 10;
float avg;
clrscr();
avg = sum/n; /*avg without type cast */
printf("avg=sum/n = %f\n",avg);
avg = (float)sum/n; /*avg with type cast on sum */
printf("avg=(float)sum/n = %f\n", avg);
avg = (float)(sum/n); /*avg without type cast on (sum/n) */
printf("avg=(float)(sum/n) = %f\n", avg);
}
Output
---------------------------------------------------------------------------------------------------------
avg=sum/n = 4.000000
avg=(float)sum/n = 4.700000
avg=(float)(sum/n) = 4.000000
Preprocessor directives
▪ Preprocessors are programs that process our source code before
compilation.
▪ There are a number of steps involved between writing a program
and executing a program in C.
▪ Let us have a look at these steps before we actually start learning
about Preprocessors.
C Program
Object Executable
Are there
No Code Code
preprocessor Compiler Linker
directive
Preprocessor perform
action
Preprocessor directives
▪ Preprocessor is a program that processes the source program
before the control is given to the compiler.
▪ Preprocessor understands some commands known as
preprocessor directives.
▪ The directive begins with symbol #. There are many directives
which the preprocessor understands.
For example,
#include <stdio.h>
# define PI 3.1415
include directive includes the file mentioned after it, while define
directive defines a symbolic constant.
Macro
▪ A macro is a fragment of code which has been given a name.
Whenever the name is used in program, it is replaced by the
contents of the macro.
▪ Macro definitions are not variables and cannot be changed by
your program code like variables.
▪ The ‘#define’ directive is used to define a macro.
▪ Do not put a semicolon ( ; ) at the end of #define statements.
▪ There are two types of macros:
• Object-like Macros
• Function-like Macros
Macro
printf(“%2d”,456); 4 5 6
printf(“%05d”,456); 0 0 4 5 6
printf(“%-5d”,456); 4 5 6
printf(“%+5d”,456); + 4 5 6
printf(“%#5o”,456); 0 7 1 0
printf(“%#5x”,456); 0x1c8 0 X 1 c 8
Formatted Output(Example::formatted_out1.c)
▪ The format specification for floating data is %w.pf
Where, w denotes width, p denotes number of digits after decimal point,
and f denotes float number. If e is used in place of f, then the number is
displayed in scientific notation.
▪ If width is not specified, then the floating point number is
displayed with six decimal point digits.
Format Output
printf(“%f”,45.678); 4 5 . 6 7 8 0 0 0
printf(“%7.2f”,45.678); 4 5 . 6 8
printf(“%-7.2f”,45.678);
4 5 . 6 8
printf(“%7.2e”,45.678);
4 . 5 7 e + 0 1
printf(“%e”,45.678);
4 . 5 6 7 8 0 0 e 0 1