First C Program: How To Compile and Run The C Program

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 56

First C Program

Before starting the abcd of C language, you need to learn how to write, compile and run the first c program.

To write the first c program, open the C console and write the following code:

#include <stdio.h> includes the standard input output library functions. The printf() function is defined in stdio.h
.

#include <conio.h> includes the console input output library functions. The getch() function is defined in conio.h
file.

void main() The main() function is the entry point of every program in c language. The void keyword specifies
that it returns no value.

printf() The printf() function is used to print data on the console.

getch() The getch() function asks for a single character. Until you press any key, it blocks the screen.

How to compile and run the c program


There are 2 ways to compile and run the c program, by menu and by shortcut.
By menu

Now click on the compile menu then compile sub menu to compile the c program.

Then click on the run menu then run sub menu to run the c program.

By shortcut

Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.

You can view the user screen any time by pressing the alt+f5 keys.

Now press Esc to return to the turbo c++ console.

clear screen by clrscr() function


If you run the c program many times, it will append the output in previous output. But, you can call clrscr()
function to clear the screen. So it will be better for you to call clrscr() function after the main method as given below:

Flow of C Program
The C program follows many steps in execution. To understand the flow of C program well, let us see a simple
program first.

File: simple.c

Let's try to understand the flow of above program by the figure given below.

Let's try to understand the flow of above program by the figure given below.
1) C program (source code) is sent to preprocessor first. The preprocessor is responsible to convert preprocessor
directives into their respective values. The preprocessor generates an expanded source code.

2) Expanded source code is sent to compiler which compiles the code and converts it into assembly code.

3) The assembly code is sent to assembler which assembles the code and converts it into object code. Now a
simple.obj file is generated.

4) The object code is sent to linker which links it to the library such as header files. Then it is converted into
executable code. A simple.exe file is generated.

5) The executable code is sent to loader which loads it into memory and then it is executed. After execution, output is
sent to console.

printf scanf in C
The printf() and scanf() functions are used for input and output in C language. Both functions are inbuilt library
functions, defined in stdio.h (header file).

printf() function

The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function

The scanf() function is used for input. It reads the input data from the console.

Program to print cube of given number

Let's see a simple example of c language that gets input from the user and prints the cube of the given number.
Output:

The scanf("%d",&number) statement reads integer number from the console and stores the given value in number
variable.

The printf("cube of number is:%d ",number*number*number) statement prints the cube of number on the
console.

Program to print sum of 2 numbers

Let's see a simple example of input and output in C language that prints addition of 2 numbers.
Output

Variables in C
A variable is a name of memory location. It is used to store data. Its value can be changed and it can be reused
many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

The example of declaring variable is given below:


Here, a, b, c are variables and int,float,char are data types.

We can also provide values while declaring the variables as given below:

Rules for defining variables


o A variable can have alphabets, digits and underscore.

o A variable name can start with alphabet and underscore only. It can't start with digit.

o No white space is allowed within variable name.

o A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

Inalid variable names:

Types of Variables in C
There are many types of variables in c:

1. local variable

2. global variable

3. static variable

4. automatic variable

5. external variable

Local Variable

A variable that is declared inside the function or block is called local variable.

It must be declared at the start of the block.


You must have to initialize the local variable before it is used.

Global Variable

A variable that is declared outside the function or block is called global variable. Any function can change the value of
the global variable. It is available to all the functions.

It must be declared at the start of the block.

Static Variable

A variable that is declared with static keyword is called static variable.

It retains its value between multiple function calls.

If you call this function many times, local variable will print the same value for each function call e.g, 11,11,11
and so on. But static variable will print the incremented value in each function call e.g. 11, 12, 13 and so on.

Automatic Variable

All variables in C that is declared inside the block, are automatic variables by default. By we can explicitly declare
automatic variable using auto keyword.
External Variable

We can share a variable in multiple C source files by using external variable. To declare a external variable, you need
to use extern keyword.

myfile.h

program1.c

Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character etc.

There are 4 types of data types in C language.


Basic Data Types
The basic data types are integer-based and floating-point based. C language supports both signed and unsigned
literals.

The memory size of basic data types may change according to 32 or 64 bit operating system.

Let's see the basic data types. Its size is given according to 32 bit architecture.
Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. There are only 32 reserved
words (keywords) in C language.

A list of 32 keywords in c language is given below:

