Skip to main content

101/Introduction to C Language - part 2



To get an overview of C language read: 101/Introduction to C - part 1

Following are some basic topics which we will cover in this tutorial:
  • How to take input from the users (Managing Input and Output operation).
  • How to take decisions (Decision making and Branching). ie. If-else and nested If-else
  • Looping:  for loop, nested for loop, while/do while loop.
  • Arrays.

How to take input from the user in C

Following are the two ways to take input from the user
  1. Using normal input syntax
  2. Taking input as command line argument

1. Using normal input syntax

In C programming, scanf() function is used to read character, string,  numeric data from keyboard.

It uses format specifier as parameter to take type of input like ‘%s’ for string, ‘%d’ for interger, ‘%c’ for character.
Example: 


#include<stdio.h>

int main()
{
int i;  
printf("Enter any Number:"); 
//taking Integer input from the user and storing at the address of variable i (&i denotes the address of i)
scanf("%d",&i);
printf("you entered i = %d\n",i);
return 0;
}

INPUT
OUTPUT


2. Taking input as command line arguments


Those values which are provided externally to the main function are knows comman line arguments.
You can provide arguments with the run command
 ./program input
Usage :


To catch the argument passed through the command line we need two parameters in main function int argc and char *argv[] as follows:
 
int main (int argc, char *argv[]) 
{ 
    //code here 
    return 0; 
}
 
where argc is the argument count which keeps track of the number of arguments passed through the command line and argv[] is the pointer to argument value.
example :
 ./addition 2 3 
here ./addition is the command to run the program named addition.
 The arguments 2 and 3 are the inputs from the user.
Here the argument count ie. argc is 3 and *argv points to each argument passed as follows:
argv[0] points to ./addition, argv[1] points to 2 and argv[2] points to 3
Let us assume we have to take the an integer input from the User

 
#include
#include 
int main(int argc, char *argv[])
{
  int i;
  //input value is always character type, we have to convert it into Interger through atoi() function
  i = atoi(argv[1]);
  printf("value of i you entered is %d\n",i);
  return 0;
}
 atoi() converts the character value to integer value. We use \n  for new line.
The following command will run your program and you are free to change the argument value.
 ./programName 2 
How to take a decision?

When we talk about decisions, we normally mean conditions that we put in if-else and nested if-else parentheses.

If-else:
syntax:


 
if (condition) 
{ 
   //statement 
} 
else 
{ 
   //statement 
}
 
if the condition inside the parentheses is true then it will fall in the brackets to execute the code in it.


Nested If-else:

syntax:

if(condition)
{
    if(condition)
    {
        //statement
    }
    else
    {
        //statement
    }
}
else
{
    //statement
}

nested if-else is multiple if’s inside each other and else at the end.



Loops


You may encounter situations, when a block of code needs to be executed several number of times. Loops help us to do the same without typing the same lines again and again. We are going to cover: For Loop, While Loop, Do-While Loop and Nested Loops.
Really hoping you don't fall in the loop.


for loop:

syntax :

 
for( initialisation; condition; increment or decrement ) 
{ 
   statement(s); 
}
 
First, we initialise the value of the counter (that will count the number of times the loop will execute).
Second, we state the condition. The loop will execute till condition is true.
Third, we increment or decrement in the value of the counter according to our convinience.
 example: print numbers from 0 to 5
 
for(int i=0; i < 6; i = i+1) 
{ 
  printf("%d\n",i); 
}
 
INPUT
OUTPUT

while Loop:
syntax:
 
while(condition) 
{ 
  //do something 
}
 
example: print numbers from 0 to 5
 
int i=0;
while(i < 6) 
{ 
  printf("%d\n",i);
  i = i+1; 
}
 
INPUT
OUTPUT

In the above example we declare the value of integer i to be zero. Then in the while loop we check if the condition i less than six is true or not. If the value of i is less than six then it will fall in the brackets to execute the lines of code in it. First statement inside the brackets is to print the value of i on screen each time in a newline(\n). The second statement increases the value of i everytime.
do-while :
syntax :
 
do 
{ 
  //code to execute 
}
while (condition);
 
example: print numbers from 0 to 5

 
int i = 0; 
do 
{  
  printf("%d",i); 
  i = i+1; 
}
while (i<6);
INPUT
OUTPUT

Note :
while
and do-while are very much same except the fact that while first checks the condition to be true where as do-while execute the first time and then checks the condition.

Nested Loop :
Nested loop is basically a loop inside a loop. It can be a nested for loop or a nested while loop.
syntax :
 
for ( initialisation; condition; increment ) 
{
      for ( initialisation; condition; increment ) 
      {   
         statement(s); 
      } 
      statement(s); 
}
 

Arrays

One dimensional arrays can be viewed as a long line of data of same types each with a different block.






    How to declare 1D array :
     First we need to assign datatype to the array. Datatypes help in allocating the memory to the array. char needs 1byte where as an int needs 2 bytes (4 bytes in some cases). Then you decide the size of the array. The size can be viewed as the number of blocks in the line.
     dataType arrayName[size]; 
    example:
     char name[5]; 
    How to assign value to array :

     char name[5] = ['D','A','N','N','Y','\0']; 
    This is one way to assign value to the array. '\0' marks the ending of the array.

    Comments

    Popular posts from this blog

    How to Install PyCharm? (Windows, Mac, Ubuntu)

      A little introduction PyCharm is one of the widely used IDE for python programming and used by many programmers these days. It is available in three editions: Professional, Community and Educational (Edu). We will prefer Edu edition as it is an open source and free to use. Also, it fits our purpose of learning python as a beginner. If you have already installed pycharm or some other compiler you can skip this and read the tutotrial here>> Let's Get Started with Python Install PyCharm You can go to the official page and follow the guide to installation, to go to the official page click here or stick with me and follow the steps below. This is the direct link to install PyCharm Edu>> click here Already Installed PyCharm Community or Professional? Then you just need to install EduTools Plugin. To install the plugin follow these simple steps: 1.        Go to Files>>Settings... or Press Ctrl+Alt+S to open Setting/Preferences dialogue. 2.  

    101/Introduction to C language - part 1

    We are assuming you have C compiler already Installed in your systems, if not you can read  How to install C compilers ? (Ubuntu, Mac, Windows) What is C ? C is high-level compared to assembly but low leveled compared to JavaScript. But in general terms C is considered as high level language . So when we talk about c language, we usually hear the following terms Header file Data types Variables Main function Operators Hello World Program ( gateway to programming world  😉 ) Addition/Subtraction program for the basic understanding of Operators What is Header File ? As a beginner I never got a satisfactory answer for the same. In a nutshell, we can say “ It's just like a brain to a body ” ,  It enables us to use the functionality which is pre-implemented by the Developers, just like the brain adds the functionality to other body parts. Header file has a file extension of '.h'  for example “stdio.h” also called standard input-ou

    Let’s Get Started with Python

    NOTE: The tutorial is aimed at people who have no prior programming experience. If you have previous experience with other programming language (C) and just want to compare the syntax you can jump to this page (link will be updated soon). If you have no compilers installed then you may follow the installation guide here>> How to Install PyCharm? Tutorial00 Statements Let’s start by using  print() , it simply prints whatever you type in double or single codes. As per the tradition let’s print Hello World. In the python file you created type print(“Hello World”) or print(‘Hello World’) as shown below