Showing posts with label Functions. Show all posts
Showing posts with label Functions. Show all posts

Monday, February 15, 2021

C program to find square of given number without an argument and a return value

C Programming => Functions

C program to find square of given number using function concept. This program demonstrate use of function without an argument and a return value.

Program code

#include<stdio.h>
int square(); //function prototype declaration.
int number; //use of global variable

int main()
{
  int answer;
  answer = square(); //Call function.
  printf("Square of %d is %d.", number, answer);
  return 0;
}

//User defined function to find square()
int square()
{
  printf("Enter your number:");
  scanf("%d", &number);
  //return answer to main function
  return(number*number);
}

Output of the program

Enter your number:5
Square of 5 is 25.





Monday, October 22, 2018

Login Check Function


User Authentication (Login Check Function)

This C program will check the User ID and Password entered by user with the UserID and Password stored into login.txt file. Each line of login.txt contains UserID Password of one user. 

Sample login.txt file contains data of 5 users which are as under:

101 abc123
102 guest
103 hi
guest guest
admin admin

Make sure that each user ID and Password is separated by space.

#include<stdio.h>

int Login_check(char id[], char pass[]);

int main()
{
 int check=0;
 char id[20], pass[20];
 printf("Enter your User ID:");
 scanf("%s", id);

 printf("Enter your Password:");
 scanf("%s", pass);

 check = Login_check(id, pass);

 if (check==1)
   printf("\nLogin successful...\n\nDisplay Menu Here...\n");
   //write main program logic here...  
 else
   printf("\nLogin failed. Try again...\n");

 return 0;
}

int Login_check(char id[], char pass[])
{
 FILE *fp;
 char *fid, *fpass, *token;
 int check=0;
 const char str[40] = "", s[2] = " ";

 fp = fopen("login.txt", "r");

 if(fp==NULL) 
 {
   printf("File error..."); exit(0);
 }
 while(fgets(str, 40, fp)!=NULL)
 {
   fid = strtok(str,s);
   fpass = strtok(NULL,s);
   fpass[strlen(fpass)-1]='\0';

   if((strcmp(id,fid) == 0) && (strcmp(pass,fpass) == 0 ))
   {
     check=1;
   }
 }
 return check;
}

Output of Program

Enter your User ID:guest
Enter your Password:guest

Login successful...

Display Menu Here...


Monday, June 25, 2018

Special Program - What's wrong?


What's wrong with this program?

Check your output...it's not as per your expectation!!!



#include<stdio.h>

void State_Guj_print(){
    printf("State - Gujarat India.\n");
}

void State_Maha_print(){
    printf("State - Maharastra India\n");

}
void State_Madhya-Prad_print(){
    printf("State - Madhya Pradesh India\n");
}

int main()
{
    int num;
    printf("Enter the number [1-3]:\n");
    scanf("%d",&num);
    switch(num)
    {
      case 1:
             State_Guj_print();
             break;
      case 2:
             State_Maha_print();
             break;
      case 3:
             State_Madhya-Prad_print();
             break;
      default:
             printf("Enter only number 1 to 3.\n");
             break;
    }
    return 0;
}
/*
Do share your answer in comments...
*/

Sunday, May 21, 2017

Global variables

Global variables are available throughout the C program and may be used by any function and part of a program. Also, their value can be used in any part of C program during execution. We can create global variables by declaring them outside of any function. Generally we declare global variables in the beginning of C program. In the following program, the variable percentage is declared outside of all functions. We can use percentage in all function including main().

#include <stdio.h>
//Declaration of global variables.
int maths, science, english;
float percentage;

void result(void);
void display(void);

int main(void)
{
printf("Enter Subject Marks out of 100.\n");
printf("-------------------------------\n");
printf("Enter Marks of Maths:");
scanf("%d",&maths);
printf("Enter Marks of Science:");
scanf("%d",&science);
printf("Enter Marks of English:");
scanf("%d",&english);

result();
display();

return 0;
}
void result(void)
{
percentage = (maths+science+english)*100/300;
}
void display(void)
{
printf("Your percentage is %.2f.", percentage);
}

Output of Program

Enter Subject Marks out of 100.
-------------------------------
Enter Marks of Maths:80
Enter Marks of Science:90
Enter Marks of English:85
Your percentage is 85.00.

Monday, March 13, 2017

Check Prime number using C function.

A prime number is a positive integer which is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13


