Programming in C1
Programming in C1
• C is general purpose programming language. You can generate different kind of software such as
billing system, games, utilities, word processor, etc.
• C is the structured programming language. It uses structured statements such as while, for, etc.
• C is a standardized programming language. For example ANSI (American National Standards
Institute) C is a standard programming language.
• The C language can run in any computer system. It is system independent.
• It has the small range of data types of detailed data manipulation statements with power data
definition methods.
• It is a language of few words such that the programmer can remember them easily.
• It is a highly efficient programming language since C compilers are generally able to translate
source code into efficient machine instructions.
Features of C Programming Language
• The C language was successful in developing UNIX operating systems.
It has special reasons to become very popular in the programming
world.
• Portability: This refers to the ability of a program to run in different
environments. Some programming language compilers such as
FORTRAN and Pascal could be used in those computers containing the
same compilers. Since, C languages have different compilers almost in
all systems, a C is termed as the most portable language.
• Flexibility: The C language combines the convenience and portable
nature of high-level language with the flexible nature.
• Wide acceptability: The C language is known to the entire world. The
language is suitable for projects at the system level and at the
application level.
• Get Started With C
To start using C, you need two things:
• A text editor, like Notepad, to write C code
• A compiler, like GCC, to translate the C code into a language that the computer will
understand
• There are many text editors and compilers to choose from. In this tutorial, we will
use an IDE (see below).
C Install IDE:
• An IDE (Integrated Development Environment) is used to edit AND compile the
code.
• Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free,
and they can be used to both edit and debug C code.
•
• Whitespace in C
• A line containing only whitespace, possibly with a comment, is known as a blank line,
and a C compiler totally ignores it.
• Whitespace is the term used in C to describe blanks, tabs, newline characters and
comments. Whitespace separates one part of a statement from another and enables
the compiler to identify where one element in a statement, such as int, ends and the
next element begins. Therefore, in the following statement −
• int age;
• there must be at least one whitespace character (usually a space) between int and
age for the compiler to be able to distinguish them. On the other hand, in the following
statement −
• fruit = apples + oranges; // get the total fruit
• no whitespace characters are necessary between fruit and =, or between = and
apples, although you are free to include some if you wish to increase readability.
• Data Types in C
In C programming, data types are declarations for
variables. This determines the type and size of data
associated with variables.
For example,
int myVar;
Here, myVar is a variable of int (integer) type. The size of
int is 4 bytes.
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: The type specifier void indicates that no value is available.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and
(e) Function types.
• In the C programming language, data types 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 the storage and how the bit pattern stored is
interpreted.
• In C, there are several data types that you can use, including:
• int: This is used to store integer values. For example, int x = 10;
• float: This is used to store decimal values with single precision. For example, float y =
3.14;
• double: This is used to store decimal values with double precision. For example,
double z = 2.71828;
• char: This is used to store a single character. For example, char c = 'A';
• void: This is used to represent the absence of a type. For example, void function() { ...
}
• There are many other data types that you can use in C, but these are some of the
most common ones.
C Variables
• Variables are containers for storing data values.
• In C, there are different types of variables (defined with different
keywords), for example:
• Create a variable called myNum of type int and assign the value 15 to it:
Note: If you assign a new value to an existing variable, it will overwrite the previous
• int myNum = 15; value:
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
• Constants
• If you don't want others (or yourself) to override existing
variable values, use the const keyword (this will declare the
variable as "constant", which means unchangeable and read-
only):
• Example
• const int myNum = 15; // myNum will always be 15
• myNum = 10; // error: assignment of read-only variable 'myNum'
• You should always declare the variable as constant when you have
values that are unlikely to change:
• const int minutesPerHour = 60;
• const float PI = 3.14;
• Operators
• Operators are used to perform operations on variables and
values.
• In the example below, we use the + operator to add together
two values:
• intmyNum = 100 + 50;
• C divides the operators into the following groups:
• Arithmetic operators Assignment operators
• Comparison operators Logical operators
• Bitwise operators
• Assignment Operators
• Assignment operators are used to assign values to variables.
• In the example below, we use the assignment operator (=) to
assign the value 10 to a variable called x:
• example program:
• #include <stdio.h>
int main() {
int x = 10;
x += 5;
printf("%d", x);
return 0;
}
o/p: 15
Example programs:
• WAP to print your name:
#include <stdio.h>
int main()
{
printf("My Name is YourName!");
return 0;
}
Data types and format
specifier example #include <stdio.h>
int main() {
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
return 0;
}
• write a c program to input your name and display it to the user.
#include <stdio.h>
void main()
{
char name[30];
printf("Input Your name: ");
scanf("%s", name);
printf("%s",name);
}
• Booleans
Very often, in programming, you will need a data type that can only have one of
two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, C has a bool data type, which is known as booleans.
Booleans represent values that are either true or false.
In C, the bool type is not a built-in data type, like int or char.
It was introduced in C99, and you must import the following header file to use it:
we must have to use : #include <stdbool.h> for booleans
Example
// Create boolean variables
bool isProgrammingFun = true;
bool isFishTasty = false;
// Return boolean values
printf("%d", isProgrammingFun); // Returns 1 (true)
printf("%d", isFishTasty); // Returns 0 (false)
Exercise:
• int () {
("Hello World!");
• return 0;
• }
• Comments in C are written with special characters. Insert the
missing parts:
Fill in the missing parts to create three variables of the same type,
using a comma-separated list:
• Syntax
if (condition) {
// block of code to be executed if the condition is true
}
classwork:
test two values to find out if 20 is greater than 18. If the
condition is true, print some text:
#include <stdio.h> We can also test variables:
In the example above we use two variables, x and y, to test whether x is greater than
y (using the > operator). As x is 20, and y is 18, and we know that 20 is greater than
18, we print to the screen that "x is greater than y".
example program
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
classwork:
WAP to print if given value is less then, equal to, greater then by using if statement.
(by using multiple if statement.)
Check if a character is a vowel or consonant?
int time = 22; In the example above, time (22) is greater than 10, so the first condition is
if (time < 10) { false. The next condition, in the else if statement, is also false, so we
move on to the else condition since condition1 and condition2 is both false
printf("Good morning."); - and print to the screen "Good evening".
} else if (time < 20) {
However, if the time was 14, our program would print "Good day."
printf("Good day.");
Another Example
} else { This example shows how you can use if..else to find out if a
printf("Good evening."); number is positive or negative:
} Example
// Outputs "Good evening." int myNum = - 10; // Is this a positive or negative number?
if (myNum > 0) {
printf("The value is a positive number.");
} else if (myNum < 0) {
printf("The value is a negative number.");
} else {
printf("The value is 0.");
}
Switch Case Statememt
• Switch Statement
• Instead of writing many if..else statements, you can use the
switch statement.
• The switch statement selects one of many code blocks to be
executed:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Following program illustrates the use of switch:
#include <stdio.h>
int main() {
int num = 8;
switch (num) {
case 7:
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break;
}
return 0;
} The Output = Value is 8
For example, we consider the following program which defaults:
#include <stdio.h>
int main() {
int language = 10;
switch (language) {
case 1:
printf("C#\n");
break;
case 2:
printf("C\n");
break;
case 3:
printf("C++\n");
break;
default:
printf("Other programming language\n");}}
Output: Other programming
language
Looping
• The computer has the ability to peform a set of instructions
repetedly. This involves repeating some portion of program
either for a specified number of iteams or till a given condition
is satisfied. this repetitive operation is done by a loop control
statement.
• Looping(or iteration or repetition) is an operation that repeats the execution of statement until a
certain condition is satisfied.
• There are three loops.:
for statement
while ststememt
do.while statement
• for loop
THe for loop is the most commenly used statement in c this loop
consist of three expression
Syntax ::
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1: is executed (one time) before the execution of the code block.
Statement 2: defines the condition for executing the code block.
Statement 3: is executed (every time) after the code block has been
executed.
Example:
#include<stdio.h>
int i;
for (i = 0; i < 5; i++) {
printf("%d\n", i);
}
Example explained:
Statement 1: sets a variable before the loop starts (int i = 0).
Statement 2: defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3: increases a value (i++) each time the code block in the loop has been
executed.
Example 1: for loop
#include <stdio.h>
// Print numbers from 1 to 10
void main()
#include <stdio.h> {
int i;
int main() { printf("The first 10 natural numbers are:\
int i; n");
for (i = 1; i < 11; ++i) for (i=1;i<=10;i++)
{
{
printf("%d ",i);
printf("%d ", i); }
} printf("\n");
return 0; }
}
#include <stdio.h>
int main()
{
int j, sum = 0;
printf("The first 10 natural number is :\n");
for (j = 1; j <= 10; j++)
{
sum = sum + j;
printf("%d ",j);
}
printf("\nThe Sum is : %d\n", sum);
}
#include <stdio.h>
int main() {
int i;
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}
return 0;
}
Nested Loops
The "inner loop" will be executed one time for each iteration of the
"outer loop":
while loop:
The second type of loop statement is while loop. while loop first
checks whether the initial condition is true of false and finding it to
be true, it will either the loop and execute the statement.
syntax:
while (condition) {
statement_1;
........
statement_n;
increment/decrement;
}
Example When the above code is compiled and
executed, it produces the following
#include<stdio.h> result −
Syntax
do {
// code block to be executed
}
while (condition);
• The example below uses a do/while loop. The loop will always
be executed at least once, even if the condition is false, because
the code block is executed before the condition is tested:
Example
#include<stdio.h>
int i = 0;
do {
printf("%d\n", i);
i++;
}
while (i < 5);
Assignment
• write a program to read the principal rate of interest and number
of years and find the simple intreast and amount.
• A C program to print Fibonacci series i.e:0 1 1 2 3 5 8... upto nth
term.
• write a program to check weather given number is prime or not.
#include <stdio.h>
int main() {
float principal, rate, time, simple_interest, amount;
return 0;
}
fibonacci series
#include <stdio.h>
int main() {
int n, i, t1 = 0, t2 = 1, next_term;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci series: ");
for (i = 1; i <= n; i++) {
printf("%d,", t1);
next_term = t1 + t2;
t1 = t2;
t2 = next_term;
}
return 0;
}
• #include<stdio.h>
• int main()
• {
• int i,fact=1,number;
• printf("Enter a number: ");
• scanf("%d",&number);
• for(i=1;i<=number;i++){
• fact=fact*i;
• }
• printf("Factorial of %d is: %d",number,fact);
• return 0;
• }
•Array and string.
(VVI)
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.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the
elements and the number of elements required by an array as
follows −
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be
an integer constant greater than zero and type can be any valid C
data type. For example, to declare a 10-element array called
balance of type double, use this statement −
Example:
int balance[10];
Here balance is a variable array which is sufficient to hold up to 10 int numbers.
Declaration of C Array
We can declare an array in the c language in the following way.
data_type array_name[array_size];
Here, int is the data_type, marks are the array_name, and 5 is the
array_size.
Initialization of C Array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Access the Elements of an Array:
To access an array element, refer to its index number.
Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
#include <stdio.h>
int main() {
// Declare an array of four integers:
int myNumbers[4]; int myNumebrs[4]: {25, 50, 75, 100}
// Add elements to it
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
printf("%d\n", myNumbers[0]); Using this method, you should know the size of the array, in order
return 0; for the program to store enough memory.
}
You are not able to change the size of the array after creation.
#include <stdio.h>
int main() {
int myNumbers[] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++) {
printf("%d\n", myNumbers[i]);
}
return 0;
}
Write a program in C to store elements in an array and print it.
// Program to take 5 values from the user
and store them in an array
// Print the elements stored in the array
#include <stdio.h>
int main() {
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}
• Classwork:
Write a C program to ask ten numbers from the user and
display them using arrey.
The first dimension represents the number of rows [2], while the
second dimension represents the number of columns [3]. The
values are placed in row-order, and can be visualized like this:
• Access the Elements of a 2D Array
• To access an element of a two-dimensional array, you must
specify the index number of both the row and column.
• This statement accesses the value of the element in the first row
(0) and third column (2) of the matrix array.
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
printf("%d", matrix[0][2]);
return 0;
}
The following example will change the value of the element in the
first row (0) and first column (0):
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;
return 0;
}
Loop Through a 2D Array
To loop through a multi-dimensional array, you need one loop
for each of the array's dimensions.
The following example outputs all elements in the matrix array:
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}
return 0;
}
Output : ???????????
#include <stdio.h>
int main()
{
int salary[50],i,n,count=0;
return 0;
}
String:(character Array)
We can represent character easily by char data type whereas the
string is a group of characters that can only be represented by
character array. To represent a character, we use char data type.
declaration:
char X;
we can only store only one character at a time which is always
enclosed by single quote.
initialization:
char x = ‘a’
The following declaration and initialization create a string consisting of the
word "Hello". To hold the null character at the end of the array, the size of the
character array containing the string is one more than the number of
characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above
statement as follows −
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
C Reverse String: strrev()
The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev()
function.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output:
}
void main(){
char str1[] = "First";
char str2[20];
strcpy(str2,str1);
printf("%s%s",str1,str2);
printf("%d",(str1!=str2)); // (!= relational operator if = 0 if !
= 1)
printf("%d",strcmp(str1,str2));
C String Length: strlen() function
The strlen() function returns the length of the given string. It doesn't count null character '\0'.
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'h', 'e', 'l', 'l', 'o', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output: 5
#include <stdio.h>
#include <string.h>
int main () {
Output: ????
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
Functions
• Functions are the self-contained program that contains
several block of statement which performs the defined task.
In C language, we can create one or more functions
according to the requirements.
[Note: &age return memory address, %u denotes unsigned integer generally used for large
positive numbers i.e address of age in this case. Memory address may vary with
computers. Same program may give different memory location but should give same value]
Importance of Pointer.
While using several numbers of functions in C program, every
functions should be called and value should be passed locally.
However, using pointer variable, which can access the address
or memory location and points whatever the address (memory
location) contains.
Pointer declaration
Data_type *variable_name
• Syntax:
• datatype *pointer_varible;
For eg:
int *a;
char *b;
float *c;
• Simple program example of pointers in C
#include<stdio.h>
int main()
Output of the above program is
{
Address of age is 65676
int age=16, *a;
Value of age is 16
a = &age;
printf("Address of age is %p\n”, (void*)a);
printf(“Value of age is %d\n”, *a);
return 0;
}
[Note: %p format specifier is used for printing the address to which pointer
points in C]
• Explanation of above program
• In C, the asterisk (*) is used to declare a variable as a pointer, and also to dereference a
pointer variable, which means accessing the value stored in the memory location pointed to by
the pointer.
• In the code, ‘a’ is declared as a pointer to an integer by using the * in the declaration int *a;.
This means that a can hold the address of an integer variable.
• Later in the code, ‘a’ is assigned the address of the age variable by using the & operator to get
the address of ‘age’: ‘a = &age;’. This means that a now points to the memory location where
age is stored.
• Finally, to print the value of age, the code uses the dereference operator * to access the value
stored in the memory location pointed to by ‘a’: ‘printf("Value of age is %d", *a);’.
• So, the ‘*a’ in the code is used to access the value of the variable pointed to by ‘a’. Without the
* operator, ‘a’ would simply represent the memory address of the variable, not its value.
Recursive functions: (V.Imp)
data_type member_2;
.
data_type member_n;
}structure_variables;
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to hold the details of a student which
consists of 4 data fields, namely name, age, branch and gender. These fields are
called structure elements or members.
Each member can have different datatype, like in this case, name is an array of
char type and age is of int type etc. Student is the name of the structure and is
called as the structure tag.
Let's see the example to define a structure for an entity employee in c.
Struct Keyword
struct employee tag, struct-tag
{ int id;
char name[10]; Member
float salary;
};
• How to create a structure?
• ‘struct’ keyword is used to create a structure. Following is an
example.
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
C Structure example
Let's see a simple example of structure in C language.
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=01;
strcpy(e1.name, "Sudip kattel"); //copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
int main( )
{
//store first employee information
e1.id=01;
strcpy(e1.name, "Sudip Kattel");//copying string into char array
e1.salary=56000;
We use the struct statement to define a We use the union keyword to define a union.
structure.
Every member is assigned a unique memory All the data members share a memory location.
location.
Change in the value of one data member does Change in the value of one data member
not affect other data members in the structure. affects the value of other data members.
You can initialize multiple members at a time. You can initialize only the first member at once.
A structure can store multiple values of the A union stores one value at a time for all of its
different members. members
A structure’s total size is the sum of the size of A union’s total size is the size of the largest
every data member. data member.
Users can access or retrieve any member at a You can access or retrieve only one member at
time. a time.
Example program::
struct Item {
char name[50];
int quantity;
float rate;
};
int main() {
struct Item item1;
return 0;
Write a function simple(p,t,r) in C to compute Simple Interest.
#include<stdio.h>
int main()
{
int p,r,t,int_amt;
printf("Input principle, Rate of interest & time to find simple interest: \n");
scanf("%d%d%d",&p,&r,&t);
int_amt=(p*r*t)/100;
printf("Simple interest = %d",int_amt);
return 0;
}
File Handling in C
In programming, we may require some specific input data to be
generated several numbers of times.Sometimes, it is not enough
to only display the data on the console. The data to be displayed
maybe very large, and only a limited amount of data can be
displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again
and again.However, if we need to do so, we may store it onto the
local file system which is volatile and can be
accessed every time. Here, comes the need of file handling in C.
• File handling in C enables us to create, update, read, and delete
the files stored on the local file
• system through our C program. The following operations can be
performed on a file.
• Text Files.
• A Text file contains only the text information like alphabets ,digits
and special symbols. The ASCII code of these characters are
stored in these files.It uses only 7 bits allowing 8 bit to be zero.
• Binary Files
• A binary file is a file that uses all 8 bits of a byte for storing the
information. It is the form which can be interpreted and
understood by the computer.
• The only difference between the text file and binary file is the
data contain in text file can be recognized by the word processor
while binary file data can’t be recognized by a word processor.
• EOF