Sie sind auf Seite 1von 13

A QUICK REVIEW OF C _for TR

What is <stdio.h> ?
stdio stands for standard input output. It's a header file that has the functions for input and
output.

what is header file ?


It is a file that has some pre-defined functions and variables which are used by the user's
program. Some pre-defined header files are <stdio.h>,<string.h> etc. Header files can also be
created by the user but to include them use “ ” instead of <>.(e.g. #include “MyFile.h”). #include is
used to include header files in c.

What is a keyword ?
Key words are reserved words used for some intended purposes. Standard keywords are
auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto,
if, int, long, register, short, return, signed, sizeof, static, struct, switch, typedef, union,
unsigned, void, volatile, while. Keywords should not be used as variables.

What is a data type ?


The type of data the variables or arrays are declared for. The basic data types are int, char,
float and double.

What is a variable ?
It's an identifier used to represent some specified information.
e.g. int a=23. Here a is variable of type int.

What is Pre increment, post increment ?


++i => pre increment. i.e. increment i, then give the new value of i.
i++ => post increment i.e. give the value of i, then increment it afterwards.

Difference between 'break” and “continue” ?


Break statement terminates the loop/switch it resides in. Continue skips the statements after
this keyword and the loop continues again.

While (true){
for (int i=0;i<=10;i++)
{
if(i==5) continue;
elif(i==7) break;
printf(“%d”,i);
}
}

Difference between “structure” and “union”?


Structure can have different data types unlike arrays (which has only one data type)
Struct data Union data
{ char name[20] ; { char name[20];
int month; int month;
int day; int day;
int year; int year;
}dateofbirth; }dateofbirth;
in structure, each member has different memory locations, while in union, it uses only single
memory location, it handles only one member at a time.

Difference between global variable and local variable ?


Local variables only exist inside th specific function that creates them. They are unknown to
other functions and main function. They stop to exist once the function that created them is
completed.
Global variables can be accessed by any function of that program.

#include <stdio.h>
int k_Global=10; // Global variable
main(){
int i; // local variable (local to main function)
for(i=0;i<1;i++){
int k_Local=1; // local variable (local to for loop function)
printf(“%d,%d\n”,k_Local,k_Global); // local and global are accessed same function
}
printf(“%d\n”,k_Local); // local variable of for loop can't be accessed here
printf(“%d\n”,k_Global); // Global variable can be accessed from any where.
}

What is static variable ?


The global static variable is same as ordinary glocal variable except that it can't be accessed
by other files. The local static variable is different from local variable. It is initialized only once no
matter how many times that function in which it resides is called.
e.g.
#include <stdio.h>
main(){
int i;
for(i=0;i<5;i++){
static int a=5; //it is initialized only once
printf(“%d\n”,++a);
}
}

What is the purpose of main() function ?


C program execution starts from main(). It may contain any no. of statements and these are
executed sequentially in the order in which the are written.
Main function can call other functions. When main calls a function, it passes the execution control
to that function. The function returns control to main when a return statement is executed or when
end of function is reached.

What is pass by value in functions?


In this method, the value of each of the actual arguments in the calling function is copied
into corresponding formal arguments of the called function. In this the changes made to the formal
arguments in called function won't change the values of the actual arguments in the calling
function.

Example:
#include <stdio.h>
void swap(int x, int y) {
int t;
t = x;
x = y;
y = t;
}
int main()
{
int m = 10, n = 20;
printf("Before executing swap m=%d n=%d\n", m, n);
swap(m, n);
printf("After executing swap m=%d n=%d\n", m, n);
return 0;
}
What is Pass by Reference
In this method, the addresses of actual arguments in the calling function are copied into formal
arguments of the called function. This means that using these addresses, we would have an access to
the actual arguments and hence we would be able to manipulate them. C does not support Call by
reference. But it can be simulated using pointers.

Example:
#include <stdio.h>
void swap(int *x, int *y) {
int t;
t = *x; /* assign the value at address x to t */
*x = *y; /* put the value at y into x */
*y = t; /* put the value at to y */
}
int main() {
int m = 10, n = 20;
printf("Before executing swap m=%d n=%d\n", m, n);
swap(&m, &n);
printf("After executing swap m=%d n=%d\n", m, n);
return 0;
}

What is recursion ?
A statement in a function calls the same function
e.g.
int fact(int n){
if (n<=0)
return 1;
else{
return (n*fact(n-1));
}
}

Swap without using temporary variable


#include <stdio.h> #include <stdio.h>
main(){ main(){
int i=1, j=100; // for any numbers int i=1, j=100; // only non zero no.s
i=i+j; i=i*j;
j=i-j; j=i/j;
i=i-j; i=i/j;
printf(“%d, %d\n”,i,j); printf(“%d, %d\n”,i,j);
} }

Print “hello world ” without using semicolon(;).


#include <stdio.h>
main(){
if( printf(“hello world\n”)){
}
}

ASCII
0-48, 1-49, ........................9-57, : -58, ; -59, < -60, = - 61, > -62, ?-63, @-64
A-65, B-66, .......................Z-90
a-97, b-98, .........................z=122

Print “ ; ” without using semicolon(;).


#include <stdio.h>
main(){
if(printf(“%c\n”,59)){
}
}

what is conditional expression ?


It is also known as terinory operator
(expression_1 ? expression_2 : expression_3)
if expression_1 is true, expression_2 is executed, otherwise expression_3 is executed.

e.g. #include <stdio.h>


main(){
int x;
printf(“enter a number\t”);
scanf(“%d”,&x);
(x>=0?(“%d is a non-negative number\n”,x ):printf(“%d is negative number \n”,x));
}

Determine the hierarchy of operations and evaluate the following expression?

I=2*3/4+4/4+8-2+5/8

i=6/4+4/4+8-2+5/8 operation: *
i=1+4/4+8-2+5/8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i=1+1+8-2+0 operation: /
i=2+8-2+0 operation: +
i = 10 - 2 + 0 operation: +
i=8+0 operation : -
i=8 operation: +

C uses PEMDAS order of precedence


Note that 6 / 4 gives 1 and not 1.5. This so happens because 6 and 4 both are integers and therefore
would evaluate to only an integer constant. Similarly 5 / 8 evaluates to zero, since 5 and 8 are
integer constants and hence must return an integer value.

What is pointer ?
Pointer is a varaible which strores the address of another variable.It's different from regular
variable which shows difference in arithematic operators like “ * ”, “%” .
A pointer will be declared as
int *p
int a=5
In the above, integer a is defined and declared with 5 and a pointer *p was declared.
Now to assign value for pointer : p=&a

Dereferencing Operator:
The ( p=&a ) means that pointer p is storing the address of the another varialble a. When
ever we need to access the value of the pointer will directly print it as printf(“%d”,*p) .The ” * ” is
known as dereferencing operator.

Arithematic Operator :
pointer arithematic is different from the ordinary arithematic operations
p=p+1

If you print now p value it won't print 6 because in pointers if we increase the value of pointer
variable that will increment the address of the variable by size of the data type based on operatin
system type.

Suppose if you are using a int type ,if you did an arithematic operation then the address will
incremented by 2 or 4 bytes (32,64 bit) based on operating system.

Advantages of pointers :
1) Pointers allow us to pass values to functions using call by reference. This is useful when large
sized arrays are passed as arguments to functions. A function can return more than one value by
using call by reference.