#include <stdio.h>
int checkPrime(int number);

int main()
{
    int n, flag;

    printf("Enter a positive integer: ");
    scanf("%d",&n);
if(n <= 0)
{
printf("Enter positive number only.");
exit(0);
}
//Function call...
flag = checkPrime(n);    

    if (flag==1)
        printf("%d is a prime number.",n);
    else
        printf("%d is not a prime number.",n);
    return 0;
}
//Function to check prime number int checkPrime(int number)
{
int i, flag=1;
for(i=2; i<=number/2; ++i)
    {
        //checks nonprime number
        if(number%i==0)
        {
            flag=0;
            break;
        }
    }
return(flag);
}


Output of program

Run-1

Enter a positive integer: 13
13 is a prime number.

Run-2

Enter a positive integer: 10
10 is not a prime number.

Run-3

Enter a positive integer: -5
Enter positive number only.


Monday, February 20, 2017

Random between 0 to 100.

#include <stdio.h>
#include <stdlib.h>
int main()
{
   int i;
   time_t my_sys_time;
   //To set random number generator as per system time 
   srand((unsigned) time(&my_sys_time));

   //To print 10 random numbers from 0 to 100
   for( i = 0 ; i < 10 ; i++ ) 
   {
      printf("%d ", rand()%100);
   }
   return(0);
}
Output of program
16 45 14 21 60 18 65 3 41 34

Monday, October 10, 2016

C program to print text at given position on screen.



C program to print text at given position on screen.

#include <windows.h>
#include<stdio.h>
#include<conio.h>
COORD c = {0, 0};

void setxy (int x, int y)
{
 c.X = x; c.Y = y; // Set X and Y coordinates
 SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}

int main()
{
 int x, y, rollno;
 char name[10];

 printf("Enter your Roll No.:");
 scanf("%d", &rollno);

 printf("Enter your name:");
 scanf("%s", name);

 printf("Where you want to print on Screen?\n");
 printf("Enter your X coordinate:");
 scanf("%d", &x);

 printf("Enter your Y coordinate:");
 scanf("%d", &y);

 setxy(x,y);
 printf("Your Roll No. is %d.", rollno);

 setxy(x,y+1); //add 1 in y to print at new line
 printf("Your Name is %s.", name);

 return 0;
}



Output of the program:

Enter your Roll No.:101
Enter your name:Purva
Where you want to print on Screen?
Enter your X coordinate:10
Enter your Y coordinate:10





          Your Roll No. is 0.
          Your Name is Purva.



Saturday, October 8, 2016

C program to implement Stack using array.



#include<stdio.h>
void push();
void pop();
void display_stack();
int stack_pointer=0, stack[10];

int main()
{
  int n;
  do{
      printf("===== Stack Operation =====\n");
      printf("1. Push\n2. Pop\n3. Display Stack\n4. Exit\n");
      printf("Enter your choice:");
      scanf("%d", &n);
      switch(n){
        case 1: push();
                if(stack_pointer>=10)
                {
                  printf("Stack is full.\n");
                  exit(0);
                }
                break;
        case 2: pop();
                break;
        case 3: display_stack();
                break;
        case 4: printf("Thank you. Have a nice time..");
                break;
        default:
                printf("Select proper menu item.\n");
        }
  }while(n != 4);
  return 0; 
}
void push(){
   printf("\nPush Operation\n");
   printf("--------------\n");
   printf("Enter number to be pushed:");
   scanf("%d", &stack[stack_pointer++]);
   printf("Push Operation performed.\n");
   printf("-------------------------\n\n");
}
void pop(){
   printf("\nPop Operation performed.\n");
   printf("------------------------\n");
   printf("Popped out element from stack is %d\n\n", stack[stack_pointer-1]);
   stack_pointer--;
   getch();//developed by kp
}
void display_stack(){
   int i;
   if(stack_pointer==0)
       printf("Stack is empty.\n\n");
   else
   {
       printf("\nStack Elements are as under:\n");
       printf("----------------------------\n");
       for(i=0; i<stack_pointer; i++)
       {
           printf("%d\n", stack[i]);
       }
   }
   printf("\nPress any key to continue...\n\n");
   getch();//cprogrampracticals.blogspot.in
}


Output of the program:

===== Stack Operation =====
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice:1

Push Operation
--------------
Enter number to be pushed:5
Push Operation performed.
-------------------------

===== Stack Operation =====
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice:1

