Saturday, April 27, 2024
HomeTechnologyC programming language: Learn easily in 7 Days

C programming language: Learn easily in 7 Days

C programming language is one of the most basic and easy to learn languages. It provides a gateway for entering into the programming world. C covers all the basic concepts of programming and helps you learn structured programming practice which is the base for learning object-oriented programming.

Here, we will first learn the syntax and then cover the important topics which are needed for programming in all the languages like a conditional statement, loops, arrays, functions, file handling, structures, etc.

Learn C programming easily – Day 1

1: Setting up the IDE for programming in C

In this part you will learn:

1. IDE
2. Compiler
3. Setting up the DEV C++ environment

First and the most basic step to start coding is to set up an IDE
(Integrated Development Environment). It sounds a little bit complicated but it really isn’t. Now let’s cover some very basic questions that may arise in your mind.

What is an IDE?

IDE stands for integrated development environment, You can say it is simply a sheet of paper on which you write your code. It has all other some other stuff integrated with it, which includes a compiler to compile your code and show you an output, code formatter to color your written code for easier reading and many other stuff let’s not go into that now.

What is a Compiler?

What you write in your code is actually not understandable by a machine. Machine only understands machine language so a compiler is a program which automatically understands your code and converts it to machine language.

Which IDE should you use?

For beginners there is a very simple and good IDE easily available on the internet with the name DEV C++. You might be thinking that it’s written C++ relax it can also be used for C, as C and C++ are quite similar.

Setting up the DEV C++ IDE

•First of all, go to this link
http://download.cnet.com/Orwell-Dev-C/3000-2069_4-12686.html
and download DEV C++

•Then simply follow the instructions and install.

C programming language 5

Select your desired Language, Font, and then select Cache These Headers.

C programming language 3
C programming language 2

Click Next and ok

•Go to File > New > Source File.
•Now everything is set up and we are ready for coding.

C programming language 1

Writing your first C program

In this part you will learn:
1. C syntax
2. Showing output
3. Tabs and new lines
4. Headers
5. Variables and data types

Whenever I write something after // or in between /* */ it means I am writing comments. Comments are not read by the compiler they are just a way to write your own notes after some statement. Just like some people write notes on the side of a book.

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>

These are the header files that we need for coding. The main header is stdio.h which provides us with most of the functions for coding in C and the second header files is just for using a function which can pause the screen until the user hits any key.

int main(){
printf("This is my first C program"); //to show an output on screen
getch(); // pause the screen and wait for user to press any key
}//end main

In our first program we write our main function which is the heart of the program. Then we write an output statement known as the printf statement which simply outputs the text written in quotes on the screen (REMEMBER to write semicolon after every statement it tells the compiler that the statement is complete it’s just like a full-stop).

You are reading Learning C Programming language easily in just days in sunnyrabiussunny.com. Thank you.

After that we write getch function to pause the screen otherwise the screen will just blink and won’t be able to see the output. We keep writing the comments after every line for explanation (Remember they are not necessary).

After writing this go to save select extension as .c source file and save.
Go to execute -> compile.
Then after compilation go to execute -> run
Here a console window will open and you can see the output.

C programming language

Writing your second C program.

File > new > Source file

#include<stdio.h>
#include<conio.h>

First of all writing the headers then writing the main function

int main(){
// Declaring variables and setting their values
int number    = 25;
char alphabet = 'a';
float average = 5.25;
double PI     = 3.1428571428;

Declaring 4 different variables with 4 different data types. Remember a character is always written in single quotes except in print statement.

/* Printing values
of
variables*/
printf("The value of number is : %d ",number);  //to print an integer we use %d
printf("\nThe alphabet is : %c ",alphabet);  //to print a charcter we use %c
printf("\nAverage is : %f \t\t Value of PI is %lf",average,PI); // to print float we use %f for double %lf
printf("\n\n\n End of Program \n\n\n");   // for newline we user \n 
}//end main

First of all writing multiple line comments using /* */ and then writing the print statement for integer. (Remember the integer is printed using %d a character with %c, float with %f and double with %lf ). Then we print the alphabet character variable, notice that we wrote \n in the next print statement that is for printing in a NEW LINE. Then we write the average and double variable with \t in between which means we want to give a tab space between them. In the end we simply write end of program after leaving three lines and close the main function bracket.
Then save, compile and execute our program.

Learn C programming easily in 7 days – Day 2

User input and Conditional statements

In this part you will learn:
1. Taking input from user
2. Conditional statements
3. C syntax
4. Showing output
5. Tabs and new lines

Basic Step: 
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>

These are the header files that we need for coding. The main header is stdio.h which provides us with most of the functions for coding in C and the second header files is just for using a function which can pause the screen until the user hits any key.

int main(){
int number;
char alphabet;

First of all, we will declare an integer and an alphabet. In this program, we will only use these variables to take input and we will simply print these variables just to check whether the program is taking correct input or not.

printf("Enter a number :");
scanf("%d",&number); // scanf takes input remember ampersand sign &
printf("The number you typed is: %d ",number);
printf("\n\nWhat is the first letter of your name ? ");
scanf(" %c",&alphabet); // scanf takes input remember ampersand sign &
printf("The first letter of your name is : %c",alphabet);
getch(); return 0; // write now just write it as it is
}//end main

Now writing the print statements first and then we write the scanf function which is used to take the input from the user.

In scanf function we first write the type of variable in which we are taking input by using the format specifier i.e in case of integer is %d and in cases of character is %c and then we used the & symbol with our variable name this is to give compiler the address of the variable in memory , you will understand it later just write this & symbol as it is for now. In the end we just pause the screen using getch function and return 0 (write it as it is for now) and our program is complete.
Execute > compile
then Execute > run

