Wednesday, 7 September 2016

C LANGUAGE INPUT AND OUTPUT

INPUT AND OUTPUT IN C LANGUAGE 

C programming has several in-build library functions to perform input and output tasks.
Two commonly used functions for I/O (Input/Output) are printf() and scanf().
The scanf() function reads formatted input from standard input (keyboard) whereas the printf() function sends formatted output to the standard output (screen).

Example #1: C Output


#include <stdio.h>      //This is needed to run printf() function.
int main()
{
    printf("C Programming");  //displays the content inside quotation
    return 0;
}
Output
C Programming
How this program works?
  • All valid C program must contain the main() function. The code execution begins from the start of main() function.
  • The printf() is a library function to send formatted output to the screen. The printf() function is declared in "stdio.h" header file.
  • Here, stdio.h is a header file (standard input output header file) and#include is a preprocessor directive to paste the code from the header file when necessary. When the compiler encounters printf() function and doesn't find stdio.h header file, compiler shows error.
  • The return 0; statement is the "Exit status" of the program. In simple terms, program ends.

Example #2: C Integer Output

#include <stdio.h>
int main()
{
    int testInteger = 5;
    printf("Number = %d", testInteger);
    return 0;
}
Output
Number = 5
Inside the quotation of printf() function, there is a format string "%d" (for integer). If the format string matches the argument (testInteger in this case), it is displayed on the screen.

Example #3: C Integer Input/Output

#include <stdio.h>
int main()
{
    int testInteger;
    printf("Enter an integer: ");
    scanf("%d",&testInteger);  
    printf("Number = %d",testInteger);
    return 0;
}
Output
Enter an integer: 4
Number = 4
The scanf() function reads formatted input from the keyboard. When user enters an integer, it is stored in variable testInteger. Note the '&' sign beforetestInteger&testInteger gets the address of testInteger and the value is stored in that address.

Example #3: C Floats Input/Output

#include <stdio.h>
int main()
{
    float f;
    printf("Enter a number: ");
// %f format string is used in case of floats
    scanf("%f",&f);
    printf("Value = %f", f);
    return 0;
}
Output
Enter a number: 23.45
Value = 23.450000
The format string "%f" is used to read and display formatted in case of floats.

Example #4: C Character I/O

#include <stdio.h>
int main()
{
    char var1;
    printf("Enter a character: ");
    scanf("%c",&var1);     
    printf("You entered %c.",var1);  
    return 0;
}   
Output
Enter a character: g
You entered g.
Format string %c is used in case of character types.

Little bit on ASCII code

When a character is entered in the above program, the character itself is not stored. Instead a numeric value(ASCII value) is stored. And when we displayed that value using "%c" text format, the entered character is displayed.

Example #5: C ASCII Code

#include <stdio.h>
int main()
{
    char var1;
    printf("Enter a character: ");
    scanf("%c",&var1);     

    // When %c text format is used, character is displayed in case of character types
    printf("You entered %c.\n",var1);  

    // When %d text format is used, integer is displayed in case of character types
    printf("ASCII value of %c is %d.", var1, var1);  
    return 0;
}
Output
Enter a character: g
You entered g.
ASCII value of g is 103.
The ASCII value of character 'g' is 103. When, 'g' is entered, 103 is stored in variable var1 instead of g. 
You can display a character if you know ASCII code of that character. This is shown by following example.

Example #6: C ASCII Code

#include <stdio.h>
int main()
{
    int var1 = 69;
    printf("Character having ASCII value 69 is %c.",var1);
    return 0;
}  
Output
Character having ASCII value 69 is E.
Click here to learn more about the complete ASCII reference.

More on Input/Output of floats and Integers

Integer and floats can be displayed in different formats in C programming.

Example #7: I/O of Floats and Integers

#include <stdio.h>
int main()
{

    int integer = 9876;
    float decimal = 987.6543;

    //  Prints the number right justified within 6 columns
    printf("4 digit integer right justified to 6 column: %6d\n", integer);

    // Tries to print number right justified to 3 digits but the number is not right adjusted because there are only 4 numbers
    printf("4 digit integer right justified to 3 column: %3d\n", integer);

    // Rounds to two digit places
    printf("Floating point number rounded to 2 digits: %.2f\n",decimal);

    // Rounds to 0 digit places
    printf("Floating point number rounded to 0 digits: %.f\n",987.6543);

    // Prints the number in exponential notation(scientific notation)
    printf("Floating point number in exponential form: %e\n",987.6543);
    return 0;
}   
Output
4 digit integer right justified to 6 column:   9876
4 digit integer right justified to 3 column: 9876
Floating point number rounded to 2 digits: 987.65
Floating point number rounded to 0 digits: 988
Floating point number in exponential form: 9.876543e+02  
To understand this example, you should have the knowledge of following C programming topics:
C program to print

Thursday, 1 September 2016

Data Types In C language


FUNDAMENTAL Data Types in C language

RAW SOFTWARES

In C programming, variables or memory locations should be declared before it can be used. Similarly, a function also needs to be declared before use.
Data types simply refers to the type and size of data associated with variables and functions.

