Sunday, 28 September 2014

Printing your name on the screen in C language

Printing your name on the screen in C language


Let’s see how to write this C program

#include<conio.h>
#include<stdio.h>
int main()
{
char myname[20];
printf(“enter your name : “);
scanf(“%s”,&myname);
printf(“my name is %s“,myname);
getch();
return 0;
}


Explanation of the above program


Preprocessors, header files, main()
We had discussed it in our previous program.

char myname[20] ;
This statement declares a variable myname of type character whose size is of 20. Which means myname variable can store up to 20 characters.

Printf()
This is a kind of a function which is use to display something on the screen
What so ever is written in the double quotes “ ”

Scanf()
This is also a function which is similar to print().
It is used to get the input from the user and stores it into the particular variable

%s
Signifies the character format of values we need to store in the variable
And this is also used to display the value of character variable

Getch()
This function is found in the conio.h library/header file   
This will going to hold the screen until any button is pressed from the keyboard

Return 0
This will going to return the null value to the main() as main() is declared in the int data type so it has to return a integer value to main()



Pictures of program:

Step 1:  Create the program:-


Step 2: compile and run:



Step 3: output 

In the output you need to enter only your first name and press enter



Step 4: run the program again and enter your full name in it



In this case it will only going to show the character entered before space-bar
Next we learn how to overcome this problem

Note:  if any of the programmer is facing the problem of reappearing of the                      previous screen again and again
           He can use the function clrscr();
           It present in the conio.h header file
           After declaring the variables

Example in this program
……
………..
char myname[20];
clrscr();
printf(“enter your name : “);
…………

……………….

Sunday, 21 September 2014

First C program (Hello, World)

First C language Program

Lets see how to write a simple c program 

#include< stdio.h>
#include< conio.h>
int main()
{
 printf("Hello,World");
 getch();
 return 0;
}

Different parts of C program.

        Pre-processor

        Header file

        Function

        Variables

        expression

        Comment

Pre-processor 

#include, the first word of any C program. It is also known as pre-processor. The main work of pre-processor is to initialize the environment of program, i.e to link the program with the header file.

 

 

Header file

Header file is a collection of built-in functions that help us in our program. Header files contain definitions of functions and variables which can be incorporated into any C program by pre-processor #include statement. Standard header files are provided with each compiler, and cover a range of areas like string handling, mathematical functions, data conversion, printing and reading of variables.
To use any of the standard functions, the appropriate header file must be included. This is done at the beginning of the C source file.
For example, to use the printf() function in a program, the line #include< stdio.h> is responsible.

 

 

main() function

main() function is a function that must be used in every C program. A function is a sequence of statement required to perform a specific task. main() function starts the execution of C program. In the above example, int in front of main() function is the return type of main() function. we will discuss about it in detail later. The curly braces { } just after the main() function encloses the body of main() function.

Compile and Run

There are many different ways to compile and run a C program. All that is required is a C compiler. We will recommend you to use turbo c IDE, oldest IDE for c programming. It is freely available over internet and is good for a beginner.


Step 1 : Open turbo C IDE(Integrated Development Environment), click on File and then click on New


first c program
Step 2 : Write the above example as it is 

Write a C program

Step 3 : Click on compile or press Alt+f9 to compile the code

Compiling a C program

Step 4 : Click on Run or press Ctrl+f9 to run the code


Running a C program
Step 5 : Output
Output of C program
that's all you need to do .
run your first C language program
i hope it will run fine on your systems.

Wednesday, 17 September 2014

Basic structure of C program

Basic structure of C program


Let’s see what the basic structure is


#include<header_file(1).h>
#include<header_file(2).h>
….
..                                                  //all header files are to declared first
….
#include<header_file(n).h>

main()     // main()function is the first function which is executed by a C                                      program

{                                                        //start of the program
Statement(1);
Statement(2);
Statement(3);
Statement(4);
…                           //N number of statements can be written
….                         //All C Statements are written within main function
……
…..
Statement(n);


}                                                 //end of the program


Sunday, 14 September 2014

About Preprocessors

The C Preprocessor is not part of the compiler, but is a separate step in the compilation process. In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct compiler to do required pre-processing before actual compilation. We'll refer to the C Preprocessor as the CPP.
All preprocessor commands begin with a pound symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in first column. Following section lists down all important preprocessor directives:
DirectiveDescription
#defineSubstitutes a preprocessor macro
#includeInserts a particular header from another file
#undefUndefines a preprocessor macro
#ifdefReturns true if this macro is defined
#ifndefReturns true if this macro is not defined
#ifTests if a compile time condition is true
#elseThe alternative for #if
#elif#else an #if in one statement
#endifEnds preprocessor conditional
#errorPrints error message on stderr
#pragmaIssues special commands to the compiler, using a standardized method

Preprocessors Examples

Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use#define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file. The next line tells CPP to get myheader.h from the local directory and add the content to the current source file.
#undef  FILE_SIZE
#define FILE_SIZE 42
This tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
   #define MESSAGE "You wish!"
#endif
This tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
   /* Your debugging statements here */
#endif
This tells the CPP to do the process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation.

Predefined Macros

ANSI C defines a number of macros. Although each one is available for your use in programming, the predefined macros should not be directly modified.
MacroDescription
__DATE__The current date as a character literal in "MMM DD YYYY" format
__TIME__The current time as a character literal in "HH:MM:SS" format
__FILE__This contains the current filename as a string literal.
__LINE__This contains the current line number as a decimal constant.
__STDC__Defined as 1 when the compiler complies with the ANSI standard.
Let's try the following example:
#include <stdio.h>