Using Conditional statements in C programming language

The if , else and else if statements in C are called conditional statements. Now we will write a program to compare two numbers using conditional statements.
File > new source file

#include<stdio.h>
#include<conio.h>
int main(){
int num1,num2; //declaring two numbers named num1 and num2
printf("Enter number1 :");
scanf("%d",&num1); // scanf takes input remember ampersand sign &
printf("Enter number2 :");
scanf("%d",&num2); // scanf takes input remember ampersand sign &

We will first write the header files and then start our main function. In the main function, we declare two variables for number1 and number 2 and take user inputs in them. Then we start writing the conditional statements

if(num1 > num2) // if number1 is greater than number 2
printf("number1 is greater than number 2");
if(num1 < num2) // if number1 is less than number 2
printf("number2 is greater than number 1");
else   // 3rd possiblity number 1 is equal to number 2
printf("Both numbers are equal");
getch();
return 0; // write now just write it as it is
}//end main

There are three possibilities that a number is either greater, smaller or equal; so we will write the conditional statements for all these possibilities.
Execute > compile
then Execute > run

Calculator using Switch and Conditional Statements

In this part you will learn:
1. To make a calculator using Conditional statements
2. What is switch statement
3. To make a calculator using switch statement
4. C syntax
5. Showing output

In this tutorial, you will learn how to make a calculator using two different ways, firstly using the Conditional statement method and then using switch statement.

Using Conditional statements to make a calculator in C:

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h> #include<conio.h>
int main(){
 int num1,num2,ans = 0;
 char sign;

First of all we will declare 3 integers named as ‘num1’, ’num2’ and ’ans’, here we have declared 3 integers because in a calculator we will need two integer type variables on which a specific operation will be performed and the result after the operation will be stored in the third integer type variable. Secondly we need we have declared a character named ‘sign’ in which we will stored the specific operation that is needed to be performed. In this program, we will only use these variables to take input and storing the result as well. In the end the result after arithmetic operation will be displayed on the console

printf("Enter number 1 :");
scanf("%d",&num1);
printf("Enter sign :");
scanf(" %c",&sign);
printf("Enter number 2 :");
scanf("%d",&num2);

Now we are taking inputs from the user, firstly the user will enter the first number and then the second number, followed by the operation that the user wants to be performed on these recently entered numbers. Later on, after the operation the result will be stored in the integer type variable ‘ans’.

if ( sign == '+')ans = num1 + num2;
else if ( sign == '-')ans = num1 - num2;
else if ( sign == '*')ans = num1 * num2;
else if ( sign == '/')ans = num1 / num2;
else
printf("Error");
printf("Ans is : %d",ans);
}//end main

In these lines of code there are four conditions,

if the character given by the user as operation is + – / * the corresponding result will be produced,

if these operations are not given, ‘Error’ will be displayed in output.

Basically what’s happening in this code is that the compiler checks out that what character is inserted by the user and as referred to my fourth tutorial if a certain conditional statement is satisfied, then a specific operation is performed, for example, the user inputs ‘/’ character and compiler comes to the first statement that will work only if the character inserted is ‘+’.

So it will pass on to the second statement which is ( sign == ‘-‘), so as clearly shown that character inserted by user is ‘/’ so no operation will be performed, sequentially after passing through series of statement, compiler finds if ( sign == ‘/’) statement and the division operation will be performed on the two integers which will be stored in another integer that is ans.

There is also a possibility that the characters inserted by the user are not a proper arithmetic operation like addition, subtraction etc so the statement printf(“Error”) is written in the program to encounter such exceptional cases.

In the last line of the program the value contained in ‘ans’ integer is displayed using printf statement .

Execute > compile
then Execute > run

Calculator using Switch Statements in C programming language

File > new source file

What is switch statement:

A switch statement is a statement in which we declare different statements according to which we jump to a specific set of statements performed if the user inputs are matched to the statement of the code. While using switch statements we use a keyword ‘case’ just like ‘if ’ which ensures that the right set of statements are executed on a specific input, it will become more clear as we proceed.

Creating a Calculator using Switch statement in C programming language

In this program just like before we will make three integer type variables and one character type variable. Two integer type variables and one character type input is taken from the user and the result is stored in the third integer.

#include<stdio.h>
#include<conio.h>
int main(){
int num1,num2,ans = 0;
char sign;
printf("Enter number 1 :");
scanf("%d",&num1);
printf("Enter sign :");
scanf(" %c",&sign);
printf("Enter number 2 :");
scanf("%d",&num2);

Writing the print and scanf statements and getting the sign from the user. (REMEMBER, when using %c in scanf put a space befor %c because C language has this problem that it skips white spaces. If you don’t put a space manually it will not prompt you to enter the sign.)

switch ( sign){
case '+':
ans = num1 + num2;
break;
case '-':
ans = num1 - num2;
break;
case '*':
ans = num1 * num2;
break;
case '/':
ans = num1 / num2;
break;
default:
printf("Error");
}
printf("Ans is : %d",ans);
getch();
}//end main

Now the most important part is writing the switch statement. In the switch statement we make cases. In this program we want the program to switch to the statement according the character given +,*,/ and – so we simply pass the character variable to switch statement and make the cases according to the required characters and we break after every statement so that switch ends after executing a single statement and the program gets out of switch brackets, continuing the sequential flow. In case of any other variable is given input we switch to default case which works the same like “else condition”. Here we have added the default at the bottom so we don’t need to write any break statement. After that most our answers will be calculated if the operator is valid. Otherwise, it will print error and 0 as ans. After that, we write getch for pause and end the main.

