0% found this document useful (0 votes)
181 views17 pages

C Language Notes

The document provides an introduction to the C programming language. It discusses why C was created, how it has influenced other languages like C++ and Java, and some of the basics of C including data types, variables, constants, and comments. It also includes instructions on setting up a C compiler and writing a simple "Hello World" program as an example to get started with writing C code.

Uploaded by

ankitadubey
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
181 views17 pages

C Language Notes

The document provides an introduction to the C programming language. It discusses why C was created, how it has influenced other languages like C++ and Java, and some of the basics of C including data types, variables, constants, and comments. It also includes instructions on setting up a C compiler and writing a simple "Hello World" program as an example to get started with writing C code.

Uploaded by

ankitadubey
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 17

1.

Introduction

What is C and why learn it


C was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories. C was originally designed for writing system software but
today a variety of software programs are written in C. C can be used on
many different types of computers but is mostly used with the UNIX
operating system.

It is a good idea to learn C because it has been around for a long time
which means there is a lot of information available on it. Quite a few other
programming languages such as C++ and Java are also based on C which
means you will be able to learn them more easily in the future.

What you will need


This tutorial is written for both Windows and UNIX/Linux users. All the code in the examples
has been tested and works the same on both operating systems.

If you are using Windows then you need to download borland C++ compiler from
http://www.borland.com/cbuilder/cppcomp. Once you have downloaded and installed it you need
to add "C:\Borland\BCC55\Bin" to your path. To add it to your path in Windows 95/98/ME you
need to add the line "PATH=C:\Borland\BCC55\Bin" to c:\autoexec.bat using notepad. If you
are using Windows NT/2000/XP then you need to open the control panel and then double click
on "system". Click on the "Advanced" tab and then click "Environment Variables". Select the
item called "Path" and then click "Edit". Add ";C:\Borland\BCC55\Bin" to "Variable value" in
the dialog box that appears and then click Ok and close everything.

All Windows users will now have to create a text file called "bcc32.cfg" in
"C:\Borland\BCC55\Bin" and save the following lines of text in it:

-I"C:\Borland\BCC55\include"
-L"C:\Borland\BCC55\lib"

If you are using UNIX/Linux then you will most probably have a C compiler installed called
GCC. To check if you have it installed type "cc" at the command prompt. If for some reason you
don't have it then you can download it from http://gcc.gnu.org.

 
Your first program
The first thing we must do is open a text editor. Windows users can use Notepad and
UNIX/Linux users can use emacs or vi. Now type the following lines of code and then I will
explain it. Make sure that you type it exactly as I have or else you will have problems. Also don't
be scared if you think it is too complicated because it is all very easy once you understand it.

Code:
#include<stdio.h>

int main()
{
printf("Hello World\n");
return 0;
}

#include<stdio.h>
This includes a file called stdio.h which lets us use certain commands. stdio is short for Standard
Input/Output which means it has commands for input like reading from the keyboard and output
like printing things on the screen.

int main()
int is what is called the return value which will be explained in a while. main is the name of the
point where the program starts and the brackets are there for a reason that you will learn in the
future but they have to be there.

{}
The 2 curly brackets are used to group all the commands together so it is known that the
commands belong to main. These curly brackets are used very often in C to group things
together.

printf("Hello World\n");
This is the printf command and it prints text on the screen. The data that is to be printed is put
inside brackets. You will also notice that the words are inside inverted commas because they are
what is called a string. Each letter is called a character and a series of characters that is grouped
together is called a string. Strings must always be put between inverted commas. The \n is called
an escape sequence and represents a newline character and is used because when you press
ENTER it doesn't insert a new line character but instead takes you onto the next line in the text
editor. You have to put a semi-colon after every command to show that it is the end of the
command.

Table of commonly used escape sequences:

\a Audible signal
\b Backspace
\t Tab
\n Newline
\v Vertical tab
\f New page\Clear screen
\r Carriage return

return 0;
The int in int main() is short for integer which is another word for number. We need to use the
return command to return the value 0 to the operating system to tell it that there were no errors
while the program was running. Notice that it is a command so it also has to have a semi-colon
after it.

Save the text file as hello.c and if you are using Notepad make sure you select All Files from the
save dialog or else you won't be able to compile your program.

You now need to open a command prompt. If you are using Windows then click Start->Run and
type "command" and Click Ok. If you are using UNIX/Linux and are not using a graphical user
interface then you will have to exit the text editor.

Using the command prompt, change to the directory that you saved your file in. Windows users
must then type:

C:\>bcc32 hello.c

