Menu
 

by the name of god lets have a start to learn c proggraming basics  ..... JAI SHREE RAM
we are starting with programs as we will learn theories along with the programming.
1ST WE WILL WRITE A SIMPLE PROGRAM TO DISPLAY HELLO WORLD;

PROGRAM;
1. #include<stdio.h>
2. void main(){
3. printf("hello world");
4. }
here in line 1. we see command #include this command includes the contents of the file "stdio.h".this function is used so that each and every time the whole header file is not required to be written. it is a header file means it contents  the definition of the functions generally used for input and output,or simple processing . therefore it has full form standard input output.
functions like printf,scanf,etc.
 in line 2. we see that void word is used . it is used so that we could tell the compiler beforehand that the main function is gonna return simple nothing.main is a compulsory function which has to be declared because the processing of the program is started and finised in this function only. we find () after the main , here the parameters are written . since we are not passing any parameters to the main function we dont need to write anything here. after that the '{' denotes the start of the main function.
note : every opened bracket,parenthesis have to be closed to avoid compiling error.
in line 3. we have have predifined function ' printf' which is defined in the header file stdio.h . it has syntax printf(""); whatever is written between double inverted commas  is printed as it is. except in certain  special conditions, which we will learn later.
every code block ends with semicolon.it denotes the end of the particular code.


NOW WE LEARN ABOUT DATA TYPE.
there are several types of datatypes in c . like int, float, char, etc.
each datatypes has memory allocated by the compiler in the RAM according to the OS( 16bit,32bit,64bit);
int is for integers , float is for decimal numbers , and char is for characters. we can also use long word before each datatypes to double the memory allocated for long calculations.
 program;

#include<stdio.h>
void main(){
int a=9,b=7,c;
c=a+b;
printf(" %d",c);
}
 here we are declaring variabes (whose values are not fixed). we are calculating sum of two numbers a and b , whose values are stored as 9 and 7 respectively. simply we can write c= a+b and its over . c now has value of sum of a and b.
here we see that printf statement has some thing different .yes, %d for integer type variable is written in the program.now this means something else has to be printed instead of %d. what is to be printed.thats written out side of the double inverted comma.after a comma.thats c. means integer value of c is printed instead of %d.similarly we can use %f for decimal numbers and %c for character type.
IF-ELSE, SWITCH CASE
now we come to learn about if else statement.
here as the name is , it checks a codition if its true do something else do other thing.
syntax
if(condition){
do something;
}
else{
do another thing;
}
one more statement else if can be used to check more than one condition ;

simple program;
 #include<stdio.h>
void main(){
int a=7;
if(a>7){
printf("good");
}
else if (a=7){
printf("ok");
}
else{
printf("not good");
}
}
again in switch case condition we can have 1 value of for which different cases are checked;

example-
 switch(1){
case 1:
 do something;
 break ;
case 2 :
do something;
break;
}
similarly we can add several case statement. dont forget to  add break statement after each case. break is used to stop the further execution of the code in the switch statement. we also have a statement called, " continue " which is used to skip the processing of code only for that  code block. we will learn about it later.
HOW TO TAKE INPUT.
we have a statement called scanf to take the value .
example
#include<stdio.h>
void main(){
int a;
printf("enter value of a ");
scanf("%d",&a);
}
we have first declared a. then we have told the user to enter the value and after entering the value scanf statement reads the value. what datatype to read is to be told between the double inverted commas. for two input readings we have to write two times the datatype. like scanf("%d%d",&a,&b);
 the second part &a stores the value in a.