Execute > compile
then Execute > run

Learn C programming language easily in 7 days at sunnyrabiussunny.com – Day 3

Learning LOOPS in C programming language

In this part you will learn:

1. What is a loop
2. For LOOP
3. More on conditional statements
4. C syntax
5. Showing output

What is a LOOP in C programming language?

A loop is simply a statement which can execute a set of defined statements repetitively. You can write any valid C statement within a loop and you can also set how many times to execute that certain statement.

There are three parts in a loop

  1. Initialization (loop starting from number mostly 1 or 0)
  2. Condition (to stop the loop at certain point)
  3. Increment (adding a certain number in variable to reach the stopping condition)

Three types of loops in C are

  1. For loop
  2. While loop
  3. Do While loop

Today we will discuss for loop.

Printing a table of any number using FOR LOOP in C programming language

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>
int main(){
 int number = 1;
int count  = 1; //to start the number multiplying by 1
 int ans = 0;

First of all, we will declare 3 integers named as ‘num1’,’num2’ and ’ans’, here we have declared 3 integers because in a table we will need two integer type variables on which a specific operation will be performed and the result after the operation will be stored in the third integer type variable. In this program, we will only use these variables to take input and storing the result as well. In the end, the multiplication table will be displayed on the console.

printf("Enter a number to print the table : ");
scanf("%d",&number);

Now we are taking inputs from the user, The user will enter the number and then we will run a loop to find the table of that number.

for(count =1; count<=20;count++){
 ans = number * count;
 printf(" %d * %d  = % d\n",number,count,ans);
}//end for
}//end main

In the for loop, notice that there are two semi colon’s which divides the bracket into three parts.

  1. The condition before the first semicolon is the initialization.
  2. The condition before the second semicolon is condition.
  3. The condition after the second semicolon is the increment.

We will simply multiply the number (given by user) with the for loop variable count which will start from 1 and go till 20. Incrementing every time the for loop runs. Then we end the program.
Execute > compile
then Execute > run

Printing EVEN ODD AND PRIME NUMBER SERIES using loops

File > new source file

#include<stdio.h>
#include<conio.h>
 int main(){
 int number = 1;
int count  = 1; //to start the number multiplying by 1
int prime; //loop counters
int choice;
int notPrime = 0; // 1 for true and 0 for false
int ans = 0;

Simply writing the headers and declaring the variables number for defining the limit to print the series. Count for loop , prime variable for loop , choice for switching , notPrime variable is a flag (1 represents true and 0 will represent false ), ans variable to store the answer.

printf("Press 1 to find series of odd numbers\nPress 2 for even \nPress 3 for Prime\nYour choice :");
scanf("%d",&choice);
printf("Please enter the LIMIT :");
scanf("%d",&number);

Here we are simply taking the user choice for ODD, EVEN OR PRIME number series and then we take the input of the limit to which he wants the series to be printed

switch(choice){
 case 1: // ODD NUMBRERS  
for(count =1; count<=number;count++){
 if(count % 2 != 0)
 printf("%d\n",count);
 }//end for
 break;

In the switch statement we write 3 cases for switching between odd, even and prime. The first case is for odd in this case we will run a for loop from 1 to the number (given by user) and check if it has remainder is not equal to 0 when it is divided by 2. if the remainder is not equal 0 when divided by 2 then it is an odd number so we simply print it and move on to the next number of the loop.

(REMEMBER: % is called modulus operator used to find the remainder of a number).

case 2: //  EVEN NUMBRERS 
 for(count =1; count<=number;count++){
 if(count % 2 == 0)
 printf("%d\n",count);
 }//end for
 break;

In this case, we will find the even numbers we simply run a loop from 1 to number (given by user) and check if the loop variable if it’s divisible by 2 if yes then it is an even number so we simply print it.

case 3: // prime numbers
 for(count = 0 ; count<number; count++){
 notPrime = 0;
 for( prime = 2; prime < count; prime++){
 if (count%prime == 0)
    notPrime = 1; }
 if(notPrime == 0)
    printf("%d\n",count);
 }//end for
 break;
default:
 printf("Invalid choice");
 }
  getch();
 return 0;
}//end main

In the third case we are finding the prime number series for that we need two nested for loops (loop within a loop). One loop for printing the numbers and the other one for checking whether the number is prime or not. First, we will set the prime variable to 0. Then we will run the 2nd loop, and then check the modulus of the every variable of the first loop by the complete second loop. Then after checking we will simply check if the number is prime then print otherwise end.
Execute > compile
then Execute > run

Learn C programming language easily in 7 days at sunnyrabiussunny.com – Day 4

Nested For LOOPS

In this part you will learn:

1. For LOOP
2. Nested For LOOP
3. More on conditional statements
4. C syntax
5. Showing output

What is a NESTED LOOP?

Sometimes we need two loops to execute a statement. For example, if we want to solve a 3 x 3 matrix then we will need two loops one for rows and other one for columns. So we use a loop within a loop for every iteration of the parent loop the inner loops runs completely.
Eg: for(int i=1;i<=10;i++){
For(int j =1;j<=10;j++)
Printf(“*”);
}
It will print 100 astericks because for each int i , int j runs 10 times.

