Showing posts with label Basic C Programming. Show all posts
Showing posts with label Basic C Programming. Show all posts

Thursday, 25 January 2018

Functions in C


A function is a set of statements that take inputs, do some specific computation and produces output....

Monday, 22 January 2018

Loops

Loop control statements in C are used to perform looping operations until the given condition is true. Control comes out of the loop statements once condition becomes false.

if else statement in c


In decision control statements (if-else and nested if), group of statements are executed when condition is true. If condition is false, then else part statements are executed.

Sunday, 21 January 2018

Operators in C

An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators −

Constants and Literals


Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.

C Variables




Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information.
 Their sole purpose is to label and store data in memory. This data can then be used throughout your program.

Assigning Value to Variables


Naming variables is known as one of the most difficult tasks in computer programming. When you are naming variables, think hard about the names. Try your best to make sure that the name you assign your variable is accurately descriptive and understandable to another reader. Sometimes that other reader is yourself when you revisit a program that you wrote months or even years earlier.

When you assign a variable, you use the = symbol. The name of the variable goes on the left and the value you want to store in the variable goes on the right.


Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows –
  
type variable_name = value;
Some examples are –

extern int d = 3, f = 5;    // declaration of d and f.
int d = 3, f = 5;           // definition and initializing d and f.
byte z = 22;                // definition and initializes z.
char x = 'x';               // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined.



There are 2 types of variable 
1. Global-->globally accepted throughout the program(Declare outside all the function)
2.Local-->Just can be used inside the program means it can be used inside small functions closed by braces({}).



Simple Program Code to understand variables:

#include<stdio.h>
int var=10; /* Assigning 10 to Var means instead of writing 10 use Var..and int means its of int type*/
void message();
void main()
{
int var=20;
  {
  int var = 30;
  printf("%d ",var); /* 30 is local to this function */
  }
printf("%d ",var);/* 20 is local to this */
message();   
}

void message()
{
printf("%d ",var);   /* 10 is local to this */
}

So, output will be 30 20 10


⇒C Compiler to run the above Code:https://goo.gl/Z24q5c

 

 

Lvalues and Rvalues in C

 

There are two kinds of expressions in C −
·        lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment.
·        rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the
following valid and invalid statements −
int g = 20; // valid statement
10 = 20; // invalid statement; would generate compile-time error






c-printf-and-scanf


printf() and scanf() functions are inbuilt library functions in C programming language which are available in C library by default.

1. printf() and scanf() in C language:
  • These functions are inbuilt library functions in C programming language. 
  • They are available in C library by default.
  • As a child is known by parents, so here scanf() and printf() are children and their parents are stdio.h.
  • We have to include “stdio.h” file to make use of these printf() and scanf() library functions in C language.

Some important points for Printf():



  • In C programming language, printf() function is used to print the “character, string, float, integer, octal and hexadecimal values” onto the output screen.
  • We use printf() function with %d format specifier to display the value of an integer variable.
  • Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for double and %x for hexadecimal variable.
  • To generate a newline,we use “\n” in C printf() statement.
  • %d got replaced by value of an integer variable  (no),
  • %c got replaced by value of a character variable  (ch),
  • %f got replaced by value of a float variable  (flt),
  • %lf got replaced by value of a double variable  (dbl),
  • %s got replaced by value of a string variable  (str),
  • %o got replaced by a octal value corresponding to integer variable  (no),
  • %x got replaced by a hexadecimal value corresponding to integer variable
  • \n got replaced by a newline.

Some Important points for Scanf()


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


  • The format specifier %d is used in scanf() statement. So that, the value entered is received as an integer and %s for string.
  • Ampersand is used before variable name “ch” in scanf() statement as &ch.
  • It is just like in a pointer which is used to point to the variable. For more information about how pointer works, please click here.



Note:
C language is case sensitive. For example, printf() and scanf() are different from Printf() and Scanf(). All characters in printf() and scanf() functions must be in lower case.


Basic Program to understant the concept of printf() and Scanf():



#include <stdio.h>
int main()
{
char ch;
/*user enters a character. This value is assigned to the variable “ch” */

char str[100];/
*User enters a string and this value is assigned to the variable “str” */

printf("Enter any character \n");
/*/n is used for next line*/
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}


Output


Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
Suraj
Entered string is Suraj



KEY POINTS TO REMEMBER IN C PRINTF() AND SCANF():

  • printf() is used to display the output and scanf() is used to read the inputs.
  • printf() and scanf() functions are declared in “stdio.h” header file in C library.
  • All syntax in C language including printf() and scanf() functions are case sensitive.


Return values of printf() and scanf() in C/C++:


printf() : It returns total number of Characters Printed, Or negative value if an output error or an encoding error