Data types in C

  1. Fundamental Data Types
    • Integer types
    • Floating type
    • Character type
  2. Derived Data Types
size chart of various data types 


we can understand the classification of data types using the following diagram:


Integer data types

Integers are whole numbers that can have both positive and negative values, but no decimal values. Example: 0, -5, 10
In C programming, keyword int is used for declaring integer variable. For example:
int id;
Here, id is a variable of type integer.
You can declare multiple variable at once in C programming. For example:
int id, age;
The size of int is either 2 bytes(In older PC's) or 4 bytes. If you consider an integer having size of 4 byte( equal to 32 bits), it can take 232 distinct states as: -231,-231+1, ...,-2, -1, 0, 1, 2, ..., 231-2, 231-1
Similarly, int of 2 bytes, it can take 216 distinct states from -215 to 215-1. If you try to store larger number than 231-1, i.e,+2147483647 and smaller number than -231, i.e, -2147483648, program will not run correctly.

Floating types

Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0 etc. You can declare a floating point variable in C by using either float or double keyword. For example:
float accountBalance;
double bookPrice;
Here, both accountBalance and bookPrice are floating type variables.
In C, floating values can be represented in exponential form as well. For example:
float normalizationFactor = 22.442e2;

Difference between float and double

The size of float (single precision float data type) is 4 bytes. And the size ofdouble (double precision float data type) is 8 bytes. Floating point variables has a precision of 6 digits whereas the precision of double is 14 digits.

Character types

Keyword char is used for declaring character type variables. For example:
char test = 'h'
Here, test is a character variable. The value of test is 'h'.
The size of character variable is 1 byte.

C Qualifiers

Qualifiers alters the meaning of base data types to yield a new data type.

Size qualifiers

Size qualifiers alters the size of a basic type. There are two size qualifiers, longand short. For example:
long double i;
The size of float is 8 bytes. However, when long keyword is used, that variable becomes 10 bytes.
If you know that the value of a variable will not be large, short can be used.

Sign qualifiers

Integers and floating point variables can hold both negative and positive values. However, if a variable needs to hold positive value only, unsigned data types are used. For example:
// unsigned variables cannot hold negative value 
unsigned int positiveInteger;
There is another qualifier signed which can hold both negative and positive only. However, it is not necessary to define variable signed since a variable is signed by default.
An integer variable of 4 bytes can hold data from -231 to 231-1. However, if the variable is defined as unsigned, it can hold data from 0 to 232-1.
It is important to note that, sign qualifiers can be applied to int and char types only.

Constant qualifiers

An identifier can be declared as a constant. To do so const keyword is used.
const int cost = 20;
The value of cost cannot be changed in the program.

Volatile qualifiers

A variable should be declared volatile whenever its value can be changed by some external sources outside the program. Keyword volatile is used for creating volatile variables.
for next topic visit : rawsoftwares.blogspot.com

Tuesday, 30 August 2016

C Language at Raw Softwares

 

     C Programming language

RAW SOFTWARES


C is a high-level and general purpose programming language that is ideal for developing firmware or portable applications. Originally intended for writing system software, C was developed at Bell Labs by Dennis Ritchie for the Unix Operating System (OS) in the early 1970s.

C belongs to the structured, procedural paradigms of languages. It is proven, flexible and powerful and may be used for a variety of different applications. Although high-level, C and assembly language share many of the same attributes.
Following are C programming language features:
  • Fixed number of keywords, including a set of control primitives, such as if, for, while, switch and do while.
  • Multiple logical and mathematical operators, including bit manipulators.
  • Multiple assignments may be applied in a single statement.
  • Function return values are not always required and may be ignored if unneeded.
  • Typing is static. All data has type but may be implicitly converted.
  • Basic form of modularity, as files may be separately compiled and linked.
  • Control of function and object visibility to other files via extern and static attributes.
Getting start with c Language:
In order to run a C program, you need a compiler. Compiler change source code(code written by programmer) to object code(code that computer understands) and creates executable file. There are many free and professional compilers available. For the sake of this course, GNU GCC compiler is used. All the examples in this course are tested and verified in GNU GCC compiler.
we are starting with basic terminology of c language
Tokens:
c tokens are the basic buildings blocks in c language which are constructed together to write a c program. each and every smalllest individual units in a c program are known as c tokens. 
c tokens are of six types. they are,
  1. keywords
  2. identifiers
  3. constants 
  4. strings
  5. special symbols
  6. operators
1. Keywords:
    Keywords are predefined, reserved words used in programming that have special meaning. Keywords are part of the syntax and they cannot be used as an identifier. For example:
int money;
Here, int is a keyword that indicates 'money' is a variable of type integer. 
Keywords in C Language
autodoubleintstruct
breakelselongswitch
caseenumregister typedef
charexternreturnunion
continueforsignedvoid
doifstatic while
defaultgotosizeofvolatile
constfloatshortunsigned
Along with these keywords, C supports other numerous keywords depending upon the compiler.
2. Identifiers:
Identifiers are the names you can give to entities such as variables, functions, structures etc.
Identifier names must be unique. They are created to give unique name to a C entity to identify it during the execution of a program. For example:
int money;
double accountBalance;
Here, money and accountBalance are identifiers.
Also remember, identifier names must be different from keywords. You cannot use int as an identifier because int is a keyword.
Rules for writing an identifier:
  1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscore only.
  2. The first letter of an identifier should be either a letter or an underscore. However, it is discouraged to start an identifier name with an underscore. It is because identifier that starts with an underscore can conflict with system names.
    In such cases, compiler will complain about it. Some system names that start with underscore are _fileno_iob_wfopen etc.
  3. There is no rule on the length of an identifier. However, the first 31 characters of identifiers are discriminated by the compiler. So, the first 31 letters of two identifiers in a program should be different.
  3. Constants:       
A constant is a value or an identifier whose value cannot be altered in a program. For example: 1, 2.5, "C programming is easy" etc.
As mentioned, an identifier also can be defined as a constant.
const double PI = 3.14
Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program.
Integer constants
A integer constant is a numeric constant (associated with number) without any fractional or exponential part. There are three types of integer constants in C programming:
  • decimal constant(base 10)
  • octal constant(base 8)
  • hexadecimal constant(base 16)
For example:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x.

Floating-point constants

A floating point constant is a numeric constant that has either a fractional form or an exponent form. For example:
-2.0
0.0000234
-0.22E-5
Note: E-5 = 10-5

Character constants

A character constant is a constant which uses single quotation around characters. For example: 'a', 'l', 'm', 'F'

Escape Sequences

Sometimes, it is necessary to use characters which cannot be typed or has special meaning in C programming. For example: newline(enter), tab, question mark etc. In order to use these characters, escape sequence is used.
For example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal way the characters are interpreted by the compiler.
Escape Sequences
Escape SequencesCharacter
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null character
String constants
String constants are the constants which are enclosed in a pair of double-quote marks. For example:
"good"                  //string constant
""                     //null string constant
"      "               //string constant of six white space
"x"                    //string constant having single character.
"Earth is round\n"         //prints string with newline
Enumeration constants
Keyword enum is used to define enumeration types. For example:
enum color {yellow, green, black, white};
Here, color is a variable and yellowgreenblack and white are the enumeration constants having value 0, 1, 2 and 3 respectively.

4.String:
A string in C is merely an array of characters. The length of a string is determined by a terminating null character: '\0' . So, a string with the contents, say, "abc" has four characters: 'a' , 'b' , 'c' , and the terminating null character. The terminating null character has the value zero.
we will learn string in letter blogs.rawsoftwares.blogspot.com

5. Special Symbols
c language contains the following special character in association with the letters and digits.
 Symbol
 Meaning
 ~  Tilde
 ! Exclamation mark 
 # Number sign 
 $ Dollar sign 
Percent sign  
 ^ Caret
 & Ampersand 
  * Asterisk 
(  Lest parenthesis 
 ) Right parenthesis 
Underscore  
 + Plus sign 
 |  Vertical bar
  \  Backslash
 ` Apostrophe
 -  Minus sign
 =  Equal to sign
  {  Left brace
  }  Right brace
 [  Left bracket
 Right bracket
 :  Colon
 "  Quotation mark
 ;  Semicolon
 <  Opening angle bracket
 >  Closing angle bracket
  ?  Question mark
 ,  Comma
 . Period
  /  Slash

6. Operators

An operator is a symbol which operates on a value or a variable. For example:+ is an operator to perform addition.
C programming has wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as:
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators
Arithmetic Operators
OperatorDescriptionExample
+Adds two operands.A + B = 30
Subtracts second operand from the first.A − B = -10
*Multiplies both operands.A * B = 200
/Divides numerator by de-numerator.B / A = 2
%Modulus Operator and remainder of after an integer division.B % A = 0
++Increment operator increases the integer value by one.A++ = 11
--Decrement operator decreases the integer value by one.A-- = 9

Relational Operators


OperatorDescriptionExample
==Checks if the values of two operands are equal or not. If yes, then the condition becomes true.(A == B) is not true.
!=Checks if the values of two operands are equal or not. If the values are not equal, then the 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 the 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 the 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 the 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 the condition becomes true.(A <= B) is true.

Logical Operators


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

Bitwise Operators


pqp & qp | qp ^ q
00000
01011
11110
10011

OperatorDescriptionExample
&Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) = 12, i.e., 0000 1100
|Binary OR Operator copies a bit if it exists in either operand.(A | B) = 61, i.e., 0011 1101
^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) = 49, i.e., 0011 0001
~Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.(~A ) = -61, i.e,. 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 = 240 i.e., 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 = 15 i.e., 0000 1111

Assignment Operators

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

Misc Operators ↦ sizeof & ternary

 size of operator and conditional operator( ? : )
OperatorDescriptionExample
sizeof()Returns the size of a variable.sizeof(a), where a is integer, will return 4.
&Returns the address of a variable.&a; returns the actual address of the variable.
*Pointer to a variable.*a;
? :Conditional Expression.If Condition is true ? then value X : otherwise value Y

For Next topic visit next blog. thank you. rawsoftwares.blogspot.com