Making a rectangle with asterisks using nested FOR LOOP:

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>
int main(){
 int width,height; // dimensions
 int w,l;

For making a rectangle we need to take input of two-variables i.e width and height. So we declare them first and we also declare the loop counters.

printf("Enter the width of rectangle: ");
scanf("%d",&width);
printf("Enter the height of rectangle: ");
scanf("%d",&height);

Now we are taking inputs from the user, The user will enter the width and height of the rectangle. We will use these variables to pass values to the for LOOP.

for(w=1; w<=height; w++){
 for(l=1; l<=width ; l++){
 printf("*");
 }
 printf("\n");
 }

Then we will run two nested for loops with the variables w and l. The first loop is for width and the second loop is for the height. For every row we will print asterisks from 1 to width and then after the inner loop is complete we simply print \n to change the line ( for going into the next row to print more asterisks.

 getch();
 return 0;
}//end main

Then we will simply call the getch function to pause the console and end the program.
Execute > compile
then Execute > run

Making a Triangle with asterisks using nested FOR LOOP:

In this program, we will simply print a triangle (using asterisks) double the size provided by the user.

File > new source file

#include<stdio.h>
#include<conio.h>
 int main(){
 int size; //size of half triangle
 int w,i;  //loop variables 
 printf("Enter the size of the triangle : ");
   scanf("%d",&size); //upper half of the triangle
for( w=1; w<=size; w++){
 for( i=1; i<=w;i++){
 printf("*");
 }
 printf("\n");
}

We first declare the variables size and loop variables and then get the size from the user. After that, we run nested for loop to print the upper half of the triangle. The first loop is to change the row of the triangle and the second loop is used to print the asterisks equal to row number (if 1st row then 1 asterisk, 2nd row 2 asterisks, and so on …). Then we will simply end these loops and start tow new nested for loops for the lower end.

 // lower half of the triangle
 for(w=1;w<=size;w++){
 for (i= size-1;i>=w;i--){
 printf("*"); 
}
 printf("\n"); 
}
 getch();
 return 0;
}

In the second set of loops, we do exactly the same thing in the first loop but in the second loop we just start it backward, so that we can make the triangle evenly . So we decrement in the second loop and change the row after it is complete. In the end we pause the screen and return and our program is complete.
Execute > compile
then Execute > run

Learn C easily in 7 days – Day 5

You are learning the C programming language in 7 days at sunnyrabiussunny.com. Do not forget to bookmark this website by pressing Ctrl+D in windows or pressing the STAR icon in any other OS or browser. remember the name: SunnyRabiusSunny dot com. Thank you.

While LOOP in C programming language

In this part you will learn:
1. While LOOP
2. C syntax
3. Showing output

What is a WHILE LOOP?

For a loop, we need three statements: Initialization, Condition and Increment. In a while loop we only write the condition within the round brackets and increment within the body of the loop. We initialize the variable outside the loop.

Checking for a prime number in C programming language

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>
int main()
{
int num,i=2;

For finding whether a number is prime or not we will simply take input in a number and make a loop counter to test whether it is divisible by numbers from 2 to 1 less than the number if yes then it is a prime number.

 printf("Enter number :");
 scanf("%d",&num);

Now taking input from the user.

while ( i<num){
 if (num %i==0 ){
 printf("\nNumber is not a prime number\n ");
 break;
 }
 i+=1;
}

Now we write the while loop. Note that we already initialized the i variable with 2 (because we will divide the number from 2 to 1 less than the number in order to find whether the number is prime or not). After that we write the conditional statement If the remainder of the number divided by loop counter is 0, then it is not a prime number. After the condition, we increment the variable.

 if (i== num)
 printf("\nNumber is a prime number\n ");
 else
 printf("\nNumber is not a prime number\n ");
 _getch();
 return 0;
}

If the loop is finished without the condition becoming true and the incremented value becomes equal to the number then that number is a prime number. Otherwise not.

Execute > compile
then Execute > run

FINDING SUM OF DIGITS in C Programming language

File > new source file

#include<stdio.h>
 int main()
{
 int num,temp=0,sum=0;
  printf("Enter the number :");
 scanf("%d",&num);
 }

For calculating the sum of digits of the numbers; we need three variables: Number, Temporary variable and Sum. We take the input in number.

while(num>0)
 {
 temp = num%10;
 sum +=temp;
  printf("\nDigit is : %d\n",temp);
              num=num/10;
 }
 printf("Sum of digits is : %d\n",sum);
 return 0;
}

Now we write the loop condition that runs until the number is greater than 0 because we will start separating the digits form Least significant to most significant. We take the remainder of the number with 10 to separate the digit and simply store it in our temp variable and add that variable to sum until the number is greater than 0. In the end we simply print the sum and return.

Execute > compile
then Execute > run

DO WHILE LOOP

In this part you will learn:
1. Do while LOOP
2. C syntax
3. Showing output

What is a DO WHILE LOOP?

A Do while loop is somewhat similar to a While loop. It has there necessary statements initialization, condition and increment. The initialization is done outside the body of the loop, the condition comes with the while part in round brackets and increment is done inside the body of the loop. In a do while loop the body of the loop is executed first and then afterwards, the condition of the loop is tested. If it is true, the code executes the body of the loop again.

Are you enjoying the tutorial on C programming language? if you are bored you can click on the play button in the lower right corner of the screen. It will play a music.

Enjoy.

Calculating Factorial in C using DO WHILE LOOP in C programming language

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>
int main()
{
int num,fact=1;

For finding the factorial of a number we take input of a number and Inside the loop, we multiply the counter times the accumulated number up to that point. In this case, the accumulator is ‘fact’.

 printf("Enter number :");
 scanf("%d",&num);
 int i=num;

Now taking input from the user.

do{
fact=fact*num;
         num--;
 }while(num>0);
}