main()
{
   printf("File :%s\n", __FILE__ );
   printf("Date :%s\n", __DATE__ );
   printf("Time :%s\n", __TIME__ );
   printf("Line :%d\n", __LINE__ );
   printf("ANSI :%d\n", __STDC__ );

}
When the above code in a file test.c is compiled and executed, it produces the following result:
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1

Preprocessor Operators

The C preprocessor offers following operators to help you in creating macros:

Macro Continuation (\)

A macro usually must be contained on a single line. The macro continuation operator is used to continue a macro that is too long for a single line. For example:
#define  message_for(a, b)  \
    printf(#a " and " #b ": We love you!\n")

Stringize (#)

The stringize or number-sign operator ('#'), when used within a macro definition, converts a macro parameter into a string constant. This operator may be used only in a macro that has a specified argument or parameter list. For example:
#include <stdio.h>

#define  message_for(a, b)  \
    printf(#a " and " #b ": We love you!\n")

int main(void)
{
   message_for(Carole, Debra);
   return 0;
}
When the above code is compiled and executed, it produces the following result:
Carole and Debra: We love you!

Token Pasting (##)

The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token. For example:
#include <stdio.h>

#define tokenpaster(n) printf ("token" #n " = %d", token##n)

int main(void)
{
   int token34 = 40;
   
   tokenpaster(34);
   return 0;
}
When the above code is compiled and executed, it produces the following result:
token34 = 40
How it happened, because this example results in the following actual output from the preprocessor:
printf ("token34 = %d", token34);
This example shows the concatenation of token##n into token34 and here we have used both stringize and token-pasting.

The defined() Operator

The preprocessor defined operator is used in constant expressions to determine if an identifier is defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). The defined operator is specified as follows:
#include <stdio.h>

#if !defined (MESSAGE)
   #define MESSAGE "You wish!"
#endif

int main(void)
{
   printf("Here is the message: %s\n", MESSAGE);  
   return 0;
}
When the above code is compiled and executed, it produces the following result:
Here is the message: You wish!

Parameterized Macros

One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows:
int square(int x) {
   return x * x;
}
We can rewrite above code using a macro as follows:
#define square(x) ((x) * (x))
Macros with arguments must be defined using the #define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between and macro name and open parenthesis. For example:
#include <stdio.h>

#define MAX(x,y) ((x) > (y) ? (x) : (y))

int main(void)
{
   printf("Max between 20 and 10 is %d\n", MAX(10, 20));  
   return 0;
}
When the above code is compiled and executed, it produces the following result:
Max between 20 and 10 is 20

Sunday, 7 September 2014

About Operators in C

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C language is rich in built-in operators and provides the following types of operators:
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators
This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Arithmetic Operators

Following table shows all the arithmetic operators supported by C language. Assume variable A holds 10 and variable B holds 20 then:

OperatorDescriptionExample
+Adds two operandsA + B will give 30
-Subtracts second operand from the firstA - B will give -10
*Multiplies both operandsA * B will give 200
/Divides numerator by de-numeratorB / A will give 2
%Modulus Operator and remainder of after an integer divisionB % A will give 0
++Increments operator increases integer value by oneA++ will give 11
--Decrements operator decreases integer value by oneA-- will give 9

Relational Operators

Following table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20, then:

OperatorDescriptionExample
==Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
!=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

Logical Operators

Following table shows all the logical operators supported by C language. Assume variable holds 1 and variable B holds 0, then:

OperatorDescriptionExample
&&Called Logical AND operator. If both the operands are non-zero, then condition becomes true.(A && B) is false.
||Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true(A || B) is true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows:
pqp & qp | qp ^ q
00000
01011
11110
10011
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011
The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then:

OperatorDescriptionExample
&Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12, which is 0000 1100
|Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61, which is 0011 1101
^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49, which is 0011 0001
~Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.(~A ) will give -61, which is 1100 0011 in 2's complement form.
<<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
>>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 0000 1111

Assignment Operators

There are following assignment operators supported by C language:
OperatorDescriptionExample
=Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A
<<=Left shift AND assignment operatorC <<= 2 is same as C = C << 2
>>=Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
&=Bitwise AND assignment operatorC &= 2 is same as C = C & 2
^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
|=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

Misc Operators ↦ sizeof & ternary

There are few other important operators including sizeof and ? : supported by C Language.

OperatorDescriptionExample
sizeof()Returns the size of an variable.sizeof(a), where a is integer, will return 4.
&Returns the address of an variable.&a; will give actual address of the variable.
*Pointer to a variable.*a; will pointer to a variable.
? :Conditional ExpressionIf Condition is true ? Then value X : Otherwise value Y

Operators Precedence in C

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity 
Post-fix () [] -> . ++ - -  Left to right 
Unary + - ! ~ ++ - - (type)* & sizeof Right to left 
Multiplicative  * / % Left to right 
Additive  + - Left to right 
Shift  << >> Left to right 
Relational  < <= > >= Left to right 
Equality  == != Left to right 
Bitwise AND Left to right 
Bitwise XOR Left to right 
Bitwise OR Left to right 
Logical AND && Left to right 
Logical OR || Left to right 
Conditional ?: Right to left 
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left 
Comma Left to right