C PROGRAMMING FOR BEGINNERS
C TUTORIAL
Learn and practice these tutorials in the given order.
CONTENT
Tap on below links to jump on that section.
Unit-1.Learn Basics with C
1.1]Turbo C++ installation.
1.2]First C Program
1.3]Keywords in C
Unit-2.Desigion control in C
Unit-3.Loops in C
Unit-4.Loop control statements in C
4.3]Goto statementUnit-5.Array Tutorials in C
How to install Turbo C++: Compile and Run a C Program
First you need to undestand that computer (Machine) can only understand Machine language (Stream of 0s and 1s). In order to convert your C program source code to Machine code, you need to compile it. Compiler is the one, which converts source code to Machine code. In simple words you can say that a compiler converts human readable code to a machine readable format.
Installing Turbo C- Guide
Step 1- Download Turbo C.
Step 2-Locate TC.exe file and open it. You can find it at location C:\TC\BIN
Step 3-Go to File>new and then start writing code.as shown below
#include<stdio.h> int main() { printf("hello World!"); return 0; }
Step 5-Now compile program using Alt+F9 or Comple>Compile.
Step 6-Now Run program using ctrl+F9 or Run>Run.
Step 7-To see output press alt+F5 or Output>Output.
C Program structure- First C program
Below i am giving you example of C program and more detailed information.
First C program
/*Demo Program written by sushil*/ #include<stdio.h> int main() { int num; printf("Enter your age: "); scanf("%d", &num); return 0; }
Output-
Enter your age:25
Lets understand this Program:
Comment- Comments are start with "/*" and end with "*/". comments are not manadatory but it is good to write comments for practice, it improves readability of code .A program can have any number of comments. comments are of two types
i) Single line comment- it is given by "//comment",
ii)Double or more line comment-start with "/*" and end with "*/".
Include Section-
While writing program we use several keywords,statements and functions like printf(),scanf() etc. The header file or include file contains the definitions of these funtions needs to be included in program. In above program we have used "stdio.h" is one of them which is used for reading and displaying data on terminal.
Main() function-
It is the starting point of all the C programs. The execution of C source code begins with this function.
Display statements-
In above program we have used printf function which is used to display data. Everything into that double quotes of printf function are get printed on console as it is.You can also use format specifiers such as %d, %c, %p to display the values of the variables and pointers using printf.
Take input from the user-
scanf function is used to take the input from the user. When you run this program, it waits for a user input (age) and once user enters the age, it does the processing of rest of the statements based on the age input by user.
About main () Function in C program
The main () function should be present in all C programs as your program won’t begin without this function.
Return type of main () function- The return type for main () function should always be int.
Why it has a return type and what’s the need of it?
The compiler should know whether your program compiled successfully or it has failed. In order to know this it checks the return value of function main (). If return value is 0 then it means that the program is successful otherwise it assumes that there is a problem, this is why we have a return 0 statement at the end of the main function.
Keywords in C
There are 32 keywords in C which have their predefined meaning and cannot be used as a variable name. These words are also known as “reserved words”. It is good practice to avoid using these keywords as variable name.
Keywords are as given below-
auto | break | char | case |
const | int | long | signed |
continue | default | do | short |
register | return | sizeof | static |
struct | switch | unsigned | void |
typedef | union | while | volatile |
double | else | float | for |
enum | extern | goto | if |
Basic usage of these keywords
int, float, char, double, long – These are the data types and used during variable declaration.break – Used with any loop OR switch case.
continue – It is generally used with for, while and dowhile loops.
union – It is a collection of variables, which shares the same memory location and memory storage.
struct, typedef – Both of these keywords used in structures.Grouping of data into single record.
enum – Set of constants.
void – One of the return type.
goto – Used for redirecting the flow of execution.
for, while, do – types of loop structures in C.
auto, signed, const, extern, register, unsigned – defines a variable.
return – This keyword is used for returning a value.
If statement in C programming
Syntax
The syntax of an 'if' statement in C programming language is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the 'if' statement (after the closing curly brace) will be executed.
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.
Flow Diagram
Example
#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;
}
Output
a is less than 20; value of a is : 10
if..Else statement in C
Syntax
The if statement may have an optional else block. The syntax of the if..else statement is:
if (test expression) {
// statements to be executed if the test expression is true
}
else {
// statements to be executed if the test expression is false
}
How if...else statement works?
If the test expression is evaluated to true,- statements inside the body of if are executed.
- statements inside the body of else are skipped from execution.
- statements inside the body of else are executed
- statements inside the body of if are skipped from execution.
Example
#include<stdio.h> #include<conio.h> void main () { int no; clrscr(); printf("Enter number-"); scanf("%d",&no); /* check the boolean condition using if statement */ if( no%2 == 0) { /* if condition is true then print the following */ printf("%d is even\n",no); } else { printf("%d is odd\n",no); } getch(); }
Output
Enter number- 44 44 is even
C if...else Ladder
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The if...else ladder allows you to check between multiple test expressions and execute different statements.
Syntax
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}
Example
#include<stdio.h> #include<conio.h> void main() { clrscr(); int n1,n2; //variable declaration printf("Enter two integers-"); scanf("%d%d",&n1,&n2); //check if two integers are equal if(n1==n2) { printf("integer 1=intiger 2"); } //check if number 1 is greater than number 2 else if(n1>n2) { printf("Result %d > %d",n1,n2); } //check number 1 is less than number 2 else { printf("Result %d < %d",n1,n2); } getch(); }
Output
Enter two integers-20 10 Result 20 > 10
C switch statement
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is much easier to read and write.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
How does the switch statement work?
The expression is evaluated once and compared with the values of each case label.- If there is a match, the corresponding statements after the matching label are executed. For example, if the value of the expression is equal to constant2, statements after case constant2: are executed until break is encountered.
- If there is no match, the default statements are executed.
- The default clause inside the switch statement is optional.
- If we do not use break, all statements after the matching label are executed.
Switch sattement Flowchart
Example
#include<conio.h> #include<stdio.h> void main() { int choice; int n1,n2; clrscr(); printf("Enter two numbers-"); scanf("%d %d",&n1,&n2); printf("\nEnter Your choice-"); printf("\n1]add \n2]sub \n3]mult\n"); scanf("%d",&choice); switch(choice) { case 1:printf("addtion is- %d",n1+n2); break; case 2:printf("substraction is- %d",n1-n2);break; case 3:printf("multiplication is- %d",n1*n2);break; default: printf("entered choice is wrong"); break; } getch(); }
Output
Enter two numbers-34 22 Enter Your choice- 1]add 2]sub 3]mult 1 addtion is- 56
for Loop
The syntax of the for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}
How for loop works?
- The initialization statement is executed only once.
- Then, the test expression is evaluated. If the test expression is evaluated to false, the for loop is terminated.
- However, if the test expression is evaluated to true, statements inside the body of for loop are executed, and the update expression is updated.
- Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false, the loop terminates.
Flow Chart
Example 1
//Print numbers from 1 to 10 #include<stdio.h> #include<conio.h> void main() { int i; for (i = 1; i < 11; ++i) { printf("%d ", i); } getch(); }
Output
1 2 3 4 5 6 7 8 9 10
Example 2
// Program to calculate the sum of first n natural numbers // Positive integers 1,2,3...n are known as natural numbers #include<stdio.h> #include<conio.h> void main() { int num, count, sum = 0; printf("Enter a positive integer: "); scanf("%d", &num); // for loop terminates when num is less than count for(count = 1; count <= num; ++count) { sum += count; } printf("Sum = %d", sum); getch(); }
Output
Enter a positive integer: 10 Sum = 55
Explanation
The value entered by the user is stored in the variable num. Suppose, the user entered 10.
The count is initialized to 1 and the test expression is evaluated. Since the test expression count<=num (1 less than or equal to 10) is true, the body of for loop is executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and the count will equal to 2. Again, the test expression is evaluated. Since 2 is also less than 10, the test expression is evaluated to true and the body of for loop is executed. Now, the sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11, the test expression is evaluated to 0 (false), and the loop terminates.
Then, the value of sum is printed on the screen.
While loop & do...while
while loop
The syntax of the while loop is:
while (testExpression)
{
// statements inside the body of the loop
}
How while loop works?
- The while loop evaluates the test expression inside the parenthesis ().
- If the test expression is true, statements inside the body of while loop are executed. Then, the test expression is evaluated again.
- The process goes on until the test expression is evaluated to false.
- If the test expression is false, the loop terminates (ends).
Flowchart for while loop
Example 1
// Print numbers from 1 to 5
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
Output
1 2 3 4 5
Explanation
- Here, we have initialized i to 1.
- When i is 1, the test expression i <= 5 is true. Hence, the body of the while loop is executed. This prints 1 on the screen and the value of i is increased to 2.
- Now, i is 2, the test expression i <= 5 is again true. The body of the while loop is executed again. This prints 2 on the screen and the value of i is increased to 3.
- This process goes on until i becomes 6. When i is 6, the test expression i <= 5 will be false and the loop terminates.
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 at least once. Only then, the test expression is evaluated.
The syntax of the do...while loop is:
do
{
// statements inside the body of the loop
}
while (testExpression);
How do...while loop works?
- The body of do...while loop is executed once. Only then, the test expression is evaluated.
- If the test expression is true, the body of the loop is executed again and the test expression is evaluated.
- This process goes on until the test expression becomes false.
- If the test expression is false, the loop ends.
Flowchart of do while
Example 2: Do..while loop
// Program to add numbers until the user enters zero
#include <stdio.h>
int main()
{
double number, sum = 0;
// the body of the loop is executed at least once
do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}
Output
Enter a number: 1.5 Enter a number: 2.4 Enter a number: -3.4 Enter a number: 4.2 Enter a number: 0 Sum = 4.70
Break and continue statements
C break
The break statement ends the loop immediately when it is encountered.
Its syntax is:
break;
The break statement is almost always used with if...else statement inside the loop.In C, break is also used with the switch statement
Example-
#include<stdio.h>
#include<stdlib.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
}
Output
0 1 2 3 4 5 came outside of loop i = 5
C continue
he continue statement skips the current iteration of the loop and continues with the next iteration.
Its syntax is:
continue;
The continue statement is almost always used with the if...else statement.Example
#include <stdio.h> int main() { for (int j=0; j<=8; j++) { if (j==4) { /* The continue statement is encountered when * the value of j is equal to 4. */ continue; } /* This print statement would not execute for the * loop iteration where j ==4 because in that case * this statement would be skipped. */ printf("%d ", j); } return 0; }
Output
0 1 2 3 5 6 7 8
go to statement in C
The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function.
Syntax:
Syntax1 | Syntax2----------------------------goto label; | label:. | .. | . . | .label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here label is a user-defined identifier which indicates the target statement. The statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.
Example
// Program to calculate the sum and average of positive numbers
// If the user enters a negative number, the sum and average are displayed.
#include <stdio.h>
int main() {
const int maxInput = 100;
int i;
double number, average, sum = 0.0;
for (i = 1; i <= maxInput; ++i) {
printf("%d. Enter a number: ", i);
scanf("%lf", &number);
// go to jump if the user enters a negative number
if (number < 0.0) {
goto jump;
}
sum += number;
}
jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
Output
1. Enter a number: 4 2. Enter a number: 5 3. Enter a number: 6 4. Enter a number: 7 Sum = 22 Average = 5.5
Array in C
An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar type of elements as in the data type must be the same for all elements.
array of integer
The array contains the following properties.
- Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
- Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.
- Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.
Declaration of C ArrayWe can declare an array in the c language in the following way.
data_type array_name[array_size];
Now, let us see the example to declare the array.
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of C ArrayThe simplest way to initialize an array is by using the index of each element. We can initialize each element of the array by using the index. Consider the following example.
// 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;
}
Output
Enter 5 integers: 1 -3 34 0 3 Displaying integers: 1 -3 34 0 3
2D Array in C
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. Before we discuss more about two Dimensional array lets have a look at the following C program.
Example 2D array
#include<stdio.h> int main(){ /* 2D array declaration*/ int disp[2][3]; /*Counter variables for the loop*/ int i, j; for(i=0; i<2; i++) { for(j=0;j<3;j++) { printf("Enter value for disp[%d][%d]:", i, j); scanf("%d", &disp[i][j]); } } //Displaying array elements printf("Two Dimensional array elements:\n"); for(i=0; i<2; i++) { for(j=0;j<3;j++) { printf("%d ", disp[i][j]); if(j==2){ printf("\n"); } } } return 0; }
Output:
Enter value for disp[0][0]:1 Enter value for disp[0][1]:2 Enter value for disp[0][2]:3 Enter value for disp[1][0]:4 Enter value for disp[1][1]:5 Enter value for disp[1][2]:6 Two Dimensional array elements: 1 2 3 4 5 6
Thank You !!!
In the next section we will talk about remaing topics.