Showing posts with label positive. Show all posts
Showing posts with label positive. Show all posts

Wednesday, 15 April 2020

C++ Program - Check Number is Positive or Negative

Q: Write a program to check whether the given number is positive or negative (using ? : ternary operator )
Solution:

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
 int a;
 cout<<"Enter any non-zero Number : ";
 cin>>a;
 (a>0)?cout<<"Number is positive":cout<<"Number is negative";
 return 0;
}

Screenshot:
 

Saturday, 7 December 2019

Mini-program: Write a console program that prompts the user for an integer.

Q: Mini-program: Write a console program that prompts the user for an integer. As long as the user keeps entering positive integers, continue prompting for the next integer. Once the user enters an integer of 0 or less, report the largest integer that was entered and end the program.

Solution:

save it as test.c and in linux or ubuntu
Please run it using command : gcc -o test test.c
                                                        :./test
#include <stdio.h>
void main(){
int i;
int big=0;
printf("enter number : ");
scanf("%d",&i);
while(1){
printf("enter number : ");
if(i>0) {if(i>big) big=i;}
else {printf("largest number entered : %d\n",big);
return;}
scanf("%d",&i);}
}

Write a console program that prompts the user for an integer.

Q: Mini-program: Write a console program that prompts the user for an integer. As long as the user keeps entering positive integers, continue prompting for the next integer. Once the user enters an integer of 0 or less, report the largest integer that was entered and end the program.

Solution:


import java.util.ArrayList;
import java.util.Scanner;

public class LargestNumber

{
public static void main(String args[])
{
int ending=0;
ArrayList<Integer> list=new ArrayList<Integer>();/* declare arrylist to store the value*/
int value=1;
while(value>0)
{
System.out.println("Please Enter the number");/* promt the user to give the number*/
Scanner in=new Scanner(System.in);
value=in.nextInt();/* store the entered value */
ending =value;
if(value>0){/* check if the value is greater than zero than only it will store*/
list.add(value);
}
 
}
int max=0;
for(int i=0;i<list.size();i++)
{
if(list.get(i).intValue()>max)
max=list.get(i).intValue();
 
}
System.out.println("----------------------------------------");
System.out.println("largest number is=");/* print the largest number*/
System.out.println(max);
}
}