now let us add two numbers  entered by user.
#include<stdio.h>
void main(){
int a,b,c;
printf("enter two numbers");
scan(%d%d",&b,&a);
c=a+b;
printf(" %d",c);
}
it adds two numbers.
similar to if else we have a ternary operator.
syntax
result= condition ? if true : if false;
example
a= b>7? c=0:c=1;
code example
#include<stdio.h>

void main()
{
   int n;

   printf("Input an integer\n");
   scanf("%d",&n);

   n%2 == 0 ? printf("Even\n") : printf("Odd\n");

 }
this function checks for even and oddd  number.
MORE PROGRAMS>
add,substract, multiply ,divide
#include <stdio.h>

void main()
{
   int first, second, add, subtract, multiply;
   float divide;

   printf("Enter two integers\n");
   scanf("%d%d", &first, &second);

   add        = first + second;
   subtract = first - second;
   multiply = first * second;
   divide     = first / (float)second;   //typecasting

   printf("Sum = %d\n",add);
   printf("Difference = %d\n",subtract);
   printf("Multiplication = %d\n",multiply);
   printf("Division = %.2f\n",divide);


}
check whether character is vowel or not.
#include <stdio.h>

void main()
{
  char ch;

  printf("Enter a character\n");
  scanf("%c", &ch);

  if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch =='o' || ch=='O' || ch == 'u' || ch == 'U')
    printf("%c is a vowel.\n", ch);
  else
    printf("%c is not a vowel.\n", ch);

 }
 here we have used '||'. this is called logical or. simply speaking  if any of the conditions is true then it processes the if block.
one more operator '&&' called logical and is present which checks if both conditions are true, then only the if block is processed.
LOOPS CONTROL SYSTEM>
now we have learned several things. but what if we have to use same codes  several number of times. we can do it by loops.
FOR LOOP;
firstly we have for loop;
if we know how many times we want to repeat same process we can use for loop. like
for(i=0;i<10;i++);
 in this statement we can see initial value of i is given as 0; now we have to repeat process for 10 times. so 0-9. total value 10. therefore 10 countings is  done. last part is for what to do after the code is processed here we will increase the value of i by 1. we can use i+=2 for increasing the value of i by 2.
while loop
while ( condition ) { Code to execute while the condition is true } The true represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is like a stripped-down version of a for loop-- it has no initialization or update section. However, an empty condition is not legal for a while loop as it is with a for loop.

Example:
#include <stdio.h>

void main()
{
  int x = 0;  /* Don't forget to declare variables */
 
  while ( x < 10 ) { /* While x is less than 10 */
      printf( "%d\n", x );
      x++;             /* Update x so the condition can be met eventually */
  }
 
}
do while
DO..WHILE - DO..WHILE loops are useful for things that want to loop at least once. The structure is
do {
} while ( condition );
Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, we jump back to the beginning of the block and execute it again. A do..while loop is almost the same as a while loop except that the loop body is guaranteed to execute at least once. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and then continue to loop while the condition is true".

Example:
#include <stdio.h>

void main()
{
  int x;

  x = 0;
  do {
      printf( "Hello, world!\n" );
  } while ( x != 0 );

}
ARRAYS
An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.
declaring arrays
int billy [5] = { 16, 2, 77, 40, 12071 };
 here int is the data type of the array, means all values in the array are integers and the number in [] is the number of elements (max) that can be stored in the array. values in {} separated by commas are values of the array at different position. we can fetch values by billy[0],billy[1] for 1st and second element respectively. thus counting starts from 0.here values are billy[0]=16,billy[1]=2,....
taking input from user in array.
main(){
int i,n=10,a[100];
for(i=0;i<n;i++){ \\n is the number of elements to be stored
printf("enter  value");
scanf("%d",&a[i]);
}}
thus we can conclude we can also demand more space , than needed,as n=10,a[100] so number of spaces allocated =100;

string can be told to be an array of characters , symbols and anything,even space.
char string[50];
this is the defination of character type string.
#include <stdio.h>

void  main()
{
    /* A nice long string */
    char string[256];                              

    printf( "Please enter a long string: " );

    /* notice stdin being passed in */
    fgets ( string, 256, stdin );          

    printf( "You entered a very long string, %s", string );


}
here a function is used fgets this has 3 parameters . fgets(string name, size , input device)   stdin means keyboard input.it is similar to scanf but it can also take input spaces ,while scanf doesnt read after a space.
Now that you should have learned about variables, loops, and conditional statements it is time to learn about functions. You should have an idea of their uses as we have already used them and defined one in the guise of main. Getchar is another example of a function. In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create your own functions.
string.h or strings.h

The C language provides no explicit support for strings in the language itself. The string-handling functions are implemented in libraries. String I/O operations are implemented in <stdio.h> (puts , gets, etc). A set of simple string manipulation functions are implemented in <string.h>, or on some systems in <strings.h>.