C Operators
An operator is simply a symbol that is used to perform operations. There can be many types of operations like
arithmetic, logical, bitwise etc.

There are following types of operators to perform different types of operations in C language.

o Arithmetic Operators

o Relational Operators

o Shift Operators

o Logical Operators

o Bitwise Operators

o Ternary or Conditional Operators

o Assignment Operator

o Misc Operator

Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The associativity specifies the
operators direction to be evaluated, it may be left to right or right to left.

Let's understand the precedence by the example given below:

The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive operator).

The precedence and associativity of C operators is given below:


Comments in C
Comments in C language are used to provide information about lines of code. It is widely used for documenting code.
There are 2 types of comments in C language.

1. Single Line Comments

2. Multi Line Comments

Single Line Comments


Single line comments are represented by double slash \\. Let's see an example of single line comment in C.

Output:
Even you can place comment after statement. For example:

Mult Line Comments


Multi line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code but it can't be
nested. Syntax:

Let's see an example of multi line comment in C.

Output:

Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string
literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.
List of Escape Sequences in C

Escape Sequence Example

Output:
Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming"
etc.

There are different types of constants in C programming.

List of Constants in C

2 ways to define constant in C


There are two ways to define constant in C programming.

1. const keyword

2. #define preprocessor

1) C const keyword
The const keyword is used to define constant in C programming.

Now, the value of PI variable can't be changed.


Output:

If you try to change the the value of PI, it will render compile time error.

Output:

Compile Time Error: Cannot modify a const object

2) C #define preprocessor
The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive later.

C if else Statement
The if statement in C language is used to perform operation on the basis of condition. By using if-else statement, you
can perform operation either condition is true or false.

There are many ways to use if statement in C language:

o If statement

o If-else statement

o If else-if ladder

o Nested if

If Statement
The single if statement in C language is used to execute the code if condition is true. The syntax of if statement is
given below:
Flowchart of if statement in C

Let's see a simple example of c language if statement.


Output

If-else Statement
The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else
statement is given below:
Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.
Output

If else-if ladder Statement


The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is
given below:
Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.


Output

C Switch Statement
The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder
statement.

The syntax of switch statement in c language is given below:


Rules for switch statement in C language
1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case,
all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.
Flowchart of switch statement in C

Let's see a simple example of c language switch statement.


Output

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case
after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.
Output

C Loops
The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.
By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).

Types of C Loops
There are three types of loops in C language that is given below:

1. do while

2. while

3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed
whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be
executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given
before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:


do while loop in C
To execute a part of program or code several times, we can use do-while loop of C language. The code given between
the do and while block will be executed until condition is true.

In do while loop, statement is given before the condition, so statement or code will be executed at lease one time. In
other words, we can say it is executed 1 or more times.

It is better if you have to execute the code at least once.

do while loop syntax

The syntax of C language do-while loop is given below:

Flowchart of do while loop

do while example

There is given the simple program of c language do while loop where we are printing the table of 1.
Output

Program to print table for the given number using do while loop
Output

Infinitive do while loop

If you pass 1 as a expression in do while loop, it will run infinite number of times.

while loop in C
The while loop in C language is used to iterate the part of program or statements many times.

In while loop, condition is given before the statement. So it is different from the do while loop. It can execute the
statements 0 or more times.

When use while loop in C

The C language while loop should be used if number of iteration is uncertain or unknown.
Syntax of while loop in C language

The syntax of while loop in c language is given below:

Flowchart of while loop in C

Example of while loop in C language


Let's see the simple program of while loop that prints table of 1.
Output

Program to print table for the given number using while loop in C
Output

Infinitive while loop in C


If you pass 1 as a expression in while loop, it will run infinite number of times.
for loop in C
The for loop in C language is also used to iterate the statement or a part of the program several times, like while
and do-while loop.

But, we can initialize and increment or decrement the variable also at the time of checking the condition in for loop.

Unlike do while loop, the condition or expression in for loop is given before the statement, so it may execute the
statement 0 or more times.

When use for loop in C

For loop is better if number of iteration is known by the programmer.

Syntax of for loop in C

The syntax of for loop in c language is given below:


Flowchart of for loop in C

Example of for loop in C language


Let's see the simple program of for loop that prints table of 1.
Output
C Program : Print table for the given number using C for loop

Output
Infinitive for loop in C

