C Programming unit I
C Programming unit I
Easy to learn
Structured language
It produces efficient programs
It can handle low-level activities
It can be compiled on a variety of computer platforms
Facts about C
Constants
An entity whose value doesn’t change is called a constant.
Types of constant
Primarily there are 3 types of constant:
1. Integer Constant -1,6,7,9
2. Real Constant -322.1,2.5,7.0
3. Character Constant ‘a’,’$’,’@’(must be enclosed within single inverted commas)
Keywords
These are reserved words whose meaning is already known to the compiler. There are 32
keywords available in c:
Types of variables
Integer variables int a=3;
Real variables int a=7.7 (wrong as 7.7 is real) ; float a=7.7;
Character variables char a=’B’;
Receiving input from the user
In order to take input from the user and assign it to a variable, we use scanf function.
The syntax for using scanf:
scanf(“%d”,&i); // [This & is important]
& is the “address of” operator, and it means that the supplied value should be copied to the
address which is indicated by variable i.
Data Type
Data types in c refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage and
how the bit pattern stored is interpreted.
The types in C can be classified as follows −
1 Basic Types
They are arithmetic types and are further classified into: (a) integer types and (b)
floating-point types.
2 Enumerated types
They are again arithmetic types and they are used to define variables that can
only assign certain discrete integer values throughout the program.
3 The type void
Floating-Point Types
The following table provide the details of standard floating-point types with storage sizes and
value ranges and their precision −
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of one or more
variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names separated
by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to
create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
Defining Constants
There are two simple ways in C to define constants −
Using #define preprocessor.
Using const keyword.
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant –
Syntax
#define identifier value
The following example explains it in detail −
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Output:
value of area : 50
The const Keyword
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Output:
value of area : 50
Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of
operators.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
We will, in this chapter, look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −
Show Examples
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = 10
* Multiplies both operands. A * B =200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of after an integer division. B%A=0
++ Increment operator increases the integer value by one. A++ = 11
-- Decrement operator decreases the integer value by one. A-- = 9
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A
holds 10 and variable B holds 20 then –
Show Examples
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60
and variable 'B' holds 13, then −
Show Examples
Operator Description Example
& Binary AND Operator copies (A & B) = 12, i.e., 0000 1100
a bit to the result if it exists in
both operands.
Assignment Operators
The following table lists the assignment operators supported by the C language −
Show Examples
Operator Description Example
Conditional Operator in C
The Conditional Operator in C, also called a Ternary operator, is one of the Operators, which
used in the decision-making process. The C Programming Conditional Operator returns the
statement depends upon the given expression result.
The basic syntax of a Ternary Operator in C Programming is as shown below:
#include<stdio.h>
int main()
{
int age;
printf(" Please Enter your age here: \n ");
scanf(" %d ", &age);
(age >= 18) ? printf(" You are eligible to Vote ") : printf(" You are not eligible to
Vote ");
return 0;
}
OUTPUT:
Increment Operators:
The increment operator is used to increment the value of a variable in an expression. In the Pre-
Increment, value is first incremented and then used inside the expression. Whereas in the Post-
Increment, value is first used inside the expression and then incremented.
Syntax:
// PREFIX
++m
// POSTFIX
m++
where m is a variable
Example:
#include <stdio.h>
// POSTFIX
b = a++;
printf("%d", b);
// PREFIX
int c = ++b;
printf("\n%d", c);
}
// Driver code
int main()
{
int x, y;
increment(x, y);
return 0;
}
Decrement Operators:
The decrement operator is used to decrement the value of a variable in an expression. In the
Pre-Decrement, value is first decremented and then used inside the expression. Whereas in the
Post-Decrement, value is first used inside the expression and then decremented.
Syntax:
// PREFIX
--m
// POSTFIX
m--
where m is a variable
Example:
#include <stdio.h>
// POSTFIX
b = a--;
printf("%d", b);
// PREFIX
int c = --b;
printf("\n%d", c);
}
// Driver code
int main()
{
int x, y;
decrement(x, y);
return 0;
}
ARITHMETIC EXPRESSIONS IN C
PROGRAMMING – I
Notice the equal sign (=) in the above expressions, it is known as the assignment
operator. It assigns the value on the right hand side of the equal sign to the variable on
the left hand side.
In the last expression, parentheses are used to perform a certain operation first. This is
because in C, operators follow a precedence rule. *, / and % have a higher precedence
over + and -. Hence to override the precedence, parentheses should be used.
Expressions having operators of the same precedence are generally evaluated from left
to right.
Another point to note is that in an expression which involves division, care should be
taken to avoid a division by zero, since this results in infinity or an abnormal value.
#include <stdio.h>
Void main()
{
int var1 = 10;
int var2 = 2;
int var3 = 35;
int var4 = 8;
int result;
result = var1 + var2;
printf("Sum of var1 and var2 is %d\n", result);
result = var3 * var3;
printf("Square of var3 is %d\n", result);
result = var2 +var3 * var4; /* precedence */
printf("var2 + var3 * var4 =%d\n", result);
}
Evaluation of Expression
In the C programming language, an expression is evaluated based on the operator precedence
and associativity. When there are multiple operators in an expression, they are evaluated
according to their precedence and associativity. The operator with higher precedence is
evaluated first and the operator with the least precedence is evaluated last.An expression is
evaluated based on the precedence and associativity of the operators in that expression.
To understand expression evaluation in c, let us consider the following simple example
expression...
10 + 4 * 3 / 2
In the above expression, there are three operators +, * and /. Among these three operators,
both multiplication and division have the same higher precedence and addition has lower
precedence. So, according to the operator precedence both multiplication and division are
evaluated first and then the addition is evaluated. As multiplication and division have the
same precedence they are evaluated based on the associativity. Here, the associativity of
multiplication and division is left to right. So, multiplication is performed first, then division
and finally addition. So, the above expression is evaluated in the order of * / and +. It is
evaluated as follows...
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Category Operator Associativity
Mathematical functions
The math.h header defines various mathematical functions and one macro. All
the functions available in this library take double as an argument and return
double as the result. Let us discuss some important functions one by one.
1. double ceil(double x): The C library function double ceil (double x) returns the
smallest integer value greater than or equal to x.
// C code to illustrate
// the use of ceil function.
#include <stdio.h>
#include <math.h>
int main ()
{
float val1, val2, val3, val4;
val1 = 1.6;
val2 = 1.2;
val3 = -2.8;
val4 = -2.3;
printf ("value1 = %.1lf\n", ceil(val1));
printf ("value2 = %.1lf\n", ceil(val2));
printf ("value3 = %.1lf\n", ceil(val3));
printf ("value4 = %.1lf\n", ceil(val4));
return(0);
}
Output:
value1 = 2.0
value2 = 2.0
value3 = -2.0
value4 = -2.0
#include <stdio.h>
int main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
return 0;
}
When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then the program proceeds and reads only a
single character and displays it as follows −
Output:
Enter a value : this is test
You entered: t
The gets() and puts() Functions
The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s
until either a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline to
stdout.
#include <stdio.h>
int main( )
{
char str[100];
printf( "Enter a value :");
gets( str );
printf( "\nYou entered: ");
puts( str );
return 0;
}
When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then the program proceeds and reads the
complete line till end, and displays it as follows −
Output:
Enter a value : this is test
You entered: this is test
#include <stdio.h>
int main( )
{
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);
return 0;
}
When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then program proceeds and reads the input and
displays it as follows –
Output:
Enter a value : seven 7
You entered: seven 7
Formatted Input and Output Functions:
C provides standard functions scanf() and printf(), to perform formatted inputs and outputs.
These functions accept a format specification string and a variable list as the parameters. The
format specification string is a character string that specifies the data type of each variable to
be input or output and the size or width of the I/O.
scanf()
The scanf() function is used for inputs formatted from standard inputs and provides numerous
conversion options for the printf() function.
Syntax:
scanf(format_specifiers, &data1, &data2,……); // & is address operator
The scanf() function reads and converts the characters from the standard input according to
the format specification string and stores the input in the memory slots represented by the
other arguments.
Example:
scanf(“%d %c”,&data1,&data2);
In the case of string data names, the data name is not prefixed with the &.
printf()
The printf() function is used for output formatted as the standard output according to a format
specification. The format specification string and the output data are the parameters of the
printf() function.
Syntax:
printf(format_specifiers, data1, data2,…..... );
Examples:
printf(“%d %c”, data1, data2);
The character specified after % is referred to as a conversion character because it allows a
data type to be converted to another type and printed.
Formatted Input and Output
The format specification string can contain text as well.
printf(“Number: %d\n”, data1);
printf(“%d\n%c”, data1, data2);
Example program:
#include <stdio.h>
void main()
{
int a;
printf(“Enter a value: ”);
scanf(“%d”,&a);
printf(“Entered Value= %d”,a);
}