Now we write the DO WHILE LOOP. Note that we are multiplying the number we entered with ‘fact’ which is the accumulator and initialized to 1. Then we made a decrement in the number and after that, we checked it with the condition. Our number should always be greater than 0 in any case. We copied the value of number into a variable ‘i’ just to print the original number.

 printf("Factorial of %d=%d\n",i,fact);
 getch();
 return 0;
}

Execute > compile
then Execute > run

Finding the SUM OF ALL THE NUMBERS UNTIL USER ENTERS ZERO in C programming language

File > new source file

#include<stdio.h> 
int main()
{
 Int sum=0,num,totalnumbers=0;  

For calculating the sum of all the numbers the user entered we need a variable to store the numbers user enters. Then we need a variable ‘sum’ to accumulate the sum of numbers. And we need a variable to keep the record of total numbers the user entered.

do{
       printf("Enter the number:\n");
       scanf("%d",&num);
        totalnumbers++;
        sum=sum+num;
       }while(num!=0); 

Now we write the body of the loop which takes a number from the user and adds it to the accumulator. Then the condition checks if the user has entered 0 it should stop taking any more numbers from the user and break out of the loop. Otherwise, it should keep going on taking numbers from the user and adding them.

   totalnumbers--;
   printf("The total number of numbers the user entered are=     %d",totalnumbers);
   printf("\nThe some of numbers is=%d",sum);
 getch();

Lastly, we printed the total number of numbers the user entered except the 0 at the end. We should not count the 0, because it’s our exit condition. And we printed the sum.

Execute > compile
then Execute > run

Learn C programming easily in 7 days – Day 6

Introduction to Arrays in C programming language

In this part you will learn:
1. Arrays
2. Sorting using arrays
3. Constants
4. Showing output

In this tutorial, you will learn how to use arrays.

What is an Array?

An array is a set of variables that you can declare in a single statement. For example, if you want to make a result calculating program; you need to declare the total number of students first. So instead of declaring student1, student2, etc., you can write int students[40]; in this way, we declared 40 variables in a single statement.

Sorting the array in descending order

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>
#define SIZE 1000

the #define statement is used to declare a constant variable.

int main()
{
 int input,i,x,y,j,temp = 0,index;
 int arr[SIZE]={0};

Now, writing the main function. We will declare variables for taking input, counters for loops and index variables to track the index of the array. Then finally we will declare an array using the constant SIZE variable that has a value of 1000.

 printf("Enter size :");
 scanf("%d",&input);

Now taking input of size to limit the array size. (REMEMBER we can’t set the size of an array in run time so we have to declare the constant SIZE first and then limit it by user input.)

for (i = 0;i < input; i++)
 {
 printf("Enter arr[%d] element : ",i);
 scanf("%d",&arr[i]);
 }

Running a for loop to take the input in array variable. We will enter the element one by one on every iteration of the loop.

 printf("UNSORTERD ARRAY\n");
 for (i = 0;i < input;i++)
 {
 printf("%d\t",arr[i]);
 }
}

After taking the input from the user we will first print to see the elements. To print the elements we will start the loop from 0 to the point of limit which is given by the user. We simply print the array with the index of I which is the loop counter starting from 0. The loop is starting from 0 because in an array the elements are stored from 0 to one less than the limit, for example, int arr[3]; there will be 3 elements in the array and we can access it by arr[0]; arr[1]; arr[2];

for(x = 0 ;x<input;x++){
 for(y=x;y<input;y++){
 if(arr[x]<arr[y]){
 temp =arr[x];
 arr[x]=arr[y]; arr[y]=temp; 
}
 }//end inner for
 }//end outer for

Now to sort the numbers we will run two loops. We will compare each number with all the numbers in the array and then adjust it’s position accordingly in descending order. So first of all making 2 nested loops outer one running form 0 to ONE LESS THAN INDEX and inner one running from outer loop counter value to ONE LESS THAN INDEX. After that we simply write an if condition that if the 1st value is less than the second value then store it in temporary variable and swap it with the greater number. After that store the temporary variable back to the variable which is picked up. So what we do is we simply compare each number in array with the complete array and if the number is less we simply swap.

printf("\nArray in descending order is:\n");
for(j=0;j<input;j++){
 printf("%d\t",arr[j]);
 }
 printf("\n");
 return 0;
}

In the end we
will run a loop to print our already sorted array and then we end our program.

Execute > compile
then Execute > run

Sorting the array in descending order in C programming language

Learning 2-Dimensional Arrays

In this part you will learn:
1. 2D Arrays
2. C syntax
3. Showing output

In this tutorial, you will learn about 2D Arrays.

What is a 2D Array?

In simple words, a 2D array is simply and array of array. We have multiple rows and columns in a 2D array. We have learned previously how we access elements of array by simply accessing the different indexes of array using subscripts. Now similarly we access the different elements of a 2D array by mentioning row number and column number in the subscript to access a specific index. 2D arrays are best used to represent tables as well as matrixes.

So today we will see the example of 2D arrays for multiplying two matrices.