If you don't initialize any variable, check condition and increment or decrement variable in for loop, it is known as
infinitive for loop.

In other words, if you place 2 semicolons in for loop, it is known as infinitive for loop.

C break statement
The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

In case of inner loops, it terminates the control of inner loop only.

There can be two usage of C break keyword:

1. With switch case

2. With loop

Syntax:

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.
Flowchart of break in c

Example of C break statement with loop

Output
As you can see on console output, loop from 1 to 10 is not printed after i==5.

C break statement with inner loop


In such case, it breaks only inner loop, but not outer loop.

Output

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and
j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

C continue statement
The continue statement in C language is used to continue the execution of loop (while, do while and for). It is used
with if condition within the loop.

In case of inner loops, it continues the control of inner loop only.


Syntax:

The jump statement can be while, do while and for loop.

Example of continue statement in c

Output

As you can see, 5 is not printed on the console because loop is continued at i==5.

C continue statement with inner loop


In such case, C continue statement continues only inner loop, but not outer loop.
Output

As you can see, 2 2 is not printed on the console because inner loop is continued at i==2 and j==2.

C goto statement
The goto statement is known as jump statement in C language. It is used to unconditionally jump to other label. It
transfers control to other parts of the program.

It is rarely used today because it makes program less readable and complex.

Syntax:
goto example
Let's see a simple example to use goto statement in C language.

Output:

Type Casting in C
Type casting allows us to convert one data type into other. In C language, we use cast operator for type casting which
is denoted by (type).

Syntax:

Without Type Casting:


With Type Casting:

Type Casting example


Let's see a simple example to cast int value into float.

Output:

functions in C
The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and
code reusability.

Advantage of functions in C
There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.


Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function,
you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.

Types of Functions
There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such as scanf(), printf(),
gets(), puts(), ceil(), floor() etc.

2. User-defined functions: are the functions which are created by the C programmer, so that he/she can use
it many times. It reduces complexity of a big program and optimizes the code.

Declaration of a function
The syntax of creating function in c language is given below:

Return Value
A C function may or may not return a value from the function. If you don't have to return any value from the function,
use void for the return type.

Let's see a simple example of C function that doesn't return any value from the function.

Example without return value:


If you want to return any value from the function, you need to use any data type such as int, long, char etc. The
return type depends on the value to be returned from the function.

Let's see a simple example of C function that returns int value from the function.

Example with return value:

In the above example, we have to return 10 as a value, so the return type is int. If you want to return floating-point
value (e.g. 10.2, 3.1, 54.5 etc), you need to use float as the return type of the method.

Now, you need to call the function, to get the value of the function.

Parameters in C Function
A c function may have 0 or more parameters. You can have any type of parameter in C program such as int, float,
char etc. The parameters are also known as formal arguments.

Example of a function that has 0 parameter:

Example of a function that has 1 parameter:

Example of a function that has 2 parameters:


Calling a function in C
If a function returns any value, you need to call function to get the value returned from the function. The syntax of
calling a function in c programming is given below:

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because
void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide arguments while calling the C function. It is also known as actual arguments.

Example to call a function:

Example of C function with no return statement


Let's see the simple program of C function that doesn't return any value from the function.
Output

Example of C function with return statement


Let's see the simple program of function in c language.

Output

Call by value and call by reference in C


There are two ways to pass value or data to function in C language: call by value and call by reference. Original value
is not modified in call by value but it is modified in call by reference.
Let's understand call by value and call by reference in c language one by one.

Call by value in C
In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory
location. If you change the value of function parameter, it is changed for the current function only. It will not change
the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:
Output

Call by reference in C
In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space.
Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:
Output

Difference between call by value and call by reference in c

Recursion in C
When function is called within the same function, it is known as recursion in C. The function which calls the same
function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail
recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.


Example of tail recursion in C
Let's see an example to print factorial number using tail recursion in C language.

Output

We can understand the above program of recursive method call by the figure given below:
Storage Classes in C
Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

o auto

o extern

o static

o register

1) auto
The auto keyword is applied to all local variables automatically. It is the default storage
class that is why it is known as automatic variable.
Output:

2) register
The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access
than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

3) static
The static variable is initialized only once and exists till the end of the program. It retains its value between multiple
functions call.

The static variable has the default value 0 which is provided by compiler.

Output:
4) extern
The extern variable is visible to all the programs. It is used if two or more files are sharing same variable or function.

You might also like