2) Dynamic memory allocation is possible with pointers (when ever you want to assign memory in
runtime)

3)We can resize data structures. For instance, if an array's memory is fixed, it cannot be resized. But
in case of an array whose memory is created out of malloc can be resized.

4)Pointers point to physical memory and allow quicker access to data.

Dynamic Memory allocation : ( malloc & calloc )


The above defined predefineded functions malloc () and calloc () are useful whenever there
is a nedd to assign memomy in runtime.
To make use of the functions we should use standard library with including stdlib.h

malloc():
used to allocate required number of bytes in memory at runtime. It takes one argument, i.e
size in bytes to be allocated.

Syntax:
void * malloc(size_t size);

Example:
a = (int*) malloc(4);
4 is the size (in bytes) of memory to be allocated.

calloc():
used to allocate required number of bytes in memory at runtime. It needs two arguments
1. total number of data and
2. size of each data.
Syntax:
void * calloc(1,2);

Example:
a = (int*) calloc(8, sizeof(int));
Here sizeof indicates the size of the data type and 8 indicates that we want to reserve space for
storing 8 integers.

realloc(): This function is used to increase or decrease the size of any dynamic memory which is
allocated using malloc() or calloc() functions.

Syntax:
void *realloc(void *ptr, size_t newsize);

The first argument 'ptr' is a pointer to the memory previously allocated by the malloc or calloc
functions. The second argument 'newsize' is the size in bytes, of a new memory region to be
allocated by realloc. This value can be larger or smaller than the previously allocated memory. The
realloc function adjusts the old memory region if newsize is smaller than the size of old memory.