Multiplication Of Matrix in C programming

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>
int main()
{
int matrix1[100][100] = { 0 }, matrix2[100][100] = { 0 }, matrix_ans[100][100] = { 0 };
 int r1, c1, r2, c2;
 int i, j, k;

For multiplying two matrixes we need three nested for loops which multiply each row of the first matrix to the columns of the second matrix. We will be using three loops because in the rules of matrices we know that if we multiply two matrices e.g 1×3 and 3×2 then the resultant matrix will have 1×2 columns so we will need three loops to traverse through all the rows and columns of all the matrices. To input and output the values of a 2D matrix we need to implement two nested for loops to access each index of a matrix.

printf("Enter the number of rows of 1st matrix :");
scanf("%d", &r1);
printf("Enter the number of columns of 1st matrix :");
scanf("%d", &c1);
printf("Enter the number of rows of 2nd matrix :");
scanf("%d", &r2);
printf("Enter the number of columns of 2nd matrix :");
scanf("%d", &c2);

Now we take input from the user the number of rows and columns of both the matrix.

if (c1 == r2)
 {
 printf("Enter element of 1st matrix :\n");
 for (i = 0; i < r1; i++)
 {
 for (j = 0; j < c1; j++)
 {
 scanf("%d", &matrix1[i][j]);
 }
 }
 printf("Enter element of 2nd matrix :");
 for (i = 0; i < r2; i++)
 {
 for (j = 0; j < c2; j++)
 {
 scanf("%d", &matrix2[i][j]);
 }
 }
 printf("\nAnswer Matrix is :\n");
 for (i = 0; i < r1; i++)
 {
 for (j = 0; j < c2; j++)
 {
 matrix_ans[i][j] = 0;
 for (k = 0; k < c1; k++)
 {
 matrix_ans[i][j] = matrix_ans[i][j] + (matrix1[i][k] *matrix2[k][j]);
 }
 printf("%d\t", matrix_ans[i][j]); } printf("\n");
 }
 }
 }

Now in this piece of code, we have taken input from the user the elements of both the matrix and them calculated their product. First of all, we have placed a condition which checks if the number of columns of the first matrix is equal to the number of rows of the second matrix because if this condition is not true then we cannot calculate the product of those two matrixes. After that, we have written a nested for loop to take input the elements of array. You see we have placed two subscripts one with a row number and the second with the column number. In this way, we access a single index of a 2D array. We have implemented the same kind of nested loop for the second matrix also to take the input. Then comes the nested for loop with three for loops. The first loop controls the row number of the resultant matrix which holds the result of the product. The second loop controls the column number of the resultant matrix as well as the column number of the second matrix. The third and the most inner loop controls the column and row number of first and second matrix respectively.
This whole nested loop works in a way that it multiplies respective elements of the column of the first matrix to the respective elements of the rows of the second matrix.

else
printf("As C1 NOT EQUAL TO R2 SO MULTIPLICATION IS NOT POSSIBLE ");
return 0;
}

The else part executes when the number of column of the first matrix are not equal to the number of rows of the second matrix.

Execute > compile
then Execute > run

Are you enjoying this tutorial on C programming for marketing professionals or students? Thank you for your patience.

Today is the last day of Learn C programming easily in 7 days with sunnyrabiussunny.com – Day 7

Functions and Global Variables in C programming language

In this part you will learn:
1. Functions
2. Global Variables
3. C syntax
4. Showing output

What are Functions?

Function provides a way in C programming to group instructions as a single unit and gives it a name. Function provides many benefits. Using function, a bigger task is divided into many sub-tasks and each sub-task is solved as a function/module. Furthermore, a function can be used/called repeatedly in C program. C programming relies heavily on functions and no meaningful program can be written without the use of functions. For even simple tasks like input and output, we use scanf and printf functions respectively which are declared in the stdio.h header file.

e.g void add(int num1,int num2);
Here void is the RETURN TYPE, add IS THE FUNCTION NAME, num1 & num2 are the parameters. Every function has these parts but parameters are optional.

Three ways of writing functions

  1. Functions with no return type. void Functions . Eg: void add();
  2. Functions with parameters Eg: add(int num1,int num2) – THERE CAN BE ANY NUMBER OF PARAMETERS
  3. Functions with return type Eg : float divide (int num1, int num2)

Making functions to make Calculations in C programming

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>
//Declaring function prototypes
voidinputGlobal(); // for taking input in global variables
void add();
void subtract(float,float);
float divide(float,float);
 //Declaring global variables
int no1;
int no2;

Here in this code, we have declared functions prototype before main, this is the basic syntax for calling the functions which are declared outside the main of the program, inside the main these functions are called and defined after the main as shown in the code below. In the second part we have declared variables named ‘no1’ and ‘no2’ as global variables. Global variables are always declared outside the main of the program. Global variables can be used by any function of the class.

int main()
{  float num1,num2;
   float ans=0;
   inputGlobal();
   add(); //for adding global variables
   printf("\n\nEnter num1:");
   scanf("%f",&num1);
   printf("Enter num2:");
   scanf("%f",&num2);
   subtract(num1,num2); //subtracting local variables by passing parameters 
        ans = divide(num1,num2); // dividing local variable by passing parameters and     returning answer
        printf("\nNumber1 divided by number 2 : %f ",ans);
     getch();
     return 0;}

Here first the local variables are declared and also variable ‘ans’ is initialized as well. Right below the function ‘inputGlobal()’ is called. The syntax for calling a function is main is that we do not have to write return type. Here inputGlobal is the name of the function whereas in the parenthesis the function can take input argument(s) but as the function need no input arguments so the parenthesis are left empty.Whenever we have to give arguments through main , the type of input arguments are not mentioned. Return type is the type of variable like int, float, double etc which the function returns after doing some calculation or work on the variables that have been input in the function. It must be remembered here that in C, a function can return only one variable , suppose if multiple operations are done on the variables which are taken by the function as input but the single variable will be returned so for different operations or calculations separate functions have to be defined just like subtract and add function.
The subtract function is called in main as ‘subtract(num1,num2);’, here as we see that it has no return type, return type is always mentioned before the name of the function definition(which is done in the later part of the code). Format for calling function in main is as follows
functionName(input arguments separated by commas) ;
For the subtract and divide function here we have also taken inputs from the users as num1 and num2. These inputs are passed to the function for the relative operation to be performed.

