C Programming Notes
C Programming Notes
• At bell labs.
Page | 1
• To develop UNIX operating system.
Q) What is a C language?
Imperative Language.
A) REASONS:
Easy to learn.
Structured Language.
Platform Independent.
Operating Systems.
Language Compilers.
Language Interpreters.
Assemblers.
Text editors.
Data bases.
1
Structure of a C program
Program specification:
Page | 2 Program:
#include<stdio.h>
Pre processor commands
int main()
Main function
{
Printf function to display
printf(“Hello World \n”);
C tokens
C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.
...
C tokens are of six types. They are,
Identifiers are also known as Keywords in C. These are names given to Variables
,constants, Functions ,Structures and user defined data.
2
Continue For signed sizeof
Default Goto static while
Do If void switch
2. The first character of an identifier can only contain alphabet(a-z , A-Z) or underscore(_).
3. Identifiers are also case sensitive in C . For example Name and name are two different
identifiers.
5. No special character such as semicolon ,period ,whitespaces ,slash or comma are permitted
to be used as an identifier.
Variables :
variables name can consist of alphabets , digits and special symbols(@,$,#,* etc..,).
3
Initializing a variable:
Program Specification:
Program:
#include<stdio.h>
extern int c;
int main()
a=7;
c=a+b;
return 0;
Output:
sum is 21
4
Program specification:
Page | 5 write a C program to add two numbers without declaring the variables.
Program:
#include<stdio.h>
#include<conio.h>
int main()
int a,b,sum;
clrscr();
scanf(“%d”,&a);
scanf(“ %d“,&b);
sum=a+b;
Character set
Character:
Character set:
5
Fundamental raw material of any language and they are used to
Represent information.
Alphabets
Digits
Special characters
Escape sequence
Escape sequence
Digits----------- 0 1 2 3 4 5 6 7 8 9
Special characters:
Tilde ( ~)
Percent (%)
At (@)
Plus (+)
Underscore (_)
Minus (--)
Caret (^)
Equal to (=)
Ampersand (&)
Slash (/)
6
Parenthesis [ () ]
Asterisk (*)
Page | 7 Apostrophe (‘ ’)
Colon (:)
Brackets ([ ])
Quotations (“ “)
Exclamation (!)
Comma (,)
• \b blank space
• \t horizontaltab
• \v verticaltab
• \r carriage return
• \f form feed
• \n new line
• \\ Back slash
• \’ Single quote
• \? Question mark
• \0 Null
• \a Alarm (bell
7
Execution Character Set:
Page | 8
Null 000 \0 Null
Hexadecimal number \x
8
Identifiers and variables:
Variable is only kinds of Identifiers are function names , class , names , structure names etc..
Example :
int a;
int a
identifier variable
Program Specification:
Program:
#include <stdio.h>
int main()
int a;
printf("Enter an integer\n");
scanf("%d", &a);
return 0;
} output:
enter an integer:7
The integer is 7
9
constants
Page | 10
Constants:
C Constants is the most fundamental and essential part of the C programming language.
Constants in C are the fixed values that are used in a program, and its value remains the same during
the entire execution of the program.
Syntax:
Example:
#include<stdio.h>
int main()
int area;
area = SIDE*SIDE;
printf("The area of the square with side: %d is: %d sq. units" , SIDE, area);
} output:
Real constants:
The numbers containing fractional parts like 99.25 are called real or floating points
constant.
Integer constants:
Decimal Integer
10
Octal Integer
Hexadecimal Integer
Example:
Character string:
It simply contains a single character enclosed within ' and ' (a pair of single quote). It
is to be noted that the character '8' is not the same as 8. Character constants have a specific set of
integer values known as ASCII values (American Standard Code for Information Interchange).
String constants:
These are a sequence of characters enclosed in double quotes, and they may include letters,
digits, special characters, and blank spaces. It is again to be noted that "G" and 'G' are
different - because "G" represents a string as it is enclosed within a pair of double quotes
whereas 'G' represents a single character.
Example:
Data types
Qualifier:
Qualifiers are nothing but an addition of a prefix keyword with existing datatypes to add some extra
feature in a declared variable.
1. const
2. volatile
const in c
Example:
1.int x=5;
x is an integer variable which holds some data 5 and it can be changed to some other value
anywhere in the program.
11
x is a constant integer variable which holds some data 5 and it can not be changed to some other
value anywhere in the program.
volatile Qualifier in C
volatile keyword mostly used with the variable which can expect change from outside word
Page | 12
also i.e by external peripheral or some other thread.
volatile keyword tells the compiler not to optimise code related the variable usually, when
we know it can be changed from “outside”.
Syntax:
A compiler can not optimize the volatile variable i.e every time variable access from its real
memory location not from cache or somewhere else.
The volatile variable may also have const qualifier if someone doesn’t want to modify in a
program.But this variable can change from outside peripheral or thread e.g status register
Enumerator :
The enum keyword allows a programmer to create a named finite set of elements. The names of the
elements of the set are also defined by the programmer.
The sole purpose of the enumerator is to increase the clarity of the program.
There is no input or output mechanism for enumerators, so the program must have hard
coded statements which set the value of the enumerator.
Enumerator values are stored as integers, so integers can be used either in setting the value
of an enumerator or testing the value of an enumerator.
The declaration of an enum defines the elements of the enumerator. It is necessary define a
variable to use the enum.
By default the values stored for an enum variable is 0 through (N - 1), where the enumerator
has N elements. This can be changed, however
Program specification:
Program:
#include <stdio.h>
12
int main()
printf("Day %d",today+1);
return 0;
Output: Day 4
Enum variable takes only one value out of many possible values.
Program Specification:
Write a C program to demonstrate the enum variable takes only one value of many
possible values.
Program:
#include <stdio.h>
enum suit
int main()
card = club;
return 0;
Output
13
Operators
Arithmetic Operators:
Addition: The ‘+’ operator adds two operands. For example, x+y.
Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
Modulus: The ‘%’ operator returns the remainder whenFor example, x%y
Program:
#include <stdio.h>
int main()
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c);
c=a%b;
return 0;
14
output:
a+b = 13
a-b = 5
Page | 15 a*b = 36
a/b = 2
Relational operators:
• A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
== Equal to 5 == 3 returns 0
15
Program:
Program:
main()
int a = 21;
int b = 10;
int c ;
if( a == b )
else
if ( a < b )
else
if ( a > b )
16
printf("Line 3 - a is greater than b\n" );
else
Page | 17 {
a = 5;
b = 20;
if ( a <= b )
if ( b >= a )
Output:
17
Operator Description Example
= assigns values from right side operands to left side operand a=b
Page | 18
+= adds right operand to the left operand and assign the result to left a+=b is same as a=a+b
-= subtracts right operand from the left operand and assign the result to left a-=b is same as a=a-b
operand
*= mutiply left operand with the right operand and assign the result to left a*=b is same as a=a*b
operand
/= divides left operand with the right operand and assign the result to left a/=b is same as a=a/b
operand
%= calculate modulus using two operands and assign the result to left operand a%=b is same as a=a%b
Program Specification:
Program:
#include <stdio.h>
main()
int a = 21;
18
int c ;
c = a;
Page | 19 c += a;
c *= a;
c /= a;
c = 200;
c %= a;
Output:
Logical operators:
19
If c = 5 and d = 2 then,
Logial AND. True only if all
&& expression ((c == 5) && (d >
operands are true
5)) equals to 0.
Page | 20
If c = 5 and d = 2 then,
Logical OR. True only if either
|| expression ((c == 5) || (d >
one operand is true
5)) equals to 1.
Program Specification:
Program:
#include <stdio.h>
int main()
20
printf("(a == b) || (c < b) equals to %d \n", result);
return 0;
Output:
(a == b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0
21
(a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
Page | 22
Unary operators:
These two operators are unary operators, meaning they only operate on a single operator.
22
#include<stdio.h>
int main()
int b=-(a);
printf(“b=%d”,b);
return 0;
} Output:
b=-10
Ternary operator:
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true comparison, and the
third is the result upon a false comparison
Syntax :
Program:
#include <stdio.h>
main()
int a , b;
a = 10;
value of b is 30
value of b is 20
23
Bitwise operators:
Bitwise operators are used for manipulating a data at the bit level, also called as bit level
programming. Bit-level programming mainly consists of 0 and 1. They are used in numerical
computations to make the calculation process faster.
Page | 24
Operator Meaning
| Bitwise OR operator
The result of the computation of bitwise logical operators is shown in the table given below.
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
24
Page | 25
Program Specification:
Program:
#include <stdio.h>
int main(void)
int x = 1, y = 2;
return 0;
Output:
1&2=0
-----------------------------------
Program Specification:
25
write a program to demonstrate the bitwise | operator
Program:
#include <stdio.h>
int x = 1, y = 2;
int result = x | y;
return 0;
Output:
1|2=3
-----------------------------------
#include <stdio.h>
int main(void)
int x = 2, y = 7;
int result = x ^ y;
return 0;
Output:
26
2^7=5
Page | 27 Calculation of the bitwise XOR operation for the above code.
-----------------------------------
Shift Left
In the following example we have an integer which we will left shift 1 position.
Program Specification:
Program:
#include <stdio.h>
int main(void)
int x = 4;
//shift left
return 0;
Output:
27
Shift left x << 1 = 8
Calculation:
Page | 28 ----------------------------------
Shift Right
In the following example we have an integer which we will right shift 1 position.
Program Specification:
Program:
#include <stdio.h>
int main(void)
int x = 4;
return 0;
Output:
Calculation:
----------------------------------
28
Control Structures
Control Structures :
Page | 29
1. If
2. If else
3. Nested if else
4. Switch
If statement
• Syntax of if statement:
The statements inside the body of “if” only execute if the given condition returns true. If the
condition returns false then the statements inside “if” are skipped.
if (condition)
//Block of C statements here //These statements will only execute if the condition is true
Figure 1: if condition.
Program Specification:
Program:
#include <stdio.h>
int main()
29
{
int x = 20;
int y = 22;
Page | 30 if (x<y)
return 0;
Output:
If else statement:
If condition returns true then the statements inside the body of “if” are executed and the
statements inside body of “else” are skipped.
If condition returns false then the statements inside the body of “if” are skipped and the
statements in “else” are executed.
if(condition)
else
30
Page | 31
Program Specification:
Program:
#include <stdio.h>
int main()
int age;
scanf("%d",&age);
if(age >=18)
else
return 0;
31
Output:
When an if else statement is present inside the body of another “if” or “else” then
if(condition)
if(condition2)
else
else
#include <stdio.h>
int main()
32
printf("Input the value of var1:");
scanf("%d", &var1);
Page | 33 scanf("%d",&var2);
if (var1 != var2)
else
else
return 0;
Output:
33
Switch:
• The if..else..if ladder allows you to execute a block code among many alternatives. If you are
checking on the value of a single variable in if...else...if, it is better to use switchstatement.
• The switch statement is often faster than nested if...else (not always). Also, the syntax of
Page | 34
switch statement is cleaner and easy to understand
switch (n)
case constant1:
case constant2:
default:
#include <stdio.h>
int main()
int num=2;
switch(num+2)
case 1:
case 2:
34
printf("Case2: Value is: %d", num);
case 3:
Page | 35 default:
return 0;
Output:
35
Looping statements
Loop :
loops are used in programming to repeat a block of code until specific condition is met.
Page | 36
Loops are of 3 types:
For
While
Do while
For loop:
Syntax:
// code
The test expression is evaluated if the test expression is true ,codes inside the body of for
loop is executed and the update expression is updated.
36
Program Specification:
Program to calculate the sum of first n natural numbers by using for loop
Page | 37 Program:
#include <stdio.h>
int main()
scanf("%d", &num);
for(count = 1; count <= num; ++count) // for loop terminates when n is less than count
return 0;
} Output:
Sum = 15
While loop :
Syntax:
while (testExpression)
//codes
37
DESCRIPTION:
• If the test expression is true (nonzero), codes inside the body of while loop is executed. The
test expression is evaluated again. The process goes on until the test expression is false.
Page | 38
• When the test expression is false, the while loop is terminated.
Program specification:
Program:
#include<stdio.h>
int main()
int n,a,r,s=0;
scanf("%d",&n);
a=n;
while(n>0)
38
r=n%10;
s=s*10+r;
n=n/10;
Page | 39 }
Do...while loop:
The do..while loop is similar to the while loop with one important difference. The body
of do...while loop is executed once, before checking the test expression. Hence, the do...while loop is
executed at least once.
Syntax:
do
// codes
} while (testExpression);
• The code block (loop body) inside the braces is executed once.
• Then, the test expression is evaluated. If the test expression is true, the loop body is
executed again. This process goes on until the test expression is evaluated to 0 (false).
• When the test expression is false (nonzero), the do...while loop is terminated. Flow chart of
39
Program specification:
Program:
#include <stdio.h>
int main()
do
scanf("%lf", &number);
sum = sum+number;
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
Output
Enter a number: 0
Sum = 4.70
40
Break:
1. It is used to come out of the loop instantly. When a break statement is encountered inside a
loop, the control directly comes out of loop and the loop gets terminated. It is used with if
statement, whenever used inside loop.
Page | 41
2. This can also be used in switch case control structure. Whenever it is encountered in switch-
case block, the control comes out of the switch-case(see the example below)
#include <stdio.h>
int main()
int i =0;
while(i<=10)
i++;
if (i==4)
break;
return 0;
Output:
41
Continue:
Continue statement are used to skips the rest of the current iteration in a loop
Page | 42 and returns to the top of the loop. The continue statement works like a shortcut
#include <stdio.h>
int main()
int j;
if (j==4)
/* This print statement would not execute for the * loop iteration where j ==4 because in that case
* this statement would be skipped. */
return 0;
Output:
01235678
Function calls
Function call by passing values:
call by value the actual arguments are copied to the formal arguments, hence any
operation performed by function on arguments doesn’t affect actual parameters.
42
Program Specification:
Program:
var = var+1;
return var;
int main()
int num1=20;
return 0;
Output:
Program Specification:
43
Program:
#include <stdio.h>
/*Function Prototype*/
int main()
swapx(&a, &b);
return 0;
int t;
t = *x;
*x = *y;
*y = t;
Output:
Arrays:
Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more useful
to think of an array as a collection of variables of the same type.
44
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Declaring an array:
Page | 45
int data[100];
The size and type of arrays cannot be changed after its declaration.
1. One-dimensional arrays
2. Two-dimensional arrays
data_type array_name[array_size];
For example,
float mark[5];
Suppose you declared an array mark as above. The first element is mark[0], second element
is mark[1] and so on.
If the size of an array is n, to access the last element, (n-1) index is used. In this example, mark[4]
Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be 2124d,
address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.
45
or
Page | 46
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Program Specification:
Write a C program to find the average of n (n < 10) numbers using arrays
Program:
#include <stdio.h>
int main()
printf("Enter n: ");
scanf("%d", &n);
scanf("%d", &marks[i]);
sum += marks[i];
average = sum/n;
46
printf("Average = %d", average); return 0;
} Output
Enter n: 5
Enter number2: 35
Enter number3: 38
Enter number4: 31
An array of arrays is known as 2D array. The two dimensional (2D) array in C programming is also
known as matrix. A matrix can be represented as a table of rows and columns.
Program specification:
Program:
#include<stdio.h>
int main()
{ /* 2D array declaration*/
int i, j;
for(j=0;j<3;j++)
scanf("%d", &disp[i][j]);
47
printf("Two Dimensional array elements:\n");
Page | 48 for(j=0;j<3;j++)
if(j==2)
printf("\n");
return 0;
Output:
456
48
Pointers
Pointers:
Pointers in C language is a variable that stores/points the address of another variable. A Pointer in C
Page | 49 is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to
any of the data type such as int, float, char, double, short etc.
Where, * is used to denote that “p” is pointer variable and not a normal variable.
• Normal variable stores the value whereas pointer variable stores the address of the variable.
• * symbol is used to get the value of the variable that the pointer is pointing to.
• Two pointers can be subtracted to know how many elements are available between these
two pointers.
Program specification:
Program:
#include <stdio.h>
int main()
int *ptr, q;
q = 50;
49
ptr = &q;
printf("%d", *ptr);
Page | 50 return 0;
OUTPUT:
50
• Array is a collection of variables belongings to the same data type. We can store group of
data of same data type in an array.
Program specification :
Program:
#include <stdio.h>
int main()
return 0;
50
Output:
Sum=9
Page | 51
Strings
Strings:
For example:
"c string“
c s t r i n g \0
• Before you can work with strings, you need to declare them first. Since string is an array of
characters. You declare strings in a similar way like you do with arrays.
• If you don't know what arrays are, we recommend you to check C arrays.
char s[5];
51
c[0] c[1] c[2] c[3] c[4]
a b c d \0
Program specification:
Program:
#include <stdio.h>
int main()
char name[20];
scanf("%s", name);
return 0;
Output:
You can use gets() function to read a line of string. And, you can use puts() to display the string.
Program Specification:
52
Program:
#include <stdio.h>
int main()
Page | 53 {
char name[30];
printf("Name: ");
return 0;
output :
C strlen()
C strlen() Prototype
The function takes a single argument, i.e, the string variable whose length is to be found,
and returns the length of the string passed.
53
Char c[ ]={‘p’,’r’,’o’,’g’,’r’,’a’,’m’,’\0’}
Temp=strlen(c);
The, temp will b e equal to 7 bacause , null character ‘\0’ is not counted
Page | 54
p r o g r a m \0
Program Specification :
Program:
#include <stdio.h>
#include <string.h>
int main()
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
char c[20];
gets(c);
return 0;
Output
Length of string a = 7
Length of string b = 7
54
Length of string c = 6
Page | 55 C strcpy()
The strcpy() function copies the string to the another character array.
A. The strcpy() function copies the string pointed by source (including the null character) to the
character array destination.
Program specification:
Program:
#include <stdio.h>
#include <string.h>
int main()
char str2[10];
char str3[10];
strcpy(str2, str1);
strcpy(str3, "well");
puts(str2);
puts(str3);
return 0;
Output
55
Awesome
well
C strcmp()
Page | 56 The strcmp() function compares two strings and returns 0 if both strings are identical.
C strcmp() Prototype
If the first character of two strings are equal, next character of two strings are compared.
This continues until the corresponding characters of two strings are different or a null
character '\0' is reached.
Negative if the ASCII value of first unmatched character is less than second.
positive integer if the ASCII value of first unmatched character is greater than second
56
Program Specification:
Page | 57 Program:
#include <stdio.h>
#include <string.h>
int main()
return 0;
Output
strcmp(str1, str2) = 1
strcmp(str1, str3) = 0
Explanation:
The ASCII value of 'c' is 99 and the ASCII value of 'C' is 67. Hence, when strings str1 and str2 are
compared, the return value is 32
C strcat()
C strcat() Prototype
57
It takes two arguments, i.e, two strings or character arrays, and stores the resultant
concatenated string in the first string specified in the argument.
Program specification:
Page | 58
Write a C program to demostarte the working of strcat().
Program:
#include <stdio.h>
#include <string.h>
int main()
char str1[] = "This is ", str2[] = "programiz.com"; //concatenates str1 and str2 and resultant string is
stored in str1.
strcat(str1,str2);
puts(str1);
puts(str2);
return 0;
Output
This is programiz.com
programiz.com
58
Page | 59
59
Page | 60
60
Page | 61
61
Page | 62
62