UNIX/Linux users must type:

$cc hello.c -ohello

The -o is for the output file name. If you leave out the -o then the file name a.out is used.

This will compile your C program. If you made any mistakes then it will tell you which line you
made it on and you will have to type out the code again and this time make sure you do it exactly
as I did it. If you did everything right then you will not see any error messages and your program
will have been compiled into an exe. You can now run this program by typing "hello.exe" for
Windows and "./hello" for UNIX/Linux.

You should now see the words "Hello World" printed on the screen. Congratulations! You have
just made your first program in C.

Indentation
You will see that the printf and return commands have been indented or moved away from the
left side. This is used to make the code more readable. It seems like a stupid thing to do because
it just wastes time but when you start writing longer, more complex programs, you will
understand why indentation is needed.
Using comments
Comments are a way of explaining what a program does. They are put after // or between /* */.
Comments are ignored by the compiler and are used by you and other people to understand your
code. You should always put a comment at the top of a program that tells you what the program
does because one day if you come back and look at a program you might not be able to
understand what it does but the comment will tell you. You can also use comments in between
your code to explain a piece of code that is very complex. Here is an example of how to
comment the Hello World program:

Code:
/* Author: w3schools.in
Date: 2009-09-05
Description:
Writes the words "Hello World" on the screen */

#include<stdio.h>

int main()
{
printf("Hello World\n"); //prints "Hello World"
return 0;
}
2.Data types
Data types in any of the language means that what are the various type of data the variables can
have in that particular language. Whenever a variable is declared it becomes necessary to define
data type that what will be the type of data that variable can hold. The various general types of
data are:

1. Number type data


2. Character type data
3. String type data
4. Boolean type data

Number type data again include to main classes, they can be either integers that is whole number
or they can be the real number that is decimal part.
C language also supports the wide range of data type like

Char used to represent the character type data


(1 byte memory is allocated, Range is -128  to  + 127).
Int to represent the integer type data.
(2 byte memory is allocated  Range is – 32768 to 32767).
Float Used to represent the real type data.
(4 byte memory is allocated Range is 3.4 x 10^-38 to 3.4 x
Long Used to represent the integer type data having long range.
(8 byte memory is allocated Range is -).
Double Used to represent the float type data in the long range.
(16 byte memory is allocated Range is – 1.7c 308 to 1.7c 308).
Long Used to represent the float type data in even more long range
Double then the double. (32 byte memory is allocated , 1.7c 4932 +
1.7c 4932).

The data type can also be of signed & unsigned. If the unsigned notation is used then the range
becomes just double. The long, signed & unsigned notations are also called qualities.
3.Variables and constants

 What are variables?


Variables in C are memory locations that are given names and can be assigned values. We use
variables to store data in memory for later use. There are 2 basic kinds of variables in C which
are numeric and character.

Numeric variables
Numeric variables can either be integer values or they can be Real values. Integer values are
whole numbers without a fraction part or decimal point in them. Real numbers can have a
decimal point in them.

Character variables
Character variables are letters of the alphabet as well as all characters on the ASCII chart and
even the numbers 0 - 9. Characters must always be put between single quotes. A number put
between single quotes is not the same thing as a number without them.

What are constants?


The difference between variables and constants is that variables can change their value at any
time but constants can never change their value. Constants can be useful for items such as Pi or
the charge on an electron. Using constants can stop you from changing the value of an item by
mistake.

Declaring variables
To declare a variable we first put the type of variable and then give the variable a name. The
following is a table of the names of the types of variables as well as their ranges:

Name Type Range


int Numeric - Integer -32 768 to 32 767
short Numeric - Integer -32 768 to 32 767
long Numeric - Integer -2 147 483 648 to 2 147 483 647
float Numeric - Real 1.2 X 10-38 to 3.4 X 1038
doubl Numeric - Real 2.2 X 10-308 to 1.8 X 10308
e
char Character All ASCII characters
You can name a variable anything you like as long as it includes only letters, numbers or
underscores and does not start with a number. It is a good idea to keep your variable names less
than 32 characters long to save time on typing them out and for compiler compatibility reasons.
Variables must always be declared at the top before any other commands are used. Now let's
declare an integer variable called a and a character variable called b.

Code:
int main()
{
int a;
char b;
return 0;
}

You can declare more than one variable at the same time in the following way:

Code:
int main()
{
int a,b,c;
return 0;
}

To declare a constant all you have to do it put the word const in front of a normal variable
declaration and make assign a value to it.

Code:
int main()
{
const float pi = 3.14;
return 0;
}

Signed and unsigned variables


The difference between signed and unsigned variables is that signed variables can be either
negative or positive but unsigned variables can only be positive. By using an unsigned variable
you can increase the maximum positive range. When you declare a variable in the normal way it
is automatically a signed variable. To declare an unsigned variable you just put the word
unsigned before your variable declaration or signed for a signed variable although there is no
reason to declare a variable as signed since they already are.

Code:
int main()
{
unsigned int a;
signed int b;
return 0;
}
Using variables in calculations
To assign a value to a variable you use the equals sign.

Code:
int main()
{
int a;
char b;
a = 3;
b = "H";
return 0;
}

There are a few different operators that can be used when performing calculations which are
listed in the following table:

Operato Operation
r
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus(Remainder of integer division)

To perform a calculation you need to have a variable to put the answer into. You can also use
both variables and normal numbers in calculations.

Code:
int main()
{
int a,b;
a = 5;
b = a + 3;
a = a - 3;
return 0;
}

Reading and printing variables


You can read a variable from the keyboard with the scanf command and print a variable with the
printf command.

Code:
#include<stdio.h>

int main()
{
int a;
scanf("%d",&a);
a = a * 2;
printf("The answer is %d",a);
return 0;
}

Format specifiers
when ever a variable has to be inputted then some registers the values from the input unit and
transfers it to their respective memory locations. Hence it is required to specify the format of the
incoming data so that there is ease to send the corresponding no. of registers because if the
format is not known to us then it becomes very difficult for the processor of decide the number
of registers to send and in this case the maximum possible registers are send and in general case
it causes the memory loss. Hence this format specifiers are used to save the memory. Some of
the common format specifiers used in C are

Format specifier purpose


%d integer data types
%f float
%u unsigned integers
%s string
%c char
%ld long integer
4.Decisions

 The if statement
So far we have only learnt how to make programs that do one thing after the other without being
able to make decisions. The if statement can be used to test conditions so that we can alter the
flow of a program. The following example has the basic structure of an if statement:

Code:
#include<stdio.h>

int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
pass = "y";
return 0;
}