void inputGlobal(){
 printf("Enter global no1 :");
 scanf("%d",&no1);
 printf("Enter global no2 :");
 scanf("%d",&no2);}

In this piece of code the function inputGlobal which was called in the main is defined, this function basically assign the values to the global variables , as this function need not to return anything so its return type is void(means empty).
As you see that for defining a function its return type is also mentioned. Format for defining a functions is Returntype functionName (input arguments with their variable types separated by commas);

void add(){
 int answer=0;
 answer = no1 + no2;
 printf("Sum of two numbers is : %d ",answer);
}}

In the add function simply the two global variable are added to each other, the output is displayed(it’s not returned), else if the output was to be returned, the return type will be int instead of void.

void subtract(float n1,float n2){
 float ans =0;
 ans = n1 - n2;
 printf("Answer is : %f ",ans);
}
 float divide(float number1,float number2){
 return number1/number2;
}

The subtract function as called in the main takes in two input arguments and subtracts the second number from the first one.The result is simply displayed(printed) on the screen.
The divide function also takes in two arguments and perform division , but instead of simply displaying the result, the result is returned to main and is stored in the float type variable ‘ans’ and it is displayed on the screen by simply printing using printf through main. Like other functions the results could be simply displayed on the screen but in case of divide function the result is returned to main and stored in another variable which is then displayed.

Execute > compile
then Execute > run

Introduction to Pointers in C

In this part you will learn:
1. What are Pointers
2. How to use them in Programs
3. C syntax
4. Showing output

What are Pointers?
Our computer stores variables in the memory so they can be accessed by the compiler for processing. The compiler sets aside a memory location with a unique address to store that variable. Compiler basically creates an address space for a specific variable declared in the program and pointers are used to store the address locations of the variables or pointer can be referred as a variable that stores a memory address.
A pointer variable can be declared just by putting an asterisk (*) before the name of the variable but after the type of variable
e.g if we want to make an integer type pointer variable then simply put asterisk before the name of the variable like here we are making an integer type pointer named num1 so we write it as
int *num1;

Secondly, there is an important thing that you will see in the program below that is ampersand ‘&’, whenever we want that the change from the function changes the value of originally passed variable, we used ampersand sign with the variable when being passed.
The address of the variable is passed when we write ampersand with variable and ampersand is opposite to *.
e.g
int num1=4;
printf(“Address of num1 : %d”,&num1); // here something like 00AF344 will show up which is the //memory address
now if we want to see the relationship between ampersand and pointers it can be demonstrated as
printf(“Value of num1 : %d”,&*num1); // output will be value of num1 i.e 4

Pointer dereferences the variable.

Using Pointer and Functions in C

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>
#include<math.h>
double distance(int *,int *,int *,int *);
 int main()
{
 int y1,y2,x1,x2;
 printf("Enter y1,y2,x1,x2 :");
 scanf("%d%d%d%d",&y1,&y2,&x1,&x2);
  printf("Distance is : %.2lf \n",distance(&y1,&y2,&x1,&x2));
 }

In the first part of the code, we have declared a function that will take in 4 pointer variables as indicated. These four variables are basically the 2D coordinates of 2 points between which the distance will be calculated by the distance function.
In the main part, we have declared four integer type variables and have taken their values by the user. The variables are passed into the functions with ampersand(&) because when they are later used in the function that is having pointer variables as its input, the variables get the values as input by the user. Whenever the pointers are used in a function the values through main are always passed by reference.

 double distance(int *y1,int *y2,int *x1,int *x2)
{
 double x,y;
 x = *x2-*x1;
 y = *y2-*y1;
  return sqrt(pow(y,2) + pow(x,2));
}

In this function, the inputs are four pointer type integer type variables. Passed from main are the variables with ampersand sign. Here we used pointer variables to perform the operation of addition and subtraction instead of using the normal variables because we want to use the user’s provided input values.
Below we see function sqrt(pow(y,2) + pow(x,2)), this is a built-in C function which comes from math.h library, pow function simply takes power between two numbers and it takes a variables as it first input and the power to which we want the value of the variable to be raised as second input. Sqrt function simply takes the square root of its input. This function will return the distance between the two numbers by using the distance formula. The returned number will have double variable type.

Execute > compile
then Execute > run

Introduction to Structures in C

In this part you will learn:
1. What are Structures
2. How to use structure in Programs
3. C syntax
4. Showing output

What are Structures in C programming language?

Just like a simple variable type like int, float etc we can define our own data type so that whenever we make a variable of that type , it contains all the variables as defined by user automatically. Structures can contain multiple variables of different data type under one name. Structures allow us to access different variables by using a single pointer. Structure can have different variable data types according to the requirement of user. Each different variable in the structure is called member.
Syntax for making a structure is:
struct(keyword) nameofstructure
{ int a;
string g;
double r; // we can put in members types as per our requirement
}
strong>Using Structures

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>
#include<math.h>

These are the header files that we need for coding. The main header is stdio.h which provides us with most of the functions for coding in C and the second header files are just for using a function that can pause the screen until the user hits any key.
In this program, we will take user input about three attributes of employees user and in the end, display all the information that was entered. We also displayed the largest most salary at the end of the program

