Unit I
Introduction to C Programming
Constants are the fixed values that never change during the execution of a program. Following are the various types of constants:
Integer constants
An integer constant is nothing but a value consisting of digits or numbers. These values never change during the execution of a program. Integer constants can be octal, decimal and hexadecimal.
Example, 111, 1234
Above are the valid decimal constants.
2. Octal constant contains digits from 0-7, and these types of constants are always preceded by 0.
Example, 012, 065
Above are the valid decimal constants.
3. Hexadecimal constant contains a digit from 0-9 as well as characters from A-F. Hexadecimal constants are always preceded by 0X.
Example, 0X2, 0Xbcd
Above are the valid hexadecimal constants.
The octal and hexadecimal integer constants are very rarely used in programming with 'C'.
Character constants
A character constant contains only a single character enclosed within a single quote (''). We can also represent character constant by providing ASCII value of it.
Example, 'A', '9'
Above are the examples of valid character constants.
String constants
A string constant contains a sequence of characters enclosed within double quotes ("").
Example, "Hello", "Programming"
These are the examples of valid string constants.
Real Constants
Like integer constants that always contains an integer value. 'C' also provides real constants that contain a decimal point or a fraction value. The real constants are also called as floating point constants. The real constant contains a decimal point and a fractional value.
Example, 202.15, 300.00
These are the valid real constants in 'C'.
A real constant can also be written as,
Mantissa e Exponent
For example, to declare a value that does not change like the classic circle constant PI, there are two ways to declare this constant
#include <stdio.h>
int main() {
const double PI = 3.14;
printf("%f", PI);
//PI++; // This will generate an error as constants cannot be changed
return 0;}
2. By using the #define pre-processor directive which doesn't use memory for storage and without putting a semicolon character at the end of that statement
#include <stdio.h>
#define PI 3.14
int main() {
printf("%f", PI);
return 0;}
2. Explain bitwise operators.
These operators are used to work on the each bits of data. These operators can work on the binary data. If the data is non binary then computer first of all convert it into binary form and then perform the operation. Following are the list of logical operator in C language. To understand the operation assume variable A contains value 10 and variable contains value 5. So the binary values of
A = 0000 1010 and
B = 0000 0101
Sr. No. | Operator | Description | Example |
1. | & | This is bitwise AND | Result of (A&B) is 0000 0000 |
2. | | | This is bitwise OR | Result of (A|B) is 0000 1111 |
3. | ^ | This is bitwise Exclusive | Result of (A^B) is 0000 1111 |
4. | << | This is used to shift bit on left side | Result of (A<<B) is |
5. | >> | This is used to shift bit on right side | Result of (A>>B) is |
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter two numbers");
scanf("%d %d",&a,&b);
printf("\n Result of bitwise and operator of %d and %d is %d",a,b,a&b);
printf("\n Result of bitwise or operator of %d and %d is %d",a,b,a|b);
printf("\n Result of bitwise exclusive operator of %d and %d is %d",a,b,a^b);
printf("\n Result of bitwise left shift operator of %d and %d is %d",a,b,a<<b);
printf("\n Result of bitwise right shift operator of %d and %d is %d",a,b,a>>b);
getch();
}
Output:
Output:
Enter two numbers
5
3
Result of bitwise and operator of 5 and 3 is 1
Result of bitwise or operator of 5 and 3 is 7
Result of bitwise exclusive operator of 5 and 3 is 6
Result of bitwise left shift operator of 5 and 3 is 40
Result of bitwise right shift operator of 5 and 3 is 0
3. Explain Decision Control
Decision making structures require that the programmer specifies 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.
Show below is the general form of a typical decision making structure found in most of the programming languages −
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
C programming language provides the following types of decision making statements.
Sr.No. | Statement & Description |
1 | An if statement consists of a boolean expression followed by one or more statements. |
2 | An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. |
3 | You can use one if or else if statement inside another if or else if statement(s). |
4 | A switch statement allows a variable to be tested for equality against a list of values. |
5 | You can use one switch statement inside another switch statement(s). |
The ? : Operator
We have covered conditional operator ? : in the previous chapter which can be used to replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this −
4. What is an array? Explain
Array is a data structure which stores the collection of similar types of element in consecutive memory locations. Indexing of array always start with ‘0’ where as non-graphical variable ‘\0’ indicates the end of array. Syntax for declaring array is
data type array name[Maximum size];
Example:
Sr. No. | Instructions | Description |
#include<stdio.h> | Header file included | |
2. | #include<conio.h> | Header file included |
3. | void main() | Execution of program begins |
4. | { | Memory is allocated for variable i,n and array a |
5. | int i,n,a[10]; | |
6. | clrscr(); | Clear the output of previous screen |
7. | printf("enter a number"); | Print “enter a number” |
8. | scanf("%d",&n); | Input value is stored at the addres of variable n |
9. | for(i=0;i<=10;i++) | For loop started from value of i=0 to i=10 |
10. | { | Compound statement(scope of for loop starts) |
11. | a[i]=n*i; | Result of multiplication of n and I is stored at the ith location of array ieas i=0 so it is stores at first location. |
12. | printf("\n %d",a[i]); | Value of ith location of the array is printed |
13. | } | Compound statement(scope of for loop ends) |
14. | printf("\n first element in array is %d",a[0]); | Value of first element of the array is printed |
15. | printf("\n fifth element in array is %d",a[4]); | Value of fifth element of the array is printed |
16. | printf("\n tenth element in array is %d",a[9]); | Value of tenth element of the array is printed |
17. | getch(); | Used to hold the output screen |
18. | } | Indicates end of scope of main function |
5. Explain functions and its types.
Similar to other languages C language also provides the facility of function. Function is the block of code which is used to perform a specific task. In c language the complete program is composed of function.
Functions are useful to divide c programs into smaller modules. Programmer can invoked these modules anywhere inside c program for any number of times.
Functions are used to increase readability of the code. Size of program can be reduce by using functions. By using function, programmer can divide complex tasks into smaller manageable tasks and test them independently before using them together.
Functions of C language are defined with the type of function. The type of functions indicates the data type of value which will return by function. In order to use function in the program, initially programmer have to inform compiler about the function. This is also called as defining a function.
In C programme all the function definition present outside the main function. All function need to be declared and defined before use. Function declaration requires function name, argument list, and return type.
The syntax for defining a function is as follows.
Return Type Function name (Argument list)
{
Statement 1;
Statement 2;
…………...
Statement n;
}
In the above syntax, return type indicates the data type of value return by the function. If return type is not written then by default “int” data type is consider.
Function name can be any alphanumeric value which is satisfying the rules used to define variable name and can be as long as 31 characters.
The argument list is a formal list that includes data type and variable name combination. Each argument must be separated by comma.
The body of the function describes what the function is supposed to do. The body starts with an opening curly bracket “{“ and ends with a closing curly bracket “}”. Everything between these two curly brackets belongs to the function.
There are two types of functions in c language.
1. Library Functions
A function which is predefined in c language is called library function. Library function is also called as built in function of C language. The definition of library function is stored in respective header file. Library functions are used to perform dedicated operation like taking input from user, displaying output, string handling operation, etc. Library functions are readily available and programmer can directly use it without writing any extra code. For example, printf () and scanf () are library function and their definition is stored in stdio header file.
2. User Defined Functions
User define function is the block of code written by programmer to perform a particular task. As compiler doesn’t have any idea about the user define function so programmer has to define and declare these functions inside the program body. Programmer can define these function outside the main function but declaration of user define function should present in main function only. Whenever compiler executes function call (function declaration) then compiler shift the flow of program execution to the definition part of user define function.
Example
#include <stdio.h>
#include<conio.h>
int add (int x, int y)
{
int sum;
sum = x + y;
return (sum);
}
main ()
{
int a,b,c;
a = 15;
b = 25;
c = add(a,b);
printf ("\n Addition is %d ", c);
}
Output:
Addition is 40
There are two ways to pass the parameters to the function
1. Parameter Passing by value
In this mechanism, the value of the parameter is passed while calling the function.
2. Parameter Passing by reference
In this mechanism, the address of the parameter is passed while calling the function.
6. What is String Manipulations?
Strings are also called as the array of character.
Char string name[size of string];
Char is the data type, user can give any name to the string by following all the rules of defining name of variable. Size of the string is the number of alphabet user wants to store in string.
Example:
Sr. No. | Instructions | Description |
#include<stdio.h> | Header file included | |
2. | #include<conio.h> | Header file included |
3. | void main() | Execution of program begins |
4. | { | String is declare with name str and size of storing 10 alphbates |
5. | char str[10]; | |
6. | clrscr(); | Clear the output of previous screen |
7. | printf("enter a string"); | Print “enter a string” |
8. | scanf("%s",&str); | Entered string is stored at address of str |
9. | printf("\n user entered string is %s",str); | Print: user entered string is (string entered by user) |
10. | getch(); | Used to hold the output screen |
11. | } | Indicates end of scope of main function |
Following are the list of string manipulation function
Sr. No. | String Function | Purpose |
strcat | use to concatenate (append) one string to another | |
2. | strcmp | use to compare one string with another. (Note: The comparison is case sensitive) |
3. | strchr
| use to locate the first occurrence of a particular character in a given string |
4. | strcpy | use to copy one string to another. |
5. | strlen | use to find the length of a string in bytes, |
7. What is Structure?
It is the user define data type. With the help of structure user can define different types of variables under the shelter of one common name. Syntax for defining structure is as follows
struct structure_name
{
structure element1;
structure element1;
structure element1;
:
:
:…..
};
Example:
#include<stdio.h>
#include<conio.h>
struct student
{
char name[100];
int roll_no;
};
void main()
{
struct student s;
printf("Enter name of student");
scanf("%s",&s.name);
printf("\n Enter roll number");
scanf("%d",&s.roll_no);
printf("\n Roll number of %s is %d",s.name,s.roll_no);
getch();
}
Output:
Enter name of student
Raushan
Enter roll number
92
Roll number of Raushan is 92
8. Difference between structure and union
Structure | Union |
1. Size of structure is summation of all elements of structure. | 1. Size of union is size of largest element is union. |
2. ‘struct’ keyword is used to define structure. | 2. ‘union’ keyword is used to define union |
3. All members are initialized with its own memory. | 3. Only first member is initialize. |
4. Size of structure is more than union. | 4. Size of union is less than structure. |
In the above syntax union is a keyword, which is used to define the union. union name can be anything according to the rules of defining names of variable. Within curly brackets user can define the several variables. Size of union is the size of largest element of the union. User can access the elements of union by creating the object of the union.
9. Explain Enumeration
Dictionary meaning of enumeration is the ‘act of counting’. Enumeration is the user define data type which is defined by using keyword ‘enum’. Enumeration consists of integer values which are carried out by symbolic names. Enum variable are easy to compare as compiler assign integer values to the enum variable. Enumeration allows user to assign numbers to the names. Enumeration is helpful to increase readability of the code. By default indexing of enumeration starts with ‘0’. Enumeration is used to create numbered list. Syntax for the declaration of enumeration is as follows
enum identifier {enumerator list};
enum identifier object-name;
In the above syntax ‘enum’ is the keyword which is followed by identifier. Identifier is used to define enumeration type but it is not directly used. Enumerator list contains the variables which are used under the tag name identifier. In the enumerator list first name has the value zero, next name has value one and so on, until the explicit values are specified.
Second line in the above syntax represents the definition of enumeration. In the definition of enumeration user need to create the object of enumeration identifier. With the help of this object user can user the variables declare in enumerated list.
Example:
#include<stdio.h> a
#include<conio.h>
void main()
{
enum Friends{Debu,Rani,Tini,Chintu,Pinki};
clrscr();
printf("\n Debu: %d",Debu);
printf("\n Rani: %d",Rani);
printf("\n Tini: %d",Tini);
printf("\n Chintu: %d",Chintu);
printf("\n Pinki: %d",Pinki);
getch();
}
Output:
Debu: 0
Rani: 1
Tini: 2
Chintu: 3
Pinki: 4
10. How to append a file?
While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file.
In order to append a new line to the existing file, open the file in append mode.
Program to append file
Let's first see what should be the step-by-step procedure to compare two integers−
START
Step 1 → Take two integer variables, say A & B
Step 2 → Assign values to variables
Step 3 → Compare variables if A is greater than B
Step 4 → If true print A is greater than B
Step 5 → If false print A is not greater than B
STOP
Flow Diagram
We can draw a flow diagram for this program as given below −
Pseudocode
Let's now see the pseudocode of this algorithm −
procedure compare(A, B)
IF A is greater than B
DISPLAY "A is greater than B"
ELSE
DISPLAY "A is not greater than B"
END IF
end procedure
Implementation
Assuming we have file with name file_append.txt with this content −
This text was already there in the file.
Now, we shall see the actual implementation of the program −
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
char *filename = "file_append.txt";
char *content = "This text is appeneded later to the file, using C programming.";
/* open for writing */
fp = fopen(filename, "r");
printf("\nContents of %s -\n\n", filename);
while ((ch = fgetc(fp) )!= EOF)
{
printf ("%c", ch);
}
fclose(fp);
fp = fopen(filename, "a");
/* Write content to file */
fprintf(fp, "%s\n", content);
fclose(fp);
fp = fopen(filename, "r");
printf("\nContents of %s -\n", filename);
while ((ch = fgetc(fp) )!= EOF)
{
printf ("%c", ch);
}
fclose(fp);
return 0;
}
Output
Output of this program should be −
Contents of file_append.txt -
This text was already there in the file.
Appending content to file_append.txt...
Content of file_append.txt after 'append' operation is -
This text was already there in the file.
This text is appended later to the file, using C programming.