Push Operation
--------------
Enter number to be pushed:10
Push Operation performed.
-------------------------

===== Stack Operation =====
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice:3

Stack Elements are as under:
----------------------------
5
10

Press any key to continue...

===== Stack Operation =====
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice:2

Pop Operation performed.
------------------------
Popped out element from stack is 10

===== Stack Operation =====
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice:4
Thank you. Have a nice time..

Sunday, October 2, 2016

C function with an argument and no return value.


//C function with an argument and no return value.

#include<stdio.h>

void print_line(int);

int main()
{
     print_line(2);  //this will pass 2 two print_line() function
    
     printf("Hello World\n");
    
     print_line(3);  //this will pass 3 two print_line() function
    
     return 0; 
}

void print_line(int n)
{
     int i;
     for(i=0; i<n; i++)
     {
           printf("------------\n"); 
     }
}


Output of the program:

------------
------------
Hello World
------------
------------
------------


C function with no arguments and no return value.


//C Function with no arguments and no return value.

#include<stdio.h>

void print_line();

void main()
{
     print_line();
    
     printf("Hello World\n");
    
     print_line();
}
//void in the function indicates no return value. 
void print_line() 
{
     printf("------------\n");
}


Output of the programs:

------------
Hello World
------------

Friday, September 30, 2016

Factorial of given number using recursive function.

Recursive Function

The function which calls itself is called recursive function.


Factorial of given number using recursive function.



#include <stdio.h>
int factorial(int);

int  main() {
   int number;
  
   printf("Enter your number:");
   scanf("%d", &number);
  
   printf("Factorial of %d is %d\n", number, factorial(number));
   return 0;
}
int factorial(int i)
{
   if(i<=1) {
      return 1;
   }
   return (i*factorial(i-1));
}


Output of the program

Enter your number:5
Factorial of 5 is 120


Use of built-in C string library function.


// Use of built-in C string library function.

#include<stdio.h>
int main()
{
     int len;
     char str1[10], str2[10];
    
     puts("Enter String 1:");
     gets(str1);
    
     puts("Enter String 2:");
     gets(str2);
    
     //Function to find length of given string 1.
     len = strlen(str1);
     printf("\nLength of String 1 is %d.\n", len);
    
     //Function to compare two strings
     if(strcmp(str1,str2)==0)
           printf("\nString 1 and String 2 are same.\n");
     else
           printf("\nString 1 and String 2 are not same.\n");
          
     //Function to copy string 1 into string 2
     strcpy(str2,str1); //this will copy str1 into str2
     printf("\nString 2 after execution of strcpy = %s", str2);
    
     return 0;
}


Output of the program:

/*Output
Enter String 1:
abc
Enter String 2:
xyz

Length of String 1 is 3.

String 1 and String 2 are not same.

String 2 after execution of strcpy = abc
*/

Thursday, September 29, 2016

Square of given number using function with an argument and a return value.

/* C program to find square of given number using function.
Use of function with an argument and a return value.
*/
#include<stdio.h>

int square(int); // function prototype declaration.

void main()
{
     int number, answer;
    
     printf("Enter your number:");
     scanf("%d", &number);
    
     answer = square(number);  //Call function.
    
     printf("Square of %d is %d.", number, answer);
}

int square(int n)
{
     //function logic is written here..
     return(n*n); //This will return answer to main function.
}



Output of the Program:

Enter your number:5
Square of 5 is 25. 

Friday, April 29, 2016

C program to show use of User Defined Functions.


This program demonstrate use of FindAverage() function.

#include<stdio.h>
void FindAverage(); // function prototype declaration.
int main()
{
     FindAverage(); //Call function.
     return 0;
}

void FindAverage()
{
     //function logic is written here..
     float num1, num2;
    
     printf("Enter number1: ");
     scanf("%f",&num1);
    
     printf("Enter number2: ");
     scanf("%f",&num2);
    
     printf("Average of two numbers: %f.", (num1+num2)/2);    
}
//Output
Enter number1: 10
Enter number2: 20

Average of two numbers: 15.000000.

C program to show use of sqrt() Library Functions.

This program demonstrate use of two library function:
--> sqrt()
--> printf()
*/
#include<stdio.h>
#include<math.h>
void main()
{
     float ans;
     ans = sqrt(100);
    
     printf("The square root of 100 is %f.", ans);  
}
//Output
The square root of 100 is 10.000000.