#define SIZE 3
 struct employee{
       char name[20];
       char designation[10];
       int salary;
        };
 }

In this code, first, we have defined the constant named ‘SIZE’ and gave it the size of 3. Then we have written a structure named ‘employee’, employee contains three variables first 2 are of type character. Two character type arrays defined here can take at most twenty characters. The last variable is of type int named salary. As told before, this is the basic syntax in C to define a structure.

 int main()
{
   employee e[SIZE];
    int i;
 int largest_salary;
     for(i=0;i<SIZE;i++)    
{
   printf("Enter name:");
   scanf("%s",&e[i].name);
   printf("Enter designation:");
   scanf("%s",&e[i].designation);
   printf("Enter salary :");
   scanf("%d",&e[i].salary);
    if(i==0)
 largest_salary=e[0].salary;
    if(e[i].salary>largest_salary)
  largest_salary=e[i].salary;
    }

In the main of the program, we have made the variable ‘e’ of the structure employee, whenever we want to declare a variable of some structure , we just write the name of structure and the name of the variable which we want to make. Now here ‘e’ will contain name, designation and salary under one name. Then we declared two integers ‘I’ and ‘largest_salary’ that will be used in the program for checking out the largest salary among three employees. Integer I is just used for running two for loops used in program. Whenever we want to use the specific variable of the structure, either by assigning some value or using some value from it we use dot ‘.’ operator. In the next line we are running a for loop which runs for 0,1 and 2 iteration because we have defined the size of constant variable ‘SIZE’ as three , the number of iterations can be changed by changing size of constant ‘SIZE’. Basically by changing the number of iterations we increase or decrease the number of employees. By using dot operator inside for loop we are assigning the values to the variables in employees, and hence the values will be assigned to three employees through this for loop.
In the last part of above code we basically assign the largest most salary among the three employees to the already made variable ‘largest_salary’. First we assign ‘largest_salary’ the first value of the salary entered for an employee and then we check whether if we find any employee’s salary greater than first one. If any value as such found, we simply assign that value to the ‘largest_salary’ variable.

 printf("%s%20s%20s","Name","Designation","Salary");
    for(i =0;i<SIZE;i++)    
{
   printf("\n%s",e[i].name);
    printf("%20s",e[i].designation);
   printf("%20d\n",e[i].salary);
       }
 printf("Largest salary: %d\n",largest_salary);
 getch();
return 0;
}    

In this code we basically printed(display) the results on our screen, first using for loop we displayed the already entered attributes of the employees and we used dot operator (.) for this purpose. In the last part, we also displayed the variable ‘largest-salary’ which contains the largest salary of any employee input by the user.

Execute > compile
then Execute > run

File Handling in C programming language

In this part you will learn:
1. Filling
2. C syntax
3. Showing output

What is Filing in C?

In C language we use filing to keep several records. We build certain programs to write our data in the file and to read our data from the file. The file can be in any format mostly we use txt formats.

File Read and Write

Basic Step:
Open Dev C++ then File > new > source file and start writing the code below.

#include<stdio.h>
#include<conio.h>

These are the header files that we need for coding. The main header is stdio.h which provides us with most of the functions for coding in C and the second header files are just for using a function that can pause the screen until the user hits any key.

struct time{
     int hour;
     int min;
     int sec;
 };
 int main()
 {
     struct time t;
     FILE *fptr;
 fptr = fopen("time.txt","wb+");

To Read and Write from a file we need a FILE type pointer that will point towards our file. In easy words, it will contain the address of our file. In this program, we have also made a struct named time which contains three int variables for hours, minutes and seconds. Note that we opened the file in a write mode. Which means we can only write in the file using fptr pointer.

printf("Enter total seconds:");
scanf("%d",&t.sec);

t.hour = t.sec / 3600;
t.sec %= 3600;
t.min=t.sec/60;
t.sec %=60;

printf("%d:%d:%d\n",t.hour,t.min,t.sec);

Now we asked the user the total number of seconds he wanted to write in the will. Then there is this simple calculation which converts the total seconds into hours and minutes and assign them to the the struct variable.

fprintf(fptr,"Time is: ");
     fwrite(&t,sizeof(struct time),1,fptr);
     printf("contents written");
 fclose(fptr);
 <\c>
 Now the first statement prints whatever we want it to print in the file. It is similar to the one we use to print anything on the console only it has a ‘f’ with it which refers to file. Then there is this function called fwrite(). This function takes input the struct which we created as an argument then the size of struct, then the condition which checks if it is true and lastly the pointer which contains the address of the file. It will write everything that was saved in the struct variable in the file. After that we closed the file with the fclosed statement.
 <\c> 
         printf("\n Now reading ..");
         fptr = fopen("time.txt","rb+");
         fseek(fptr,ftell(fptr)-sizeof(struct time),SEEK_END);
     fread(&t,sizeof(struct time),1,fptr);     printf("\n%d:%d:%d\n",t.hour,t.min,t.sec);
       fclose(fptr); 
}
 getch();
     return 0;

Now we opened the file in the reading mode. In the reading mode we are first pointing our pointer towards our file i.e time.txt and then opening it in read binary plus (rb+) mode because we are using binary file handling. Then we used the fseek() function to set the position of file pointer at the start. Then we used fread() function which reads everything from the file in the struct we sent as an argument. And lastly we print the contents again on the console and closed the file again using fclose().

Execute > compile
then Execute > run

That’s it. You have completed the beginner course in C programming tutorial. Thank you.

RELATED ARTICLES

Most Popular