Differences between Malloc() and Calloc() :

1) No of arguments differ
2)By default memory allocated by malloc contains Garbage values and for Calloc those will be
Zeros.

Pattern 1:

*
**
***
****
n=4 (here)

Approach:
As we can see the no. of rows should increase upto given 'n' and also for every row there is an
increment of no. of stars which is equal to the row number . So, there is a need of loop which
increments the row no. having an inner loop where stars are printed.
Program:
#include <stdio.h>
void main(){
int i,j,n;
printf(“Enter any number\t”);
scanf(“%d”,&n);
for(i=0; i<n; i++){
for(j=0; j<=i; j++){
printf(" * ");
}
printf("\n");
}
}

Pattern 2:

*
**
***
****
*****
n=5 (here)

Approach:
1. For the first row, see that there are 4 spaces at stars i.e., n-1 and also these spaces goes on
decrementing till the end.
2. For the first row, one '* ' is printed and for the second it's two and so on till given 'n'.
3. And totally for n rows we need an incrementing loop upto n which have inner loops of printing
spaces, stars.

Program:
#include <stdio.h>
void main(){
int i,j,k;
for(i=1; i<=n; i++){
for(j=1; j<=2*(n-i); j++){
printf(" ");
}
for(k=1; k<=i; k++){
printf("*");
}
printf("\n");
}
}

Pattern 3:

*
* *
* * *
** * *
* * *
* *
*

Approach:
1. First, divide the pattern into two parts, first part with first 4 rows is similar to problem2.
2. Then, for the second part just reverse the code by decrementing the variables instead of
incrementing them.
3. Just check for starting and ending point of each variable. According to that assign suitable values
to them and in/decrement accordingly.

Program:

#include <stdio.h>
void main(){
int i,j,k,samp=1;
for(i=1; i<=5; i++) {
for(k=samp; k<=5; k++){
printf(" ");
}
for(j=0; j< i; j++){
printf("*");
}
samp = samp + 1;
printf("\n");
}
samp = 1;
for(i=4; i>=1; i--){
for(k=samp; k>=0; k--){
printf(" ");
}
for(j=i; j>=1; j--){
printf("*");
}
samp = samp + 1;
printf("\n");
}
}

Prime Number :
Approach:
If a number is divisible only by 1 and by its own ,then the no is known as Prime number.
So to check the prime no ,one should check the divisibility of the number by the numbers less than
to that number.
Program :

#include <stdio.h>
main()
{
int n, i, c = 0;
printf("Enter any number n: \n");
scanf("%d", &n);
/*logic*/
for (i = 1; i <= n; i++) {
if (n % i == 0) c++;
}
if (c == 2) printf("n is a Prime number");

else printf("n is not a Prime number");

Palindrome (Number):
If a number/string, which when read in both forward and backward way is same, then such a
number is called a palindrome.

Approach :
1) Reverse the given number in order to check it with the given number
2) Obtain each digit from right by dividing by 10 and getting remainder.
3) This number should be multiplied by 10 and next digit should be added to it.
4) It goes on till last digit is considered.

Program:

#include <stdio.h>
int main()
{
int n, n1, rev = 0, rem;
printf("Enter any number: \n");
scanf("%d", &n);
n1 = n;
while (n > 0){
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
if (n1 == rev) printf("Given number is a palindromic number");

else printf("Given number is not a palindromic number");


}

Palindrome (String):
Approach:
1)Characters from left should be same as characters from right of that string.
2)Loop is to be created that checks equality between characters from left and from right.
3)If any equality fails, it is not a palindrome.
Program:

#include <stdio.h>
#include <string.h>
int main()
{
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: \n");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++){
if(string1[i] != string1[length-i-1]){
flag = 1;
break;
}
}
if (flag) printf("%s is not a palindrome\n", string1);

else printf("%s is a palindrome\n", string1);


}

Factorial:
Approach:
1) A factorial is a number that is obtained by multiplying a number with all the natural numbers less
than that number.
2)So create a function, which multiplies the given number with the same function of a number 1
less to it.
3)Output of the function of last number is to be defined such that the recursion ends here.
Program:
#include <stdio.h>
int fact(int n);
int main(){
int x, i;
printf("Enter a value for x: \n");
scanf("%d", &x);
i = fact(x);
printf("\nFactorial of %d is %d", x, i);
}
int fact(int n) {
if (n <= 0) {
return (1);
}
else {
return (n * fact(n - 1));
}
}

Fibonacci series:
Any number in the series is obtained by adding the previous two numbers of the series.
Approach:
1)Create a function, which adds the given number with the same function of a number 1 less to it.
2)Output of the function of last number is to be defined such that the recursion ends here.
Program:

#include<stdio.h>
int main()
{
int i, fib[25],n;
fib[0] = 0;
fib[1] = 1;
printf(“enter the no of Fibonacci numbers you want :”);
scanf(“%d”,&n);
for (i = 2; i < n; i++)
{
fib[i] = fib[i - 1] + fib[i - 2];
}
printf("The fibonacci series is as follows \n");
for (i = 0; i < 10; i++) {
printf("%d \n", fib[i]);
}
}

Angstrom number:
Approach:
1)Obtain each digit from right side of the number by dividing with 10 and getting remainder.
2)Cube each obtained digit and add them to a variable
3)Check the output with the given number

Program:
#include <stdio.h>
#include <math.h>
main(){
int no,a,b,count,i;
printf(“Enter three digit number”);
scanf(“%d”,&no);
b=0,count=no;
for(i=0;i<3;i++){
a=count%10;
count=count/10;
b+=pow(a,3);
}
}
if (b==no) printf(“Its a Aungstome No\n”);
else printf(“Its not an Aungstrome No\n”);
}

Perfect Number:
Sum of all the factors of a number except itself is equal to that number
Approach:
1)Check divisibility of the given number with all the numbers less than this.
2)Sum all the factors to a given variable
3)Check the sum with the given number.
Program:
#include <stdio.h>
#include <math.h>
main()
{
int no,i,a;
no=6;
for(i=1;i<no;i++){
if ((no%i)==0) a+=i;
}
if (a==no) printf(“%d is the perfect no\n”,no);
else printf(“%d is not the perefect no\n”,no);
}

Even /Odd Number:


Program:
#include <stdio.h>
main(){
int n;
printf(“enter a number\t”);
scanf(“%d”,&n);
(n%2?printf(“Even\n”):printf(“Odd”));
}

Minimum/Maximum :
Approach:
1)Consider first number as maximum/minimum.
2)Create a loop that checks the maximum/minimum with each number of the array
3)if condition is true, assign the particular value to that maximum/minimum and loop continues.
Program:
#include<stdio.h>
main()
{
a[100],count,i,j,max,min;
printf(“enter the no of elemets \t”);
scanf(“%d”,count);
for(i=0;i<count;i++)
{
scanf(“%d”,&a[i]);
}
max=min=a[0];
for(j=0;j<count;j++)
{
if ( a[j] > max) max=a[j];
if ( a[j] < min ) min=a[j];
}
printf(“%d is the maximum”,max);
printf(“%d is the minimum”,min);
}

Das könnte Ihnen auch gefallen