The string library (string.h or strings.h) has some useful functions for working with strings, like strcpy, strcat, strcmp, strlen, strcoll, etc. We will take a look at some of these string operations.

Important: Don’t forget to include the library string.h (or on some systems strings.h) if you want to use one of these library functions.
strcpy
This library function is used to copy a string and can be used like this: strcpy(destination, source). (It is not possible in C to do this: string1 = string2). Take a look at the following example:
str_one = "abc";
str_two = "def";
strcpy(str_one , str_two); // str_one becomes "def"
Note: strcpy() will not perform any boundary checking, and thus there is a risk of overrunning the strings.
strcmp
This library function is used to compare two strings and can be used like this: strcmp(str1, str2).
If the first string is greater than the second string a number greater than null is returned.
If the first string is less than the second string a number less than null is returned.
If the first and the second string are equal a null is returned.
Take look at an example:
printf("Enter you name: ");
scanf("%s", name);
if( strcmp( name, "jane" ) == 0 )
printf("Hello, jane!\n");

Note: strcmp() will not perform any boundary checking, and thus there is a risk of overrunning the strings.
strcat
This library function concatenates a string onto the end of the other string. The result is returned. Take a look at the example:
printf("Enter you age: ");
scanf("%s", age);
result = strcat( age, " years old." ) == 0 )
printf("You are %s\n", result);
Note: strcat() will not perform any boundary checking, and thus there is a risk of overrunning the strings.
strlen
This library function returns the length of a string. (All characters before the null termination.) Take a look at the example:
name = "jane";
result = strlen(name); //Will return size of four.
memcmp
This library function compares the first count characters of buffer1 and buffer2. The function is used like this: memcmp(buffer1,buffer2). The return values are as follows:
If buffer1 is greater than buffer2 a number greater than null is returned.
If buffer1 is less than buffer2 a number less than null is returned.
If buffer1 and buffer2 are equal a null is returned.
Note: There are also library functions: memcpy, memset and memchr.
FUNCTIONS
functions are used to perform some operation ,which is defined  only once and can be used over and over again whenever required.
For example:
#include <stdlib.h>

int a = rand(); /* rand is a standard function that all compilers have */
Do not think that 'a' will change at random, it will be set to the value returned when the function is called, but it will not change again.


There can be more than one argument passed to a function or none at all (where the parentheses are empty), and it does not have to return a value. Functions that do not return values have a return type of void. Let's look at a function prototype:
int mult ( int x, int y );
This prototype specifies that the function mult will accept two arguments, both integers, and that it will return an integer. Do not forget the trailing semi-colon. Without it, the compiler will probably think that you are trying to write the actual definition of the function.

When the programmer actually defines the function, it will begin with the prototype, minus the semi-colon. Then there should always be a block (surrounded by curly braces) with the code that the function is to execute, just as you would write it for the main function. Any of the arguments passed to the function can be used as if they were declared in the block. Finally, end it all with a cherry and a closing brace. Okay, maybe not a cherry.

Let's look at an example program:
#include <stdio.h>

int mult ( int x, int y );

void main()
{
  int x;
  int y;
 
  printf( "Please input two numbers to be multiplied: " );
  scanf( "%d", &x );
  scanf( "%d", &y );
  printf( "The product of your two numbers is %d\n", mult( x, y ) );

}

int mult (int x, int y)
{
  return x * y;
}
here the values are passed to the function mult and it  gives back product to the main function.
recursive function.
this is a type of function which calls itself.let us take an example of factorial. 1*2*3*4=4!
thus we can define a fuction like this
int fact(int a){
if (a==0 || 1)
return 1;
else return (a*fact(a-1));
}
here the function returns 1 when a=0,1 as 0!,1!=1;
again if a not =1,0 it calls itself again for the value a-1, till  it gets a=0,1.then onwards it starts replacing values in the previous cases.like if for a particular case a=3 then it returns 3*fact(2), here for fact(2) it returns 2*fact(1), now fact(1)=1, therefore previous 2*fact(1) becomes 2. and 3*fact(2) becomes 3*2=6

Post a Comment

 
Top