In the above example the user enters the mark they got and then the if statement is used to test if
the mark is greater than 40. Make sure you remember to always put the conditions of the if
statement in brackets. If the mark is greater than 40 then it is a pass.

Now we must also test if the user has failed. We could do it by adding another if statement but
there is a better way which is to use the else statement that goes with the if statement.

Code:
#include<stdio.h>

int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
pass = "y";
else
pass = "n";
return 0;
}

The if statement first tests if a condition is true and then executes an instruction and the else is
for when the result of the condition is false.
If you want to execute more than 1 instruction in  if statements then you have to put them
between curly brackets. The curly brackets are used to group commands together.

Code:
#include<stdio.h>

int main()
{
int mark;
char pass;
scanf("%d",&mark);
if (mark > 40)
{
pass = "y";
printf("You passed");
}
else
{
pass = "n";
printf("You failed");
}
return 0;
}

It is possible to test 2 or more conditions at once using the AND (&&) operator. You can use the
OR (||) operator to test if 1 of 2 conditions is true. The NOT (!) operator makes a true result of a
test false and vice versa.

Code:
#include<stdio.h>

int main()
{
int a,b;
scanf("%d",&a);
scanf("%d",&b);
if (a > 0 && b > 0)
printf("Both numbers are positive\n");
if (a == 0 || b == 0)
printf("At least one of the numbers = 0\n");
if (!(a > 0) && !(b > 0))
printf("Both numbers are negative\n");
return 0;

Boolean operators
In the above examples we used > and < which are called Boolean operators. They are called
Boolean operators because they give you either true or false when you use them to test a
condition. The following is table of all the Boolean operators in c:
== Equal
!= Not equal
>  Greater than
>= Greater than or equal
<  Less than
<= Less than or equal
&& And
|| Or
! Not

The switch statement


The switch statement is just like an if statement but it has many conditions and the commands for
those conditions in only 1 statement. It is runs faster than an if statement. In a switch statement
you first choose the variable to be tested and then you give each of the conditions and the
commands for the conditions. You can also put in a default if none of the conditions are equal to
the value of the variable. If you use more than one command then you need to remember to
group them between curly brackets.

Code:

#include<stdio.h>

int main()
{
char fruit;
printf("Which one is your favourite fruit:\n");
printf("a) Apples\n");
printf("b) Bananas\n");
printf("c) Cherries\n");
scanf("%c",&fruit);
switch (fruit)
{
case "a":
printf("You like apples\n");
break;
case "b":
printf("You like bananas\n");
break;
case "c":
printf("You like cherries\n");
break;
default:
printf("You entered an invalid choice\n");
}
return 0;
}
5.Loops

 The various control structures in C


Control structures are the statements which controls the overall any program. Control structures
are basically of three types –

o Sequence statements
o Iterative statements
o Selection statements

Sequence Statements : All the State in a program except the iterative & statements.
They are generally the individual statements which performs the task of input, output,
assignment declaration etc.

Iterative Statement are those repeated execution of a particular set of instructions


desired number of times. These statements are generally called loops for their execution
nature.  Loops are basically of two types –

 Count Loot  
 Event Loop

Count Loop :- Those loops whose no. of times of execution is known


prior to the execution of loop are termed as count loops i.e they care
countable in nature.

Event Loop :- Those loop whose execution any certain event are called
event before the execution.
A loop basically consists of a loop variable which has for the completion
of any iterative   statement, i.e a loop consists of three main statements:-

(1) Initialization (2) Condition (3) Incrementation

        Initialization is used to start any loop i.e. it gives some initial value to the
loop variable. Which defines that from which value the loop has to get start.
Condition is provided to give the final value to the loop variable so that how
many times the loop has to get executed. For reaching the loop variable from
initial value to the final value there should be some sort of increamentation and
that provided by the third component statement of loop and that is incrementation.
        If in any loop the incramentation or the final value is not provided then the
loop becomes infinite. If the initialization is not done then the garbage value of
the loop variable becomes its initial value.

        In C language the iterative statements (loops) can be implemented in the


three loops and they are

The for loop


Syntax of For Loop –
for (initialization; condition; incrementation)
{ ----------------- body of loop -------------
}

        For Loop will perform its execution until the condition remains satisfied. If
the body of the loop consists of more than one statement then these statements are
made compound by placing the open and closed curly brackets around the body of
the loop. For loop is a count loop. The initialization condition and
increamentation may be done in the same statement. For loop will not execute at
least once also if the condition is false at the first time itself.

With loops you also have to put commands between curly brackets if there is
more than one of them. Here is the solution to the problem that we had with the
24 printf commands:

Code:
#include

int main()
{
int i;
for (i = 1;i <= 24;i++)
printf("H\n");
return 0;

A for loop is made up of 3 parts inside its brackets which are separated by semi-
colons. The first part initializes the loop variable. The loop variable controls and
counts the number of times a loop runs. In the example the loop variable is called
i and is initialized to 1. The second part of the for loop is the condition a loop
must meet to keep running. In the example the loop will run while i is less than or
equal to 24 or in other words it will run 24 times. The third part is the loop
variable incremental. In the example i++ has been used which is the same as
saying i = i + 1. This is called incrementing. Each time the loop runs i has 1 added
to it. It is also possible to use i-- to subtract 1 from a variable in which case it's
called decrementing.
The while loop
Syntax –
        Initialization;
        While (condition)
        {
        Body of loop;
        Incrementation;
        }

In this loop, initialisation, condition and incrementation is done in the three


different statements. This loops is count as well as event loop. In case of while
loops the body of the loop will consist of more than one statements because each
time one statement will be of incrementation. Hence the open and closed curly
brackets are required.

Code:
#include<stdio.h>

int main()
{
int i,times;
scanf("%d",&times);
i = 0;
while (i <= times)
{
i++;
printf("%d\n",i);
}
return 0;

The do while loop


The third loop statement available in C is do-while statement syntax :-
Initialization;
Do
{
Body of loop;
Increamentation;
}
While (condition);

In this loop the condition is checked at the end, and for this reason this loop will
execute at least once whether the condition may be satisfying and unsatisfying.

Code:
#include<stdio.h>

int main()
{
int i,times;
scanf("%d",&times);
i = 0;
do
{
i++;
printf("%d\n",i);
}
while (i <= times);
return 0;

Break and continue


You can exit out of a loop at any time using the break statement. This is useful
when you want a loop to stop running because a condition has been met other
than the loop end condition.

Code:
#include<stdio.h>

int main()
{
int i;
while (i < 10)
{
i++;
if (i == 5)
break;
}
return 0;

You can use continue to skip the rest of the current loop and start from the top
again while incrementing the loop variable again. The following example will
never print "Hello" because of the continue.

Code:
#include<stdio.h>

int main()
{
int i;
while (i < 10)
{
i++;
continue;
printf("Hello\n");
}
return 0;
}

You might also like