Example 1: The printf() function in the code written below returns 6. As ‘CODING’ contains 6 characters.



// C/C++ program to demonstrate return value 
// of printf() 
#include <stdio.h> 
  
int main() 
{ 
    char st[] = "CODING"; 
  
    printf("While printing "); 
    printf(", the value returned by printf() is : %d", 
                                    printf("%s", st)); 
  
    return 0; 
} 


scanf() : It returns total number of Inputs Scanned successfully, or EOF if input failure occurs before the first receiving argument was assigned.


Example : The first scanf() function in the code written below returns 1, as it is scanning 1 item. Similarly second scanf() returns 2 as it is scanning 2 inputs and third scanf() returns 3 as it is scanning 3 inputs.

#include <stdio.h> 
int main() 
{ 
    char a[100], b[100], c[100]; 
  
    // scanf() with one input 
    printf("\n First scanf() returns : %d", 
                            scanf("%s", a)); 
  
    // scanf() with two inputs 
    printf("\n Second scanf() returns : %d", 
                       scanf("%s%s", a, b)); 
  
    // scanf() with three inputs 
    printf("\n Third scanf() returns : %d",  
                  scanf("%s%s%s", a, b, c)); 
  
    return 0; 
} 


Saturday, 20 January 2018

Basic programming concepts



We assume you are well aware of English Language, which is a well-known Human Interface Language. English has a predefined grammar, which needs to be followed to write English statements in a correct way. Likewise, most of the Human Interface Languages (Hindi, English, Spanish, French, etc.) are made of several elements like verbs, nouns, adjectives, adverbs, propositions, and conjunctions, etc.
Similar to Human Interface Languages, Computer Programming Languages are also made of several elements. We will take you through the basics of those elements and make you comfortable to use them in various programming languages. These basic elements include −
  • Programming Environment
  • Basic Syntax
  • Data Types
  • Variables
  • Keywords
  • Basic Operators
  • Decision Making
  • Loops
  • Numbers
  • Characters
  • Arrays
  • Strings
  • Functions
  • File I/O
We will explain all these elements in subsequent chapters with examples using different programming languages. First, we will try to understand the meaning of all these terms in general and then, we will see how these terms can be used in different programming languages.
This tutorial has been designed to give you an idea about the following most popular programming languages −
  • C Programming
  • Java Programming
  • Python Programming
A major part of the tutorial has been explained by taking C as programming language and then we have shown how similar concepts work in Java and Python. So after completion of this tutorial, you will be quite familiar with these popular programming languages.


C PROGRAMMING BASICS TO WRITE A C PROGRAM:


Below are few commands and syntax used in C programming to write a simple C program. Let’s see all the sections of a simple C program line by line.

 A SIMPLE C PROGRAM:


Below C program is a very simple and basic program in C programming language. This C program displays “Hello World!” in the output window. And, all syntax and commands in C programming are case sensitive. Also, each statement should be ended with semicolon (;) which is a statement terminator.


#include <stdio.h>
int main()
{
   /* Our first simple C basic program */
   printf("Hello World! ");
   getch();
   return 0;

}

C Basic commandsExplanation
#include <stdio.h>This is a preprocessor command that includes standard input output header file(stdio.h) from the C library before compiling a C program
int main()This is the main function from where execution of any C program begins.
{This indicates the beginning of the main function.
/*_some_comments_*/whatever is given inside the command “/*   */” in any C program, won’t be considered for compilation and execution.
printf(“Hello_World! “);printf command prints the output onto the screen.
getch();This command waits for any character input from keyboard.
return 0;
This command terminates C program (main function) and returns 0.
}
This indicates the end of the main function.

 STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT:

Below are the steps to be followed for any C program to create and get the output. This is common to all C program and there is no exception whether its a very small C program or very large C program.

Create
Compile
Execute or Run

Get the Output


CREATION, COMPILATION AND EXECUTION OF A C PROGRAM:



Prerequisite:


  • If  you want to create, compile and execute C programs by your own, you have to install C compiler in your machine. Then, you can start to execute your own C programs in your machine.
  • You can refer below link for how to install C compiler and compile and execute C programs in your machine.
  • Once C compiler is installed in your machine, you can create, compile and execute C programs as shown in below link.
  • If you don’t want to install C/C++ compilers in your machine, you can refer online compilers which will compile and execute C/C++ and many other programming languages online and display outputs on the screen. Please search for online C/C++ compilers in Google for more details.


KEY POINTS TO REMEMBER IN C PROGRAMMING BASICS:

  • C programming is a case sensitive programming language.
  • Each C programming statement is ended with semicolon (;) which are referred as statement terminator.
  • printf() command is used to print the output onto the screen.
  • C programs are compiled using C compilers and displays output when executed.